Debian Codegraph @

dist/ext/hx-optimistic.js

raw symbols SCIP
1 (() =>{
2
3 function normalizeSwapStyle(style) {
4 return style === 'before' ? 'beforebegin' :
5 style === 'after' ? 'afterend' :
6 style === 'prepend' ? 'afterbegin' :
7 style === 'append' ? 'beforeend' : style;
8 }
9
10 let api;
11
12 function insertOptimisticContent(ctx) {
13 ctx.optimistic = api.attributeValue(ctx.sourceElement, "hx-optimistic");
14 if (!ctx.optimistic) {
15 return
16 }
17
18 let sourceElt = document.querySelector(ctx.optimistic);
19 if (!sourceElt) return;
20
21 let target = ctx.target;
22
23 if (typeof target === 'string') {
24 target = document.querySelector(target);
25 }
26 if (!target) return;
27
28 // Create optimistic div with reset styling
29 let optimisticDiv = document.createElement('div');
30 optimisticDiv.style.cssText = 'all: initial';
31 optimisticDiv.classList.add('hx-optimistic');
32 optimisticDiv.innerHTML = sourceElt.innerHTML;
33
34 // Set data-* for each request param
35 if (ctx.optimisticBody) {
36 let keys = new Set(ctx.optimisticBody.keys());
37 for (let k of keys) {
38 let values = ctx.optimisticBody.getAll(k).filter(v => typeof v === 'string');
39 if (!values.length) continue;
40 let val = values.length === 1 ? values[0] : JSON.stringify(values);
41 try {
42 optimisticDiv.dataset[k] = val;
43 } catch (e) {
44 try {
45 optimisticDiv.setAttribute('data-' + k, val);
46 } catch (e2) { /* truly invalid name, skip */ }
47 }
48 }
49 }
50
51 let swapStyle = normalizeSwapStyle(ctx.swap);
52 ctx.optHidden = [];
53
54 if (swapStyle === 'innerHTML') {
55 // Hide children of target
56 for (let child of target.children) {
57 child.style.display = 'none';
58 ctx.optHidden.push(child);
59 }
60 target.appendChild(optimisticDiv);
61 } else if (['beforebegin', 'afterbegin', 'beforeend', 'afterend'].includes(swapStyle)) {
62 target.insertAdjacentElement(swapStyle, optimisticDiv);
63 } else {
64 // Assume outerHTML-like behavior, Hide target and insert div after it
65 target.style.display = 'none';
66 ctx.optHidden.push(target);
67 target.after(optimisticDiv);
68 }
69 ctx.optimisticDiv = optimisticDiv;
70 htmx.process(optimisticDiv);
71 }
72
73 function removeOptimisticContent(ctx) {
74 if (!ctx.optimisticDiv) return;
75
76 // Remove optimistic div
77 ctx.optimisticDiv.remove();
78
79 // Unhide any hidden elements
80 for (let elt of ctx.optHidden) {
81 elt.style.display = '';
82 }
83 }
84
85 htmx.registerExtension('hx-optimistic', {
86 init: (internalAPI) => { api = internalAPI; },
87 htmx_config_request: (elt, detail) => {
88 let body = detail.ctx.request.body;
89 if (body?.entries) detail.ctx.optimisticBody = body;
90 },
91 htmx_before_request: (elt, detail) => {
92 insertOptimisticContent(detail.ctx);
93 },
94 htmx_error : (elt, detail) => {
95 removeOptimisticContent(detail.ctx)
96 },
97 htmx_before_swap : (elt, detail) => {
98 removeOptimisticContent(detail.ctx)
99 }
100 });
101 })();