1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 |
|
6 |
|
7 | import $ from 'jquery';
|
8 | import CodeMirror from 'codemirror';
|
9 | import XMLLite from 'xml-lite';
|
10 | import lang from 'zero-lang';
|
11 | import './index.less';
|
12 |
|
13 | const $xml = $('#xml-textarea');
|
14 | const $json = $('#json-textarea');
|
15 | const $parserStatus = $('#parser-status');
|
16 |
|
17 | XMLLite.keepDoubleQuotes = true;
|
18 |
|
19 | const editorOptions = {
|
20 | foldGutter: true,
|
21 | gutters: [
|
22 | 'CodeMirror-linenumbers',
|
23 | 'CodeMirror-foldgutter'
|
24 | ],
|
25 | lineNumbers: true,
|
26 | lineWrapping: true,
|
27 | };
|
28 |
|
29 | const xmlEditor = CodeMirror.fromTextArea($xml[0], lang.extend({
|
30 | mode: 'text/xml',
|
31 | }, editorOptions));
|
32 | const jsonEditor = CodeMirror.fromTextArea($json[0], lang.extend({
|
33 | mode: 'javascript',
|
34 | }, editorOptions));
|
35 |
|
36 | function setParserStatus(error) {
|
37 | if (error) {
|
38 | $parserStatus
|
39 | .removeClass('success')
|
40 | .addClass('error')
|
41 | .html(error);
|
42 | } else {
|
43 | $parserStatus
|
44 | .removeClass('error')
|
45 | .addClass('success')
|
46 | .html('success');
|
47 | }
|
48 | }
|
49 |
|
50 | function xml2json() {
|
51 | const xmlContent = xmlEditor.getValue();
|
52 | try {
|
53 | const json = XMLLite.xml2json(xmlContent, null, 2);
|
54 | jsonEditor.getDoc().setValue(json);
|
55 | setParserStatus();
|
56 | } catch (e) {
|
57 | console.log(e);
|
58 | setParserStatus(e);
|
59 | }
|
60 | }
|
61 | function json2xml() {
|
62 | const jsonContent = jsonEditor.getValue();
|
63 | try {
|
64 | const xml = XMLLite.json2xml(jsonContent, {
|
65 | beautify: true,
|
66 | });
|
67 | xmlEditor.getDoc().setValue(xml);
|
68 | setParserStatus();
|
69 | } catch (e) {
|
70 | console.log(e);
|
71 | setParserStatus(e);
|
72 | }
|
73 | }
|
74 |
|
75 | xmlEditor.on('change', () => {
|
76 | if (xmlEditor.hasFocus()) {
|
77 | xml2json();
|
78 | }
|
79 | });
|
80 | jsonEditor.on('change', () => {
|
81 | if (jsonEditor.hasFocus()) {
|
82 | json2xml();
|
83 | }
|
84 | });
|
85 |
|
86 | $.get('./spec/fixtures/bookstore.xml', (xmlContent) => {
|
87 | xmlEditor.getDoc().setValue(xmlContent);
|
88 | xml2json();
|
89 | }, 'text');
|