-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.html
91 lines (83 loc) · 2.73 KB
/
index.html
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
91
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Functional Generative Art</title>
<style>
body {
margin: 0;
padding: 0;
}
</style>
</head>
<body>
<script type="text/javascript" src="index.js"></script>
<script type="text/javascript">
const app = Elm.Main.init();
const port = 6743;
app.ports.raiseLowerPen.subscribe( () => {
http('PUT', api(port, '/print'), "")
.then(console.log)
.catch(console.error);
});
app.ports.disableMotor.subscribe( () => {
http('DELETE', api(port, '/print'), "")
.then(console.log)
.catch(console.error);
});
app.ports.print.subscribe( () => {
const node = document.getElementById('frame');
const payload = { svg: node.outerHTML };
console.log(payload);
http('POST', api(port, '/print'), payload)
.then(console.log)
.catch(console.error);
});
app.ports.download.subscribe( name => {
const node = document.getElementById('frame');
const routeName = name.split(' ')[0];
saveSvg(node, `${routeName}.svg`);
});
// Get plotter status every 30 seconds
window.setInterval( () => {
http('GET', api(port, '/print'))
.then(app.ports.getPlotterStatus.send)
.catch(console.error);
}, 10000);
// Return the full API url
function api (port, endpoint) {
return `//localhost:${port}${endpoint}`;
}
// Generic HTTP Request helper function
function http (method, url, data) {
return fetch (url, {
body: JSON.stringify(data),
cache: 'no-cache',
headers: {
'content-type': 'application/json'
},
method: method,
mode: 'cors',
redirect: 'follow',
referrer: 'no-referrer',
})
.then(response => response.json()); // parses response to JSON
}
// As it turns out, it is very annoying to save <svg> into a file via JS
// See https://stackoverflow.com/a/46403589
function saveSvg(svgEl, name) {
svgEl.setAttribute("xmlns", "http://www.w3.org/2000/svg");
var svgData = svgEl.outerHTML;
var preface = '<?xml version="1.0" standalone="no"?>';
var svgBlob = new Blob([preface, svgData], {type:"image/svg+xml;charset=utf-8"});
var svgUrl = URL.createObjectURL(svgBlob);
var downloadLink = document.createElement("a");
downloadLink.href = svgUrl;
downloadLink.download = name;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
}
</script>
</body>
</html>