microjungle JsonML to DocumentFragment

Based on https://github.com/deepsweet/microjungle by Kir Belevich

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/25520/241821/microjungle%20JsonML%20to%20DocumentFragment.js

  1. // ==UserScript==
  2. // @name microjungle JsonML to DocumentFragment
  3. // @description Based on https://github.com/deepsweet/microjungle by Kir Belevich
  4. // @namespace https://greatest.deepsurf.us/en/users/447-spooky-donkey
  5. // @ecmaVersion 6
  6. // @version 3
  7. // @grant none
  8. // ==/UserScript==
  9.  
  10. /*exported MicrojungleJsonMLtoDocumentFragment*/
  11. const MicrojungleJsonMLtoDocumentFragment = function () {
  12. "use strict";
  13. return function frag(template, target = document.createDocumentFragment()) {
  14. if (!Array.isArray(template)) {
  15. return target;
  16. }
  17. const stringOrFinite = a => typeof a === "string" ||
  18. (typeof a === "number" && isFinite(a));
  19. function createElement(item, s = item[1]) {
  20. const elem = document.createElement(item.shift());
  21. if (!!s && s.constructor === Object) {
  22. const attrList = item.shift();
  23. Object.entries(attrList).forEach(([attrName, attrValue]) => {
  24. if (stringOrFinite(attrValue)) {
  25. elem.setAttribute(attrName, attrValue);
  26. }
  27. });
  28. }
  29. target.appendChild(frag(item, elem));
  30. }
  31. template.forEach(item => {
  32. if (stringOrFinite(item)) {
  33. target.appendChild(document.createTextNode(item));
  34. } else if (item) {
  35. if (typeof item[0] === "string") {
  36. createElement(item);
  37. } else if (item.nodeType) {
  38. target.appendChild(item);
  39. } else {
  40. frag(item, target);
  41. }
  42. }
  43. });
  44. return target;
  45. };
  46. };