Add loading-states extension (#805)

* Add loading-states extension

* Add extension to the extensions list

* Remove duplicate reference to client-side-templates

* Remove duplicate entry to debug

How did this happen?!
This commit is contained in:
Alejandro Schmeichler 2022-02-12 14:13:30 -04:00 committed by GitHub
parent 546e346e98
commit c50b96129e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 295 additions and 2 deletions

165
src/ext/loading-states.js Normal file
View File

@ -0,0 +1,165 @@
;(function () {
let loadingStatesUndoQueue = []
function loadingStateContainer(target) {
return htmx.closest(target, '[data-loading-states]') || document.body
}
function mayProcessUndoCallback(target, callback) {
if (document.body.contains(target)) {
callback()
}
}
function mayProcessLoadingStateByPath(elt, requestPath) {
const pathElt = htmx.closest(elt, '[data-loading-path]')
if (!pathElt) {
return true
}
return pathElt.getAttribute('data-loading-path') === requestPath
}
function queueLoadingState(sourceElt, targetElt, doCallback, undoCallback) {
const delayElt = htmx.closest(sourceElt, '[data-loading-delay]')
if (delayElt) {
const delayInMilliseconds =
delayElt.getAttribute('data-loading-delay') || 200
const timeout = setTimeout(() => {
doCallback()
loadingStatesUndoQueue.push(() => {
mayProcessUndoCallback(targetElt, () => undoCallback())
})
}, delayInMilliseconds)
loadingStatesUndoQueue.push(() => {
mayProcessUndoCallback(targetElt, () => clearTimeout(timeout))
})
} else {
doCallback()
loadingStatesUndoQueue.push(() => {
mayProcessUndoCallback(targetElt, () => undoCallback())
})
}
}
function getLoadingStateElts(loadingScope, type, path) {
return Array.from(htmx.findAll(loadingScope, `[${type}]`)).filter(
(elt) => mayProcessLoadingStateByPath(elt, path)
)
}
function getLoadingTarget(elt) {
if (elt.getAttribute('data-loading-target')) {
return Array.from(
htmx.findAll(elt.getAttribute('data-loading-target'))
)
}
return [elt]
}
htmx.defineExtension('loading-states', {
onEvent: function (name, evt) {
if (name === 'htmx:beforeRequest') {
const container = loadingStateContainer(evt.target)
const loadingStateTypes = [
'data-loading',
'data-loading-class',
'data-loading-class-remove',
'data-loading-disable',
]
let loadingStateEltsByType = {}
loadingStateTypes.forEach((type) => {
loadingStateEltsByType[type] = getLoadingStateElts(
container,
type,
evt.detail.pathInfo.path
)
})
loadingStateEltsByType['data-loading'].forEach((sourceElt) => {
getLoadingTarget(sourceElt).forEach((targetElt) => {
queueLoadingState(
sourceElt,
targetElt,
() =>
(targetElt.style.display =
sourceElt.getAttribute('data-loading') ||
'inline-block'),
() => (targetElt.style.display = 'none')
)
})
})
loadingStateEltsByType['data-loading-class'].forEach(
(sourceElt) => {
const classNames = sourceElt
.getAttribute('data-loading-class')
.split(' ')
getLoadingTarget(sourceElt).forEach((targetElt) => {
queueLoadingState(
sourceElt,
targetElt,
() =>
classNames.forEach((className) =>
targetElt.classList.add(className)
),
() =>
classNames.forEach((className) =>
targetElt.classList.remove(className)
)
)
})
}
)
loadingStateEltsByType['data-loading-class-remove'].forEach(
(sourceElt) => {
const classNames = sourceElt
.getAttribute('data-loading-class-remove')
.split(' ')
getLoadingTarget(sourceElt).forEach((targetElt) => {
queueLoadingState(
sourceElt,
targetElt,
() =>
classNames.forEach((className) =>
targetElt.classList.remove(className)
),
() =>
classNames.forEach((className) =>
targetElt.classList.add(className)
)
)
})
}
)
loadingStateEltsByType['data-loading-disable'].forEach(
(sourceElt) => {
getLoadingTarget(sourceElt).forEach((targetElt) => {
queueLoadingState(
sourceElt,
targetElt,
() => (targetElt.disabled = true),
() => (targetElt.disabled = false)
)
})
}
)
}
if (name === 'htmx:afterOnLoad') {
while (loadingStatesUndoQueue.length > 0) {
loadingStatesUndoQueue.shift()()
}
}
},
})
})()

View File

@ -64,10 +64,9 @@ against `htmx` in each distribution
| [`event-header`](/extensions/event-header) | includes a JSON serialized version of the triggering event, if any
| [`include-vals`](/extensions/include-vals) | allows you to include additional values in a request
| [`json-enc`](/extensions/json-enc) | use JSON encoding in the body of requests, rather than the default `x-www-form-urlencoded`
| [`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.
| [`client-side-templates`](/extensions/client-side-templates) | support for client side template processing of JSON responses
| [`debug`](/extensions/debug) | an extension for debugging of a particular element using htmx
| [`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,129 @@
---
layout: layout.njk
title: </> htmx - high power tools for html
---
## The `loading-states` Extension
This extension allows you to easily manage loading states while a request is in flight, including disabling elements, and adding and removing CSS classes.
### Usage
Add the `hx-ext="loading-states"` attribute to the body tag or to any parent element containing your htmx attributes.
Add the following class to your stylesheet to make sure elements are hidden by default:
```css
[data-loading] {
display: none;
}
```
### Supported attributes
- `data-loading`
Shows the element. The default style is `inline-block`, but it's possible to use any display style by specifying it in the attribute value.
```html
<div data-loading>loading</div>
<div data-loading="block">loading</div>
<div data-loading="flex">loading</div>
```
- `data-loading-class`
Adds, then removes, CSS classes to the element:
```html
<div class="transition-all ease-in-out duration-600" data-loading-class="bg-gray-100 opacity-80">
...
</div>
```
- `data-loading-class-remove`
Removes, then adds back, CSS classes from the element.
```html
<div class="p-8 bg-gray-100 transition-all ease-in-out duration-600" data-loading-class-remove="bg-gray-100">
...
</div>
```
- `data-loading-disable`
Disables an element for the duration of the request.
```html
<button data-loading-disable>Submit</button>
```
- `data-loading-delay`
Some actions may update quickly and showing a loading state in these cases may be more of a distraction. This attribute ensures that the loading state changes are applied only after 200ms if the request is not finished. The default delay can be modified through the attribute value and expressed in milliseconds:
```html
<button type="submit" data-loading-disable data-loading-delay="1000">Submit</button>
```
You can place the `data-loading-delay` attribute directly on the element you want to disable, or in any parent element.
- `data-loading-target`
Allows setting a different target to apply the loading states. The attribute value can be any valid CSS selector. The example below disables the submit button and shows the loading state when the form is submitted.
```html
<form hx-post="/save"
data-loading-target="#loading"
data-loading-class-remove="hidden">
<button type="submit" data-loading-disable>Submit</button>
</form>
<div id="loading" class="hidden">Loading ...</div>
```
- `data-loading-path`
Allows filtering the processing of loading states only for specific requests based on the request path.
```html
<form hx-post="/save">
<button type="submit" data-loading-disable data-loading-path="/save">Submit</button>
</form>
```
You can place the `data-loading-path` attribute directly on the loading state element, or in any parent element.
```html
<form hx-post="/save" data-loading-path="/save">
<button type="submit" data-loading-disable>Submit</button>
</form>
```
- `data-loading-states`
This attribute is optional and it allows defining a scope for the loading states so only elements within that scope are processed.
```html
<div data-loading-states>
<div hx-get=""></div>
<div data-loading>loading</div>
</div>
<div data-loading-states>
<div hx-get=""></div>
<div data-loading>loading</div>
</div>
<form data-loading-states hx-post="">
<div data-loading>loading</div>
</form>
```
#### Source
<https://unpkg.com/htmx.org/dist/ext/loading-states.js>