UNPKG

3.29 kBJavaScriptView Raw
1(function () {
2
3 function splitOnWhitespace(trigger) {
4 return trigger.split(/\s+/);
5 }
6
7 function parseClassOperation(trimmedValue) {
8 var split = splitOnWhitespace(trimmedValue);
9 if (split.length > 1) {
10 var operation = split[0];
11 var classDef = split[1].trim();
12 var cssClass;
13 var delay;
14 if (classDef.indexOf(":") > 0) {
15 var splitCssClass = classDef.split(':');
16 cssClass = splitCssClass[0];
17 delay = htmx.parseInterval(splitCssClass[1]);
18 } else {
19 cssClass = classDef;
20 delay = 100;
21 }
22 return {
23 operation: operation,
24 cssClass: cssClass,
25 delay: delay
26 }
27 } else {
28 return null;
29 }
30 }
31
32 function performOperation(elt, classOperation, classList, currentRunTime) {
33 setTimeout(function () {
34 elt.classList[classOperation.operation].call(elt.classList, classOperation.cssClass);
35 }, currentRunTime)
36 }
37
38 function toggleOperation(elt, classOperation, classList, currentRunTime) {
39 setTimeout(function () {
40 setInterval(function () {
41 elt.classList[classOperation.operation].call(elt.classList, classOperation.cssClass);
42 }, classOperation.delay);
43 }, currentRunTime)
44 }
45
46 function processClassList(elt, classList) {
47 var runs = classList.split("&");
48 for (var i = 0; i < runs.length; i++) {
49 var run = runs[i];
50 var currentRunTime = 0;
51 var classOperations = run.split(",");
52 for (var j = 0; j < classOperations.length; j++) {
53 var value = classOperations[j];
54 var trimmedValue = value.trim();
55 var classOperation = parseClassOperation(trimmedValue);
56 if (classOperation) {
57 if (classOperation.operation === "toggle") {
58 toggleOperation(elt, classOperation, classList, currentRunTime);
59 currentRunTime = currentRunTime + classOperation.delay;
60 } else {
61 currentRunTime = currentRunTime + classOperation.delay;
62 performOperation(elt, classOperation, classList, currentRunTime);
63 }
64 }
65 }
66 }
67 }
68
69 function maybeProcessClasses(elt) {
70 if (elt.getAttribute) {
71 var classList = elt.getAttribute("classes") || elt.getAttribute("data-classes");
72 if (classList) {
73 processClassList(elt, classList);
74 }
75 }
76 }
77
78 htmx.defineExtension('class-tools', {
79 onEvent: function (name, evt) {
80 if (name === "htmx:afterProcessNode") {
81 var elt = evt.detail.elt;
82 maybeProcessClasses(elt);
83 if (elt.querySelectorAll) {
84 var children = elt.querySelectorAll("[classes], [data-classes]");
85 for (var i = 0; i < children.length; i++) {
86 maybeProcessClasses(children[i]);
87 }
88 }
89 }
90 }
91 });
92})();
\No newline at end of file