forked from crabl/nicejson.com
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
45 lines (37 loc) · 1.24 KB
/
index.js
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
const format = require('xml-formatter');
const parser = require('fast-xml-parser');
const $paste = document.getElementById('paste');
const $result = document.getElementById('xml');
const $instructions = document.getElementById('instructions');
const $error = document.getElementById('error');
const ERROR_SYMBOL = Symbol();
function formatXML(xmlString) {
try {
const valid = parser.validate(xmlString);
if (valid !== true) throw Error();
const formattedXml = format(xmlString, { collapseContent: true });
return formattedXml;
} catch (e) {
return ERROR_SYMBOL;
}
}
$paste.onpaste = event => {
let rawPaste;
if (window.clipboardData && window.clipboardData.getData) {
rawPaste = window.clipboardData.getData('Text');
} else if (event.clipboardData && event.clipboardData.getData) {
rawPaste = event.clipboardData.getData('text/plain');
}
const result = formatXML(rawPaste);
if (result === ERROR_SYMBOL) {
$result.style.display = 'none';
$instructions.style.display = 'none';
$error.style.display = 'block';
} else {
$result.style.display = 'block';
$result.innerText = result;
$instructions.style.display = 'none';
$error.style.display = 'none';
}
return false; // prevent default
};