-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathindex.js
More file actions
90 lines (78 loc) · 2.47 KB
/
index.js
File metadata and controls
90 lines (78 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
import CodeMirror from './codemirror/lib/codemirror.js'
import './codemirror/mode/xml/xml.js'
(function() {
const input = document.querySelector('input[type=file]')
const result = document.getElementById('result')
const preview = document.querySelector('.preview')
const download = document.getElementById('download')
const copy = document.getElementById('copy')
const previewBg = document.getElementById('preview-bg')
let code = ''
let theme = 'default'
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
theme = 'material-darker'
}
const editor = CodeMirror.fromTextArea(result, {
lineNumbers: true,
mode: {
name: 'xml'
},
theme: theme,
tabSize: 2
})
editor.on('change', function(editor) {
const value = editor.getValue()
readFile(value)
})
function svgDataURL(svg) {
const svgAsXML = (new XMLSerializer).serializeToString(svg)
return 'data:image/svg+xml,' + encodeURIComponent(svgAsXML)
}
function readFile(event) {
const value = (event.target && event.target.result) || event
if (event.target && event.target.result) {
editor.setValue(value)
}
const fragment = document.createRange().createContextualFragment(value)
if (fragment.querySelector('svg')) {
preview.innerHTML = value
code = value
copy.removeAttribute('disabled')
const svg = preview.querySelector('svg')
download.href = svgDataURL(svg)
download.setAttribute('download', 'image.svg')
} else {
preview.innerHTML = 'Not a valid SVG code'
}
if (!value) {
copy.setAttribute('disabled', true)
preview.innerHTML = ''
}
}
function changeFile() {
const file = input.files[0]
const reader = new FileReader()
reader.addEventListener('load', readFile)
reader.readAsText(file)
}
function handleCopy (e) {
window.navigator.clipboard.writeText(code)
e.target.classList.add('copied')
setTimeout(() => {
e.target.classList.remove('copied')
}, 1000)
}
function handleDownload (e) {
if (!e.currentTarget.getAttribute('href')) {
e.preventDefault()
}
}
function handlePreviewBgChange (e) {
preview.style.background = e?.target?.value || '#e3e3e3'
}
input.addEventListener('change', changeFile)
copy.addEventListener('click', handleCopy)
download.addEventListener('click', handleDownload)
previewBg.addEventListener('input', handlePreviewBgChange)
handlePreviewBgChange()
})()