UNPKG

1.43 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');
15
16const editorOptions = {
17 foldGutter: true,
18 gutters: [
19 'CodeMirror-linenumbers',
20 'CodeMirror-foldgutter'
21 ],
22 lineNumbers: true,
23 lineWrapping: true,
24};
25
26const xmlEditor = CodeMirror.fromTextArea($xml[0], lang.extend({
27 mode: 'text/xml',
28}, editorOptions));
29const jsonEditor = CodeMirror.fromTextArea($json[0], lang.extend({
30 mode: 'javascript',
31}, editorOptions));
32
33function 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}
42function 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
54xmlEditor.on('change', () => {
55 if (xmlEditor.hasFocus()) {
56 xml2json();
57 }
58});
59jsonEditor.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');