You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

util.js 1.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. window.addEventListener("error", evt => {
  2. console.error(evt);
  3. alert("Oh no: " + evt.message);
  4. });
  5. window.addEventListener("unhandledrejection", evt => {
  6. console.error(evt);
  7. alert("Oh no: " + evt.reason.toString());
  8. });
  9. async function api(method, path, body = null) {
  10. let options = {method};
  11. if (body != null) {
  12. options.body = JSON.stringify(body);
  13. }
  14. let json;
  15. let resp = await fetch("/api/" + path, options).then(r => r.text());
  16. json = JSON.parse(resp);
  17. return json;
  18. }
  19. function html(name, attrs, children) {
  20. if (!(children instanceof Array)) {
  21. children = [children];
  22. }
  23. if (name == "text") {
  24. return document.createTextNode(attrs);
  25. }
  26. let el = document.createElement(name);
  27. for (let key in attrs) {
  28. if (!attrs.hasOwnProperty(key)) {
  29. continue;
  30. }
  31. el.setAttribute(key, attrs[key]);
  32. }
  33. for (let child of children) {
  34. if (typeof child == "string") {
  35. el.appendChild(document.createTextNode(child));
  36. } else {
  37. el.appendChild(child);
  38. }
  39. }
  40. return el;
  41. }
  42. function clearElement(el) {
  43. while (el.firstChild) {
  44. el.removeChild(el.firstChild);
  45. }
  46. }
  47. function renderToElement(el, children) {
  48. if (!(children instanceof Array)) {
  49. children = [children];
  50. }
  51. clearElement(el);
  52. for (let child of children) {
  53. el.appendChild(child);
  54. }
  55. }