index.js (view raw)
1let copyElement = document.getElementById('copy');
2const flask = new CodeFlask('#editor', { language: 'javascript', lineNumbers: true, defaultTheme: false });
3const lzma = new LZMA('lzma.min.js');
4Prism.plugins.autoloader.languages_path = 'https://cdn.jsdelivr.net/npm/prismjs@1.14.0/components/';
5let select;
6
7function init() {
8 initLangSelector();
9 initCode();
10 const clipboard = new ClipboardJS('.clipboard');
11 clipboard.on('success', function() {
12 copyElement.style.display = 'none';
13 });
14}
15
16function initLangSelector() {
17 select = new SlimSelect({
18 select: '#language',
19 data: Object.entries(languages).map(([value, text]) => ({ text, value })),
20 showContent: 'up',
21 onChange: e => {
22 console.log(e.value);
23 flask.updateLanguage(e.value);
24 }
25 });
26
27 const urlParams = new URLSearchParams(window.location.search);
28 select.set(Object.keys(languages).indexOf(urlParams.get('lang')) === -1 ? 'javascript' : urlParams.get('lang'));
29}
30
31function initCode() {
32 const base64 = location.hash.substr(1);
33 if (base64.length === 0) {
34 return;
35 }
36
37 if (!fetch) {
38 alert('Your browser does not support this page. Sorry! :(');
39 return;
40 }
41
42 fetch('data:application/octet-stream;base64,' + base64)
43 .then(r => r.blob())
44 .then(function(blob) {
45 const reader = new FileReader();
46 reader.onload = function() {
47 lzma.decompress(Array.from(new Uint8Array(reader.result)), function(plaintext, error) {
48 if (error) {
49 alert('Failed to decompress data: ' + error);
50 return;
51 }
52 flask.updateCode(plaintext);
53 });
54 };
55 reader.readAsArrayBuffer(blob);
56 });
57}
58
59function generateLink() {
60 const code = flask.getCode();
61 lzma.compress(code, 1, function(compressed, error) {
62 if (error) {
63 alert('Failed to compress data: ' + error);
64 return;
65 }
66 const reader = new FileReader();
67 reader.onload = function() {
68 const base64 = reader.result.substr(reader.result.indexOf(',') + 1);
69 const url = `${location.protocol}//${location.host}${
70 location.pathname
71 }?lang=${select.selected()}#${base64}`;
72 document.getElementById('copy-link').value = url;
73 copyElement.style.display = 'block';
74 };
75 reader.readAsDataURL(new Blob([new Uint8Array(compressed)]));
76 });
77}
78
79init();