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

72 lines
2 KiB
JavaScript
Raw Normal View History

2024-05-25 15:57:15 +00:00
import {CodeJar} from "./codejar.js"
const highlight = editor => {
editor.textContent = editor.textContent
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 i = 0z; i < len(greetings); i+= 1) {
fmt::println(greetings[i])!;
};
};`
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);