UNPKG

1.82 kBJavaScriptView Raw
1'use strict';
2/**
3 * index.demo module
4 * @module index.demo
5 * @see module:index
6 */
7import $ from 'jquery';
8import CodeMirror from 'codemirror';
9import XMLLite from 'xml-lite';
10import lang from 'zero-lang';
11import './index.less';
12
13const $xml = $('#xml-textarea');
14const $json = $('#json-textarea');
15const $parserStatus = $('#parser-status');
16
17const editorOptions = {
18 foldGutter: true,
19 gutters: [
20 'CodeMirror-linenumbers',
21 'CodeMirror-foldgutter'
22 ],
23 lineNumbers: true,
24 lineWrapping: true,
25};
26
27const xmlEditor = CodeMirror.fromTextArea($xml[0], lang.extend({
28 mode: 'text/xml',
29}, editorOptions));
30const jsonEditor = CodeMirror.fromTextArea($json[0], lang.extend({
31 mode: 'javascript',
32}, editorOptions));
33
34function 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
48function 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}
59function 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
73xmlEditor.on('change', () => {
74 if (xmlEditor.hasFocus()) {
75 xml2json();
76 }
77});
78jsonEditor.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');