Debian Codegraph @

dist/ext/hx-targets.js

raw symbols SCIP
1 //==========================================================
2 // hx-targets.js
3 //
4 // An extension that adds an 'hx-targets' attribute to target
5 // multiple elements with the same swap content.
6 //
7 // Usage:
8 // <button hx-get="/api" hx-targets=".card">Click</button>
9 //
10 // The response will be swapped into all elements matching
11 // the selector. The hx-targets attribute is inherited.
12 //==========================================================
13 (() => {
14 let api;
15
16 htmx.registerExtension('hx-targets', {
17 init: (internalAPI) => {
18 api = internalAPI;
19 },
20 htmx_before_swap: (elt, detail) => {
21 let {ctx, tasks} = detail;
22 let selector = api.attributeValue(ctx.sourceElement, 'hx-targets');
23 if (!selector) return;
24
25 let targets = htmx.findAll(ctx.sourceElement, selector);
26 if (!targets.length) {
27 console.warn(`htmx: '${selector}' on hx-targets did not match any elements`, { selector });
28 return;
29 }
30
31 // Replace main task with one task per target
32 let mainIndex = tasks.findIndex(t => t.type === 'main');
33 if (mainIndex === -1) return;
34
35 let mainTask = tasks[mainIndex];
36 let newTasks = Array.from(targets).map(target => ({
37 ...mainTask,
38 fragment: mainTask.fragment.cloneNode(true),
39 target
40 }));
41
42 tasks.splice(mainIndex, 1, ...newTasks);
43 }
44 });
45 })();