extensions: added new extension 'multi-swap' with mocha tests and docs (#1096)

* extensions: added new extension 'multi-swap' with mocha tests and docs

* multi-swap extension: removed forgotten debug console.log()

* multi-swap extension: removed forgotten debug comment from mocha test
This commit is contained in:
Ján Regeš 2022-10-23 16:59:03 +02:00 committed by GitHub
parent 9c42457af6
commit 34582b839c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 173 additions and 0 deletions

45
src/ext/multi-swap.js Normal file
View File

@ -0,0 +1,45 @@
(function () {
/** @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;
}
}
});
})();

52
test/ext/multi-swap.js Normal file
View File

@ -0,0 +1,52 @@
describe("multi-swap extension", function() {
beforeEach(function () {
this.server = makeServer();
clearWorkArea();
});
afterEach(function () {
this.server.restore();
clearWorkArea();
});
it('swap only one element with default innerHTML', function () {
this.server.respondWith("GET", "/test", '<html><body><div class="dummy"><div id="a">New A</div></div></html>');
var content = make('<div>Foo <div id="a">Old A</div></div>');
var btn = make('<button hx-get="/test" hx-ext="multi-swap" hx-swap="multi:#a">Click Me!</button>');
btn.click();
this.server.respond();
should.equal(content.innerHTML, 'Foo <div id="a">New A</div>');
});
it('swap multiple elements with outerHTML, beforeend, afterend, beforebegin and delete methods', function () {
this.server.respondWith("GET", "/test",
'<html><body><div class="abc">' +
'<div id="a">New A</div> foo ' +
'<div id="b"><b>New B</b></div> bar ' +
'<div id="c">New C</div> dummy ' +
'<div id="d">New D</div> lorem ' +
'<div id="e">TO DELETE</div>' +
'</div></html>'
);
var content = make(
'<div>Foo ' +
' <div id="a">Old A</div> A ' +
' <div id="b">Old B</div> B ' +
' <div id="c">Old C</div> C ' +
' <div id="d">Old D</div> D ' +
' <div id="e">Old E</div> E ' +
'</div>'
);
var btn = make('<button hx-get="/test" hx-ext="multi-swap" hx-swap="multi:#a:outerHTML,#b:beforeend,#c:afterend,#d:beforebegin,#e:delete">Click Me!</button>');
btn.click();
this.server.respond();
should.equal(content.outerHTML,
'<div>Foo ' +
' <div id="a">New A</div> A ' +
' <div id="b">Old B<b>New B</b></div> B ' +
' <div id="c">Old C</div>New C C ' +
' New D<div id="d">Old D</div> D ' +
' E ' +
'</div>'
);
});
});

View File

@ -134,6 +134,9 @@
<script src="../src/ext/disable-element.js"></script>
<script src="ext/disable-element.js"></script>
<script src="../src/ext/multi-swap.js"></script>
<script src="ext/multi-swap.js"></script>
<!-- events last so they don't screw up other tests -->
<script src="core/events.js"></script>

View File

@ -952,6 +952,7 @@ Htmx includes some extensions that are tested against the htmx code base. Here
| [`client-side-templates`](/extensions/client-side-templates) | support for client side template processing of JSON responses
| [`path-deps`](/extensions/path-deps) | an extension for expressing path-based dependencies [similar to intercoolerjs](http://intercoolerjs.org/docs.html#dependencies)
| [`class-tools`](/extensions/class-tools) | an extension for manipulating timed addition and removal of classes on HTML elements
| [`multi-swap`](/extensions/multi-swap) | allows to swap multiple elements with different swap methods
See the [extensions page](/extensions#included) for a complete list.

View File

@ -75,6 +75,7 @@ See the individual extension documentation for more details.
| [`loading-states`](/extensions/loading-states) | allows you to disable inputs, add and remove CSS classes to any element while a request is in-flight.
| [`method-override`](/extensions/method-override) | use the `X-HTTP-Method-Override` header for non-`GET` and `POST` requests
| [`morphdom-swap`](/extensions/morphdom-swap) | an extension for using the [morphdom](https://github.com/patrick-steele-idem/morphdom) library as the swapping mechanism in htmx.
| [`multi-swap`](/extensions/multi-swap) | allows to swap multiple elements with different swap methods
| [`path-deps`](/extensions/path-deps) | an extension for expressing path-based dependencies [similar to intercoolerjs](http://intercoolerjs.org/docs.html#dependencies)
| [`preload`](/extensions/preload) | preloads selected `href` and `hx-get` targets based on rules you control.
| [`remove-me`](/extensions/remove-me) | allows you to remove an element after a given amount of time

View File

@ -0,0 +1,71 @@
---
layout: layout.njk
title: </> htmx - multi-swap extension
---
## The `multi-swap` extension
This extension allows you to swap multiple elements marked with the `id` attribute from the HTML response. You can also choose for each element which [swap method](/docs/#swapping) should be used.
Multi-swap can help in cases where OOB ([Out of Band Swaps](/docs/#oob_swaps)) is not enough for you. OOB requires HTML tags marked with `hx-swap-oob` attributes to be at the TOP level of HTML, which significantly limited its use. With OOB is not possible to swap multiple elements arbitrarily placed and nested in the DOM tree.
It is a very powerful tool in conjunction with `hx-boost` and `preload` extension.
#### Usage
1. Set `hx-ext="multi-swap"` attribute on `<body>`, on some parent element, or on each action element that should trigger an action (typically anchors or buttons).
2. On your action elements set `hx-swap="multi:ID-SELECTORS"`, e.g. `hx-swap="multi:#id1,#id2:outerHTML,#id3:afterend"`.
3. If you're not using e.g. `hx-get` to enable HTMX behavior, set `hx-boost="true"` on your action elements, or on some parent element, so that all elements inherit the hx-boost setting.
Selectors must be separated by a comma (without surrounding spaces) and a colon with the desired swap method can optionally be placed after the selector. Default swap method is `innerHTML`.
```html
<body hx-boost="true" hx-ext="multi-swap">
<-- simple example how to swap #id1 and #id2 from /example by innerHTML (default swap method) -->
<button hx-get="/example" hx-swap="multi:#id1,#id2">Click to swap #id1 and #id2 content</button>
<-- advanced example how to swap multiple elements from /example by different swap methods -->
<a href="/example" hx-swap="multi:#id1,#id2:outerHTML,#id3:beforeend,#id4:delete">Click to swap #id1 and #id2, extend #id3 content and delete #id4 element</a>
<div id="id1">Old 1 content</div>
<div id="id2">Old 2 content</div>
<div id="id3">Old 3 content</div>
<div id="id4">Old 4 content</div>
</body>
```
**Real world example with preloading**
The use case below shows how to ensure that only the `#submenu` and `#content` elements are redrawn when the main menu items are clicked. Thanks to the combination with the preload extension, the page, including its images, is preloaded on `mouseover` event.
```html
<head>
<script src="/path/to/htmx.js"></script>
<script src="/path/to/ext/multi-swap.js"></script>
<script src="/path/to/ext/preload.js"></script>
</head>
<body hx-ext="multi-swap,preload">
<header>...</header>
<menu hx-boost="true">
<ul>
<li><a href="/page-1" hx-swap="multi:#submenu,#content" preload="mouseover" preload-images="true">Page 1</a></li>
<li><a href="/page-2" hx-swap="multi:#submenu,#content" preload="mouseover" preload-images="true">Page 2</a></li>
</ul>
<div id="submenu">... submenu contains items by selected top-level menu ...</div>
<menu>
<main id="content">...</div>
<footer>...</footer>
</body>
```
#### Notes and limitations
* Attribute `hx-swap` value **must not contain spaces**, otherwise only the part of the value up to the first space will be accepted.
* If the `delete` swap method is used, the HTML response must also contain deleted element (it can be empty div with `id` attribute).
* Only elements with an `id` selector are supported, as the function internally uses OOB internal method. So it is not possible to use `class` or any other selectors.
#### Source
<https://unpkg.com/htmx.org/dist/ext/multi-swap.js>