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