Skip to content

Instantly share code, notes, and snippets.

@d6u
Last active October 24, 2016 20:22
Show Gist options
  • Select an option

  • Save d6u/9f1cbdb9f320caa88ec7b407d26185e5 to your computer and use it in GitHub Desktop.

Select an option

Save d6u/9f1cbdb9f320caa88ec7b407d26185e5 to your computer and use it in GitHub Desktop.
import sax = require('sax');
/**
* Beautify HTML for human
*/
export function beautify(html: string) {
return new Promise((resolve, reject) => {
const parser = sax.parser(false, {});
let indent = 0;
let result = '';
parser.onopentag = function (tag) {
if (isSelfClosing(tag.name)) {
result += `${getTabs(indent)}<${tag.name.toLowerCase()}${getAttrs(tag.attributes)}/>\n`;
} else {
result += `${getTabs(indent)}<${tag.name.toLowerCase()}${getAttrs(tag.attributes)}>\n`;
indent += 1;
}
};
parser.ontext = function (text) {
// console.log('ontext', JSON.stringify(text));
};
parser.onscript = function (script) {
// console.log('onscript', JSON.stringify(script));
};
parser.onclosetag = function (tagName) {
if (!isSelfClosing(tagName)) {
indent -= 1;
result += `${getTabs(indent)}</${tagName.toLowerCase()}>\n`;
}
};
parser.onerror = function (err) {
reject(err);
};
parser.onend = function () {
resolve(result);
};
parser.write(html);
parser.close();
});
}
function getTabs(n: number) {
let i = 0;
let r = '';
while (i < n) {
i += 1;
r += ' ';
}
return r;
}
function getAttrs(attributes: {[key: string]: string | sax.QualifiedAttribute}) {
const res: string[] = [];
for (const attr of Object.keys(attributes)) {
res.push(`${attr.toLowerCase()}="${quoteEscape(attributes[attr] as string)}"`);
}
return res.length ? ' ' + res.join(' ') : '';
}
function isSelfClosing(tagName: string) {
return ['IMG'].indexOf(tagName) > -1;
}
const HTML_ENTITY_MAP: {[key: string]: string} = {
'"': 'quot',
'&': 'amp'
};
function quoteEscape(html: string) {
return html.replace(/["&]/g, (s) => {
return `&${HTML_ENTITY_MAP[s]};`;
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment