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 | const editorOptions = {
|
18 | foldGutter: true,
|
19 | gutters: [
|
20 | 'CodeMirror-linenumbers',
|
21 | 'CodeMirror-foldgutter'
|
22 | ],
|
23 | lineNumbers: true,
|
24 | lineWrapping: true,
|
25 | };
|
26 |
|
27 | const xmlEditor = CodeMirror.fromTextArea($xml[0], lang.extend({
|
28 | mode: 'text/xml',
|
29 | }, editorOptions));
|
30 | const jsonEditor = CodeMirror.fromTextArea($json[0], lang.extend({
|
31 | mode: 'javascript',
|
32 | }, editorOptions));
|
33 |
|
34 | function setParserStatus(error) {
|
35 | if (error) {
|
36 | $parserStatus
|
37 | .removeClass('success')
|
38 | .addClass('error')
|
39 | .html(error);
|
40 | } else {
|
41 | $parserStatus
|
42 | .removeClass('error')
|
43 | .addClass('success')
|
44 | .html('success');
|
45 | }
|
46 | }
|
47 |
|
48 | function xml2json() {
|
49 | const xmlContent = xmlEditor.getValue();
|
50 | try {
|
51 | const json = XMLLite.xml2json(xmlContent, null, 2);
|
52 | jsonEditor.getDoc().setValue(json);
|
53 | setParserStatus();
|
54 | } catch (e) {
|
55 | console.log(e);
|
56 | setParserStatus(e);
|
57 | }
|
58 | }
|
59 | function json2xml() {
|
60 | const jsonContent = jsonEditor.getValue();
|
61 | try {
|
62 | const xml = XMLLite.json2xml(jsonContent, {
|
63 | beautify: true,
|
64 | });
|
65 | xmlEditor.getDoc().setValue(xml);
|
66 | setParserStatus();
|
67 | } catch (e) {
|
68 | console.log(e);
|
69 | setParserStatus(e);
|
70 | }
|
71 | }
|
72 |
|
73 | xmlEditor.on('change', () => {
|
74 | if (xmlEditor.hasFocus()) {
|
75 | xml2json();
|
76 | }
|
77 | });
|
78 | jsonEditor.on('change', () => {
|
79 | if (jsonEditor.hasFocus()) {
|
80 | json2xml();
|
81 | }
|
82 | });
|
83 |
|
84 | $.get('./spec/fixtures/bookstore.xml', (xmlContent) => {
|
85 | xmlEditor.getDoc().setValue(xmlContent);
|
86 | xml2json();
|
87 | }, 'text');
|