UNPKG

1.86 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
17XMLLite.keepDoubleQuotes = true;
18
19const editorOptions = {
20 foldGutter: true,
21 gutters: [
22 'CodeMirror-linenumbers',
23 'CodeMirror-foldgutter'
24 ],
25 lineNumbers: true,
26 lineWrapping: true,
27};
28
29const xmlEditor = CodeMirror.fromTextArea($xml[0], lang.extend({
30 mode: 'text/xml',
31}, editorOptions));
32const jsonEditor = CodeMirror.fromTextArea($json[0], lang.extend({
33 mode: 'javascript',
34}, editorOptions));
35
36function 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
50function 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}
61function 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
75xmlEditor.on('change', () => {
76 if (xmlEditor.hasFocus()) {
77 xml2json();
78 }
79});
80jsonEditor.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');