All files / src get-diff-message.js

86.36% Statements 19/22
84% Branches 21/25
100% Functions 7/7
85.71% Lines 18/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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    5x 1x             19x 4x     15x 10x     5x 5x                         7x     1x   4x   6x   3x                               20x 7x       7x       13x 13x          
import { isElement, isTextNode } from './parse5-utils';
 
export const isAttribute = arg => arg && 'name' in arg && 'value' in arg;
const { isArray } = Array;
 
/**
 * @param {ASTNode | Attribute} arg
 * @returns {string} the human readable diff identifier
 */
function getIdentifier(arg) {
  if (isTextNode(arg)) {
    return `text "${arg.value}"`;
  }
 
  if (isElement(arg)) {
    return `tag <${arg.tagName}>`;
  }
 
  Eif (isAttribute(arg)) {
    return arg.value
      ? `attribute [${arg.name}="${arg.value}"]`
      : `attribute [${arg.name}]`;
  }
 
  throw new Error(`Unknown arg: ${arg}`);
}
 
/**
 * Asserts that the diff is an array diff, returns type assertions to remove optional props.
 * @returns {boolean}
 */
function isArrayDiff(diff) {
  return diff.kind === 'A' && !!diff.item && typeof diff.index === 'number';
}
 
const messageTemplates = {
  // New diff
  N: (diff, lhs, rhs) => `${getIdentifier(rhs)} has been added`,
  // Edit diff
  E: (diff, lhs, rhs) => `${getIdentifier(lhs)} was changed to ${getIdentifier(rhs)}`,
  // Delete diff
  D: (diff, lhs) => `${getIdentifier(lhs)} has been removed`,
};
 
/**
 * Generates a human understandable message for a HTML diff.
 *
 * @param {object} diff The diff
 * @param {object | object[]} lhs The left hand side diffed object.
 *  Can be a HTML ASTNode or an Attribute.
 * @param {object | object[]} rhs The left hand side diffed object.
 *  Can be a HTML ASTNode or an Attribute.
 *
 * @returns the message
 */
export function getDiffMessage(diff, lhs, rhs) {
  // Array diff
  if (isArray(lhs) || isArray(rhs)) {
    Iif (!isArrayDiff(diff) || !isArray(lhs) || !isArray(rhs)) {
      throw new Error('Not all arguments are array diffs');
    }
 
    return getDiffMessage(diff.item, lhs[diff.index], rhs[diff.index]);
  }
 
  // Non-array diff
  Eif (diff.kind in messageTemplates) {
    return messageTemplates[diff.kind](diff, lhs, rhs);
  }
 
  throw new Error(`Unknown diff kind: ${diff.kind}`);
}