All files / lib printer.js

98.08% Statements 204/208
84.78% Branches 78/92
100% Functions 10/10
97.98% Lines 194/198
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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300    1x 1x 1x     1x 1x 1x     1x     1x       1x   80x 80x 80x 80x       467x 860x 430x 430x 430x   467x       117x 117x 1x 1x 1x   232x 116x 116x 116x   234x 117x 117x 117x   232x 116x 116x 116x   117x       18x 18x 11x 10x 12x 10x 10x   8x     72x 18x 18x 18x 18x 18x 18x 18x     18x 18x 18x 18x       883x     883x   883x 752x   883x 19x   883x   883x 99x 99x 99x     99x 99x   99x   81x 81x   81x   81x 81x 81x 81x   98x 49x 49x 49x     81x 81x 160x 80x 80x 80x 80x 80x     81x 84x 84x 84x 84x 84x 28x   56x     84x 12x 6x 6x 6x 6x 6x 6x   6x   130x 130x 176x 88x 88x 88x 88x 88x   88x 88x 87x 87x 87x 84x 3x 3x   87x                   87x 87x 3x     88x 88x   88x 12x 6x           6x 6x 6x 6x 6x 6x   6x   7x 7x   179x 179x   3x 3x   2x 2x 36x 18x 18x 18x 18x 17x   18x 18x   18x 1x 1x   1x 1x 1x 1x       1x 1x     18x 18x     18x 1x 1x 1x 1x   1x 2x 1x 1x   1x   1x   41x 41x   41x   1x 1x   1x 1x       232x 116x 116x 116x   116x 38x 19x 19x 19x       883x    
/* eslint no-use-before-define: ["error", { "functions": false }] */
/* eslint no-param-reassign: [0, { "ignorePropertyModificationsFor": ["lastLoc"] }] */
import merge from 'deepmerge';
import { reduce } from 'underscore';
import {
  builders as b,
} from 'glimmer-engine/dist/node_modules/glimmer-syntax';
import isSelfClosing from './utils/is-self-closing';
import escapeHTML from './utils/escape-html';
import whitespaceDiff, {
  locToWhitespace,
} from './utils/whitespace-diff';
import {
  sortNodes as sort,
} from './utils/node';
import {
  locAppend,
} from './utils/location';
 
const defaults = { quotes: { mustache: '"' } };
 
export default function print(ast, options = {}) {
  const optionsWithDefault = merge(defaults, options);
  const lastLoc = b.loc(1, 0, 1, 0);
  return build(ast, lastLoc, optionsWithDefault).output.join('');
}
 
function buildEach(asts, lastLoc, options) {
  const output = [];
  asts.forEach((node) => {
    const { output: out, lastLoc: loc } = build(node, lastLoc, options);
    output.push(...out);
    lastLoc = loc;
  });
  return { lastLoc, output };
}
 
function pathParams(ast, lastLoc, options) {
  const output = [];
  if (ast.name) {
    const { output: name, lastLoc: nameLoc } = build(ast.name, lastLoc, options);
    output.push(...name);
    lastLoc = nameLoc || lastLoc;
  }
  if (ast.path) {
    const { output: path, lastLoc: pathLoc } = build(ast.path, lastLoc, options);
    output.push(...path);
    lastLoc = pathLoc || lastLoc;
  }
  Eif (ast.params) {
    const { output: params, lastLoc: paramsLoc } = buildEach(ast.params, lastLoc, options);
    output.push(...params);
    lastLoc = paramsLoc || lastLoc;
  }
  if (ast.hash) {
    const { output: hash, lastLoc: hashLoc } = build(ast.hash, lastLoc, options);
    output.push(...hash);
    lastLoc = hashLoc || lastLoc;
  }
  return { output, lastLoc };
}
 
