73 lines
1.9 KiB
JavaScript
73 lines
1.9 KiB
JavaScript
import {CodeJar} from "./codejar.js"
|
||
|
||
function highlight(editor) {
|
||
editor.textContent = editor.textContent;
|
||
editor.removeAttribute("data-highlighted");
|
||
hljs.highlightElement(editor);
|
||
}
|
||
|
||
function base64ToBytes(base64) {
|
||
const binString = atob(base64);
|
||
return Uint8Array.from(binString, (m) => m.codePointAt(0));
|
||
}
|
||
function base64Encode(str) {
|
||
return bytesToBase64(new TextEncoder().encode(str));
|
||
}
|
||
|
||
function bytesToBase64(bytes) {
|
||
const binString = Array.from(bytes, (byte) =>
|
||
String.fromCodePoint(byte),
|
||
).join("");
|
||
return btoa(binString);
|
||
}
|
||
function base64Decode(bytes) {
|
||
return new TextDecoder().decode(base64ToBytes(bytes));
|
||
}
|
||
|
||
let jar = CodeJar(document.querySelector('.editor'), highlight)
|
||
const defaultCode = `use fmt;
|
||
|
||
export fn main() void = {
|
||
const greetings = [
|
||
"Hello, world!",
|
||
"¡Hola Mundo!",
|
||
"Γειά σου Κόσμε!",
|
||
"Привіт, світ!",
|
||
"こんにちは世界!",
|
||
];
|
||
for (let greeting .. greetings) {
|
||
fmt::println(greeting)!;
|
||
};
|
||
};`;
|
||
|
||
if (location.hash) {
|
||
let code = base64Decode(location.hash.substr(1));
|
||
jar.updateCode(code)
|
||
} else {
|
||
jar.updateCode(defaultCode);
|
||
}
|
||
|
||
let shareLink = document.createElement("a");
|
||
shareLink.href = "#";
|
||
shareLink.onclick = (e) => {
|
||
e.preventDefault();
|
||
let code = document.querySelector('.editor').innerText;
|
||
location.hash = base64Encode(code);
|
||
|
||
if (navigator.clipboard) {
|
||
let text = location.href;
|
||
navigator.clipboard.writeText(text).then(function() {
|
||
document.querySelector("codapi-status").innerText = "✓ Link copied!"
|
||
}, function(err) {
|
||
document.querySelector("codapi-status").innerText = "✓ Link changed. Copy the URL now."
|
||
});
|
||
} else {
|
||
document.querySelector("codapi-status").innerText = "✓ Link changed. Copy the URL now."
|
||
}
|
||
};
|
||
|
||
let shareText = document.createTextNode("Share");
|
||
shareLink.appendChild(shareText);
|
||
let editLink = document.querySelector("codapi-toolbar a");
|
||
editLink.insertAdjacentElement('afterend', shareLink);
|