From 44d1990a9947bc4fe9b8bb3902d9aec0441c9f77 Mon Sep 17 00:00:00 2001 From: Jan Tuomi Date: Wed, 3 Jul 2019 13:55:24 +0300 Subject: Implement web UI --- public/script.js | 63 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 public/script.js (limited to 'public/script.js') diff --git a/public/script.js b/public/script.js new file mode 100644 index 0000000..f9263fa --- /dev/null +++ b/public/script.js @@ -0,0 +1,63 @@ +// https://stackoverflow.com/a/18197511/9381890 +function download(filename, text) { + var pom = document.createElement('a'); + pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text)); + pom.setAttribute('download', filename); + + if (document.createEvent) { + var event = document.createEvent('MouseEvents'); + event.initEvent('click', true, true); + pom.dispatchEvent(event); + } + else { + pom.click(); + } +} + +$('#convertButton').click(async function() { + const jsonInput = $('#jsonInput').val(); + + if (jsonInput.length === 0) return; + + try { + const resp = await axios.post('/convert', { json: jsonInput }); + const data = resp.data; + const xmlOutput = data.xml; + $('#xmlOutput').val(xmlOutput); + $('#xmlOutput').change(); + } catch (err) { + $('#xmlOutput').val(String(err)); + $('#xmlDownloadButton').attr('disabled', true); + } + +}); + +$('#jsonInput').change(function() { + const uploadDisabled = $('#jsonInput').val().length === 0; + $('#convertButton').attr('disabled', uploadDisabled); +}) + +$('#xmlOutput').change(function() { + const downloadDisabled = $('#xmlOutput').val().length === 0; + $('#xmlDownloadButton').attr('disabled', downloadDisabled); +}) + +$('#xmlDownloadButton').click(function() { + const content = $('#xmlOutput').val(); + download('output.xml', content); +}); + +$('#jsonUploadInput').change(function(e) { + const file = e.target.files[0]; + if (file) { + const reader = new FileReader(); + reader.readAsText(file, 'UTF-8'); + reader.onload = function (evt) { + $('#jsonInput').val(evt.target.result); + $('#jsonInput').change(); + } + reader.onerror = function (evt) { + $('#jsonInput').html('Error reading file.'); + } + } +}); \ No newline at end of file -- cgit v1.3