function blockParams(block, lastLoc) {
  const params = block.program.blockParams;
  if (params.length) {
    const spaced = reduce(params, (acc, p) => acc.concat([p, ' ']), []);
    spaced.splice(-1, 1);
    const length = reduce(spaced, (acc, p) => acc + p.length, 0);
    lastLoc = locAppend(lastLoc.end, { column: length + 5 });
    return { lastLoc, output: [' as |', ...spaced, '|'] };
  }
  return { lastLoc, output: [] };
}
 
function openBlock(block, lastLoc, options) {
  lastLoc = locAppend(lastLoc.start, { column: 3 }); // {{#
  const { output: path, lastLoc: pathLoc } = pathParams(block, lastLoc, options);
  lastLoc = pathLoc;
  const { output: params, lastLoc: paramsLoc } = blockParams(block, lastLoc, options);
  lastLoc = paramsLoc;
  lastLoc = locAppend(lastLoc.end, { column: 2 }); // }}
  return { lastLoc, output: ['{{#', ...path, ...params, '}}'] };
}
 
function closeBlock(block, lastLoc, options) {
  lastLoc = locAppend(lastLoc.start, { column: 3 }); // {{/
  const { output: path } = build(block.path, lastLoc, options);
  return ['{{/', ...path, '}}'];
}
 
