1
Fork 0
hare-playground/frontend/app.js

73 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-05-25 15:57:15 +00:00
import {CodeJar} from "./codejar.js"
2024-05-25 16:33:44 +00:00
function highlight(editor) {
editor.textContent = editor.textContent;
editor.removeAttribute("data-highlighted");
hljs.highlightElement(editor);
}
2024-05-25 15:57:15 +00:00
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 = {
2024-05-25 16:28:00 +00:00
const greetings = [
"Hello, world!",
"¡Hola Mundo!",
"Γειά σου Κόσμε!",
"Привіт, світ!",
"こんにちは世界!",
];
for (let greeting .. greetings) {
fmt::println(greeting)!;
};
};`;
2024-05-25 15:57:15 +00:00
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() {
2024-05-25 16:19:49 +00:00
document.querySelector("codapi-status").innerText = "✓ Link copied!"
2024-05-25 15:57:15 +00:00
}, function(err) {
2024-05-25 16:19:49 +00:00
document.querySelector("codapi-status").innerText = "✓ Link changed. Copy the URL now."
2024-05-25 15:57:15 +00:00
});
} else {
2024-05-25 16:19:49 +00:00
document.querySelector("codapi-status").innerText = "✓ Link changed. Copy the URL now."
2024-05-25 15:57:15 +00:00
}
};
let shareText = document.createTextNode("Share");
shareLink.appendChild(shareText);
let editLink = document.querySelector("codapi-toolbar a");
editLink.insertAdjacentElement('afterend', shareLink);