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