aboutsummaryrefslogtreecommitdiff
path: root/static/js/ext/multi-swap.js
blob: 0c882f83329b6002b3b41ec02db4302c20e2bc8b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
(function () {

    if (htmx.version && !htmx.version.startsWith("1.")) {
        console.warn("WARNING: You are using an htmx 1 extension with htmx " + htmx.version +
            ".  It is recommended that you move to the version of this extension found on https://htmx.org/extensions")
    }

    /** @type {import("../htmx").HtmxInternalApi} */
    var api;

    htmx.defineExtension('multi-swap', {
        init: function (apiRef) {
            api = apiRef;
        },
        isInlineSwap: function (swapStyle) {
            return swapStyle.indexOf('multi:') === 0;
        },
        handleSwap: function (swapStyle, target, fragment, settleInfo) {
            if (swapStyle.indexOf('multi:') === 0) {
                var selectorToSwapStyle = {};
                var elements = swapStyle.replace(/^multi\s*:\s*/, '').split(/\s*,\s*/);

                elements.map(function (element) {
                    var split = element.split(/\s*:\s*/);
                    var elementSelector = split[0];
                    var elementSwapStyle = typeof (split[1]) !== "undefined" ? split[1] : "innerHTML";

                    if (elementSelector.charAt(0) !== '#') {
                        console.error("HTMX multi-swap: unsupported selector '" + elementSelector + "'. Only ID selectors starting with '#' are supported.");
                        return;
                    }

                    selectorToSwapStyle[elementSelector] = elementSwapStyle;
                });

                for (var selector in selectorToSwapStyle) {
                    var swapStyle = selectorToSwapStyle[selector];
                    var elementToSwap = fragment.querySelector(selector);
                    if (elementToSwap) {
                        api.oobSwap(swapStyle, elementToSwap, settleInfo);
                    } else {
                        console.warn("HTMX multi-swap: selector '" + selector + "' not found in source content.");
                    }
                }

                return true;
            }
        }
    });
})();