'use strict'; import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer } from '@angular/platform-browser'; function isBlank(obj) { return obj === undefined || obj === null; } var level = 1; const COLLAPSE_LEVEL = 2; @Pipe({ name: 'jsonFormatter' }) export class JsonFormatter implements PipeTransform { constructor(private sanitizer: DomSanitizer) {} transform(value) { if (isBlank(value)) return value; return this.sanitizer.bypassSecurityTrustHtml(jsonToHTML(value)); } } function htmlEncode(t) { return t != undefined ? t.toString().replace(/&/g, '&').replace(/"/g, '"').replace(//g, '>') : ''; } function decorateWithSpan(value, className) { return '' + htmlEncode(value) + ''; } function valueToHTML(value) { var valueType = typeof value, output = ''; if (value == undefined) { output += decorateWithSpan('null', 'type-null'); } else if (value && value.constructor === Array) { level++; output += arrayToHTML(value); level--; } else if (value && value.constructor === Date) { output += decorateWithSpan('"' + value.toISOString() + '"', 'type-string'); } else if (valueType === 'object') { level++; output += objectToHTML(value); level--; } else if (valueType === 'number') { output += decorateWithSpan(value, 'type-number'); } else if (valueType === 'string') { if (/^(http|https):\/\/[^\s]+$/.test(value)) { output += decorateWithSpan('"', 'type-string') + '' + htmlEncode(value) + '' + decorateWithSpan('"', 'type-string'); } else { output += decorateWithSpan('"' + value + '"', 'type-string'); } } else if (valueType === 'boolean') { output += decorateWithSpan(value, 'type-boolean'); } return output; } function arrayToHTML(json) { var collapsed = level > COLLAPSE_LEVEL ? 'collapsed' : ''; var i, length; var output = '
[]'; if (!hasContents) { output = '[ ]'; } return output; } function objectToHTML(json) { var collapsed = level > COLLAPSE_LEVEL ? 'collapsed' : ''; var i, key, length, keys = Object.keys(json); var output = '
{}'; if (!hasContents) { output = '{ }'; } return output; } function jsonToHTML(json) { level = 1; var output = ''; output += '
'; output += valueToHTML(json); output += '
'; return output; }