Guest User

Untitled

a guest
Jun 20th, 2018
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. // if running in a CommonJS environment use exports object,
  2. // otherwise set up as hiccup.html()
  3. if (typeof exports === "undefined" || !exports) {
  4. var hiccup = {};
  5. }
  6.  
  7. (function(exports) {
  8.  
  9. var html = exports.html = function() {
  10. var buffer = [];
  11. build(arguments, buffer);
  12. return buffer.join("");
  13. }
  14.  
  15. // if jQuery is available create a $.hiccup() that returns
  16. // a jQuery selector with the rendered HTML
  17. if (typeof jQuery === "function") {
  18. jQuery.hiccup = function() {
  19. return jQuery(html.apply(null, arguments));
  20. };
  21. }
  22.  
  23. function build(list, buffer) {
  24. var index = 0;
  25. var length = list.length;
  26. if (typeof list[index] === "string") {
  27. var tag = splitTag(list[index++]);
  28. var attr = tag[1];
  29. tag = tag[0];
  30. if (isObject(list[index])) {
  31. mergeAttributes(attr, list[index++]);
  32. }
  33. buffer.push("<", tag);
  34. for (var key in attr) {
  35. buffer.push(" ", key, "=\"", attr[key], "\"");
  36. }
  37. buffer.push(">");
  38. buildRest(list, index, buffer);
  39. buffer.push("</", tag, ">");
  40. } else {
  41. buildRest(list, index, buffer);
  42. }
  43. }
  44.  
  45. function buildRest(list, index, buffer) {
  46. var length = list.length;
  47. while (index < length) {
  48. var item = list[index++];
  49. if (isArray(item)) {
  50. build(item, buffer);
  51. } else {
  52. buffer.push(item);
  53. }
  54. }
  55. }
  56.  
  57. function isObject(item) {
  58. return item instanceof Object && item.constructor !== Array;
  59. }
  60.  
  61. function isArray(item) {
  62. return item instanceof Object && item.constructor === Array;
  63. }
  64.  
  65. function mergeAttributes(attr1, attr2) {
  66. for (var key in attr2) {
  67. if (!attr1.hasOwnProperty(key)) {
  68. attr1[key] = attr2[key];
  69. } else if (key === "class") {
  70. attr1[key] += " " + attr2[key];
  71. }
  72. }
  73. }
  74.  
  75. function splitTag(tag) {
  76. var attr = {};
  77. var match = tag.match(/([^\s\.#]+)(?:#([^\s\.#]+))?(?:\.([^\s#]+))?/);
  78. if (match[2]) attr.id = match[2];
  79. if (match[3]) attr["class"] = match[3].replace(/\./g, " ");
  80. return [match[1], attr];
  81. }
  82.  
  83. })(hiccup || exports);
Add Comment
Please, Sign In to add comment