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 flask.updateLanguage(e.value);
23 }
24 });
25
26 const urlParams = new URLSearchParams(window.location.search);
27 select.set(Object.keys(languages).indexOf(urlParams.get('lang')) === -1 ? 'javascript' : urlParams.get('lang'));
28}
29
30function initCode() {
31 const base64 = location.hash.substr(1);
32 if (base64.length === 0) {
33 return;
34 }
35
36 if (!fetch) {
37 alert('Your browser does not support this page. Sorry! :(');
38 return;
39 }
40
41 fetch('data:application/octet-stream;base64,' + base64)
42 .then(r => r.blob())
43 .then(function(blob) {
44 const reader = new FileReader();
45 reader.onload = function() {
46 lzma.decompress(Array.from(new Uint8Array(reader.result)), function(plaintext, error) {
47 if (error) {
48 alert('Failed to decompress data: ' + error);
49 return;
50 }
51 flask.updateCode(plaintext);
52 });
53 };
54 reader.readAsArrayBuffer(blob);
55 });
56}
57
58function generateLink() {
59 const code = flask.getCode();
60 lzma.compress(code, 1, function(compressed, error) {
61 if (error) {
62 alert('Failed to compress data: ' + error);
63 return;
64 }
65 const reader = new FileReader();
66 reader.onload = function() {
67 const base64 = reader.result.substr(reader.result.indexOf(',') + 1);
68 const url = `${location.protocol}//${location.host}${
69 location.pathname
70 }?lang=${select.selected()}#${base64}`;
71 const linkInput = document.getElementById('copy-link');
72 linkInput.value = url;
73 linkInput.setSelectionRange(0, url.length);
74 copyElement.style.display = 'flex';
75 };
76 reader.readAsDataURL(new Blob([new Uint8Array(compressed)]));
77 });
78}
79
80init();