function build(ast, lastLoc, options) {
  Iif (!ast) {
    return '';
  }
  const output = [];
 
  if (ast.loc && !ast.skipInitialWhitespace) {
    output.push(whitespaceDiff(lastLoc, ast.loc));
  }
  if (ast.skipInitialWhitespace) {
    delete ast.skipInitialWhitespace;
  }
  lastLoc = ast.loc || lastLoc;
 
  switch (ast.type) {
    case 'Program': {
      const chainBlock = ast.chained && ast.body[0];
      Iif (chainBlock) {
        chainBlock.chained = true;
      }
      const { output: body } = buildEach(ast.body, lastLoc, options);
      output.push(...body);
    }
      break;
    case 'ElementNode': {
      const selfClosing = isSelfClosing(ast.tag);
      const attrNodes = sort(ast.attributes, ast.modifiers, ast.comments);
 
      output.push('<', ast.tag);
 
      let loc = lastLoc;
      const tagLength = ast.tag.length;
      const tagLoc = locAppend(loc.start, { column: tagLength + 1 });
      loc = tagLoc;
 
      if (attrNodes.length) {
        const { output: attrs, lastLoc: attrsLoc } = buildEach(attrNodes, loc, options);
        output.push(...attrs);
        loc = attrsLoc;
      }
 
      output.push('>');
      loc = locAppend(loc.end, { column: 1 }); // >
      if (!selfClosing) {
        const { output: children, lastLoc: childLoc } = buildEach(ast.children, loc, options);
        output.push(...children);
        output.push('</', ast.tag, '>');
        loc = locAppend(childLoc.end, { column: 3 + ast.tag.length }); // </tag>
        lastLoc = loc;
      }
    }
      break;
    case 'AttrNode': {
      output.push(ast.name, '=');
      const loc = locAppend(lastLoc.start, { column: ast.name.length + 1 });
      const { output: value } = build(ast.value, loc, options);
      if (ast.value.type === 'TextNode') {
        output.push('"', ...value, '"');
      } else {
        output.push(...value);
      }
    }
      break;
    case 'ConcatStatement': {
      output.push('"');
      const { output: parts, lastLoc: partsLoc } = buildEach(ast.parts, lastLoc, options);
      output.push(...parts);
      output.push('"');
      lastLoc = b.loc(partsLoc);
      lastLoc.end.column += 1; // "
    }
      break;
    case 'TextNode':
      output.push(escapeHTML(ast.chars));
      break;
    case 'MustacheStatement': {
      const open = ast.escaped ? '{{' : '{{{';
      const close = ast.escaped ? '}}' : '}}}';
      let loc = locAppend(lastLoc.start, { column: open.length }); // {{ or {{{
      const { output: out, lastLoc: pathLoc } = pathParams(ast, loc, options);
      loc = locAppend(pathLoc.end, { column: close.length + 1 }); // }} or }}}
 
      let whitespace = '';
      if (ast.loc && loc) {
        const lineDiff = ast.loc.end.line - loc.end.line;
        let columnDiff = 0;
        if (lineDiff === 0) {
          columnDiff = ast.loc.end.column - loc.end.column;
        } else Eif (lineDiff > 0) {
          columnDiff = ast.loc.end.column - 2;
        }
        const offset = {
          start: {
            line: 0,
            column: 0,
          },
          end: {
            line: lineDiff,
            column: columnDiff,
          },
        };
        whitespace = locToWhitespace(offset);
        if (whitespace) {
          loc = ast.loc;
        }
      }
      output.push(open, ...out, whitespace, close);
      lastLoc = loc;
    }
      break;
    case 'MustacheCommentStatement': {
      const contentLength = ast.value.length;
      const {
        loc: {
          start: { column: start },
          end: { column: end },
        },
      } = ast;
      const nodeLength = end - start;
      const diff = nodeLength - contentLength;
      const open = diff > 5 ? '{{!--' : '{{!';
      const close = diff > 5 ? '--}}' : '}}';
      output.push(open, ast.value, close);
    }
      break;
    case 'ElementModifierStatement':
      output.push('{{', ...pathParams(ast, lastLoc, options).output, '}}');
      break;
    case 'PathExpression':
      output.push(ast.original);
      break;
    case 'SubExpression':
      output.push('(', ...pathParams(ast, lastLoc, options).output, ')');
      break;
    case 'BooleanLiteral':
      output.push(ast.value ? 'true' : false);
      break;
    case 'BlockStatement': {
      const { output: open } = openBlock(ast, lastLoc, options);
      output.push(...open);
      const firstBodyNode = ast.program.body[0];
      if (firstBodyNode) {
        firstBodyNode.skipInitialWhitespace = true;
      }
      const { output: program } = build(ast.program, lastLoc, options);
      output.push(...program);
 
      if (ast.inverse) {
        Eif (!ast.inverse.chained) {
          output.push('{{else}}');
        }
        const firstInverseNode = ast.inverse.body[0];
        ast.inverse.skipInitialWhitespace = true;
        Eif (firstInverseNode) {
          firstInverseNode.skipInitialWhitespace = true;
        }
        const {
          output: inverse,
        } = build(ast.inverse, ast.inverse.loc, options);
        output.push(...inverse);
      }
 
      Eif (!ast.chained) {
        output.push(...closeBlock(ast, lastLoc, options));
      }
    }
      break;
    case 'PartialStatement': {
      const loc = locAppend(lastLoc.start, { column: 3 }); // {{>
      const { output: params } = pathParams(ast, loc, options);
      output.push('{{>', ...params, '}}');
    }
      break;
    case 'CommentStatement': {
      output.push('<!--', ast.value, '-->');
      const { line, column } = lastLoc.end;
      // TODO: multiline comments
      lastLoc = b.loc(line, column, line, column + ast.value.length + 7);
    }
      break;
    case 'StringLiteral': {
      const quote = options.quotes.mustache;
      output.push(quote, ast.value, quote);
    }
      break;
    case 'NumberLiteral':
      output.push(ast.value);
      break;
    case 'UndefinedLiteral':
      output.push('undefined');
      break;
    case 'NullLiteral':
      output.push('null');
      break;
    case 'Hash': {
      const { output: pairs, lastLoc: loc } = buildEach(ast.pairs, lastLoc, options);
      output.push(...pairs);
      lastLoc = loc;
    }
      break;
    case 'HashPair': {
      const { output: value, lastLoc: loc } = build(ast.value, lastLoc, options);
      output.push(ast.key, '=', ...value);
      lastLoc = loc;
    }
    // no default
  }
  return { lastLoc, output };
}