Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
1cg committed Sep 20, 2024
2 parents d61b000 + 02aa8fd commit c2a29ce
Show file tree
Hide file tree
Showing 11 changed files with 117 additions and 17 deletions.
17 changes: 17 additions & 0 deletions test/attributes/hx-vals.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,23 @@ describe('hx-vals attribute', function() {
div.innerHTML.should.equal('Clicked!')
})

it('Dynamic hx-vals using spread operator works', function() {
this.server.respondWith('POST', '/vars', function(xhr) {
var params = getParameters(xhr)
params.v1.should.equal('test')
params.v2.should.equal('42')
xhr.respond(200, {}, 'Clicked!')
})
window.foo = function() {
return { v1: 'test', v2: 42 }
}
var div = make("<div hx-post='/vars' hx-vals='js:{...foo()}'></div>")
div.click()
this.server.respond()
div.innerHTML.should.equal('Clicked!')
delete window.foo
})

it('hx-vals can be on parents', function() {
this.server.respondWith('POST', '/vars', function(xhr) {
var params = getParameters(xhr)
Expand Down
8 changes: 5 additions & 3 deletions www/content/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,15 +126,17 @@ Note that using a [meta tag](@/docs.md#config) is the preferred mechanism for se
* `wsReconnectDelay:'full-jitter'` - string/function: the default implementation of `getWebSocketReconnectDelay` for reconnecting after unexpected connection loss by the event code `Abnormal Closure`, `Service Restart` or `Try Again Later`
* `wsBinaryType:'blob'` - string: the [the type of binary data](https://developer.mozilla.org/docs/Web/API/WebSocket/binaryType) being received over the WebSocket connection
* `disableSelector:"[hx-disable], [data-hx-disable]"` - array of strings: htmx will not process elements with this attribute on it or a parent
* `scrollBehavior:'smooth'` - string: the behavior for a boosted link on page transitions. The allowed values are `auto` and `smooth`. Smooth will smoothscroll to the top of the page while auto will behave like a vanilla link.
* `scrollBehavior:'instant'` - string: the scroll behavior when using the [show](@/attributes/hx-swap.md#scrolling-scroll-show) modifier with `hx-swap`. The allowed values are `instant` (scrolling should happen instantly in a single jump), `smooth` (scrolling should animate smoothly) and `auto` (scroll behavior is determined by the computed value of [scroll-behavior](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior)).
* `defaultFocusScroll:false` - boolean: if the focused element should be scrolled into view, can be overridden using the [focus-scroll](@/attributes/hx-swap.md#focus-scroll) swap modifier
* `getCacheBusterParam:false` - boolean: if set to true htmx will append the target element to the `GET` request in the format `org.htmx.cache-buster=targetElementId`
* `globalViewTransitions:false` - boolean: if set to `true`, htmx will use the [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) API when swapping in new content.
* `methodsThatUseUrlParams:["get"]` - array of strings: htmx will format requests with these methods by encoding their parameters in the URL, not the request body
* `methodsThatUseUrlParams:["get", "delete"]` - array of strings: htmx will format requests with these methods by encoding their parameters in the URL, not the request body
* `selfRequestsOnly:true` - boolean: whether to only allow AJAX requests to the same domain as the current document
* `ignoreTitle:false` - boolean: if set to `true` htmx will not update the title of the document when a `title` tag is found in new content
* `scrollIntoViewOnBoost:true` - boolean: whether or not the target of a boosted element is scrolled into the viewport. If `hx-target` is omitted on a boosted element, the target defaults to `body`, causing the page to scroll to the top.
* `triggerSpecsCache:null` - object: the cache to store evaluated trigger specifications into, improving parsing performance at the cost of more memory usage. You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy) |
* `triggerSpecsCache:null` - object: the cache to store evaluated trigger specifications into, improving parsing performance at the cost of more memory usage. You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy)
* `htmx.config.responseHandling:[...]` - HtmxResponseHandlingConfig[]: the default [Response Handling](@/docs.md#response-handling) behavior for response status codes can be configured here to either swap or error
* `htmx.config.allowNestedOobSwaps:true` - boolean: whether to process OOB swaps on elements that are nested within the main response element. See [Nested OOB Swaps](@/attributes/hx-swap-oob.md#nested-oob-swaps).

##### Example

Expand Down
42 changes: 39 additions & 3 deletions www/content/attributes/hx-swap-oob.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,50 @@ The value of the `hx-swap-oob` can be:

If the value is `true` or `outerHTML` (which are equivalent) the element will be swapped inline.

If a swap value is given, that swap strategy will be used.
If a swap value is given, that swap strategy will be used and the encapsulating tag pair will be stripped for all strategies other than `outerHTML`.

If a selector is given, all elements matched by that selector will be swapped. If not, the element with an ID matching the new content will be swapped.

### Troublesome Tables
### Using alternate swap strategies

As mentioned previously when using swap strategies other than `true` or `outerHTML` the encapsulating tags are stripped, as such you need to excapsulate the returned data with the correct tags for the context.

When trying to insert a `<tr>` in a table that uses `<tbody>`:
```html
<tbody hx-swap-oob="beforeend:#table tbody">
<tr>
...
</tr>
</tbody>
```

A "plain" table:
```html
<table hx-swap-oob="beforeend:#table2">
<tr>
...
</tr>
</table>
```

A `<li>` may be encapsulated in `<ul>`, `<ol>`, `<div>` or `<span>`, for example:
```html
<ul hx-swap-oob="beforeend:#list1">
<li>...</li>
</ul>
```

A `<p>` can be encapsulated in `<div>` or `<span>`:
```html
<span hx-swap-oob="beforeend:#text">
<p>...</p>
</span>
```

### Troublesome Tables and lists

Note that you can use a `template` tag to encapsulate types of elements that, by the HTML spec, can't stand on their own in the
DOM (`<tr>`, `<td>`, `<th>`, `<thead>`, `<tbody>`, `<tfoot>`, `<colgroup>`, `<caption>` & `<col>`).
DOM (`<tr>`, `<td>`, `<th>`, `<thead>`, `<tbody>`, `<tfoot>`, `<colgroup>`, `<caption>`, `<col>` & `<li>`).

Here is an example with an out of band swap of a table row being encapsulated in this way:

Expand Down
18 changes: 13 additions & 5 deletions www/content/attributes/hx-vals.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@
title = "hx-vals"
+++

The `hx-vals` attribute allows you to add to the parameters that will be submitted with an AJAX request.
The `hx-vals` attribute allows you to add to the parameters that will be submitted with an AJAX request.

By default, the value of this attribute is a list of name-expression values in [JSON (JavaScript Object Notation)](https://www.json.org/json-en.html)
By default, the value of this attribute is a list of name-expression values in [JSON (JavaScript Object Notation)](https://www.json.org/json-en.html)
format.

If you wish for `hx-vals` to *evaluate* the values given, you can prefix the values with `javascript:` or `js:`.
Expand All @@ -23,12 +23,20 @@ When using evaluated code you can access the `event` object. This example includ
</div>
```

You can also use the spread operator to dynamically specify values. This allows you to include all properties from an object returned by a function:

```html
<div hx-get="/example" hx-vals='js:{...foo()}'>Get Some HTML, Including All Values from foo() in the Request</div>
```

In this example, if `foo()` returns an object like `{name: "John", age: 30}`, both `name` and `age` will be included as parameters in the request.

## Security Considerations

* By default, the value of `hx-vals` must be valid [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON).
* By default, the value of `hx-vals` must be valid [JSON](https://developer.mozilla.org/en-US/docs/Glossary/JSON).
It is **not** dynamically computed. If you use the `javascript:` prefix, be aware that you are introducing
security considerations, especially when dealing with user input such as query strings or user-generated content,
which could introduce a [Cross-Site Scripting (XSS)](https://owasp.org/www-community/attacks/xss/) vulnerability.
security considerations, especially when dealing with user input such as query strings or user-generated content,
which could introduce a [Cross-Site Scripting (XSS)](https://owasp.org/www-community/attacks/xss/) vulnerability.

## Notes

Expand Down
9 changes: 6 additions & 3 deletions www/content/docs.md
Original file line number Diff line number Diff line change
Expand Up @@ -1034,7 +1034,7 @@ htmx supports some htmx-specific response headers:

* [`HX-Location`](@/headers/hx-location.md) - allows you to do a client-side redirect that does not do a full page reload
* [`HX-Push-Url`](@/headers/hx-push-url.md) - pushes a new url into the history stack
* `HX-Redirect` - can be used to do a client-side redirect to a new location
* [`HX-Redirect`](@/headers/hx-redirect.md) - can be used to do a client-side redirect to a new location
* `HX-Refresh` - if set to "true" the client-side will do a full refresh of the page
* [`HX-Replace-Url`](@/headers/hx-replace-url.md) - replaces the current URL in the location bar
* `HX-Reswap` - allows you to specify how the response will be swapped. See [hx-swap](@/attributes/hx-swap.md) for possible values
Expand All @@ -1049,6 +1049,8 @@ For more on the `HX-Trigger` headers, see [`HX-Trigger` Response Headers](@/head
Submitting a form via htmx has the benefit of no longer needing the [Post/Redirect/Get Pattern](https://en.wikipedia.org/wiki/Post/Redirect/Get).
After successfully processing a POST request on the server, you don't need to return a [HTTP 302 (Redirect)](https://en.wikipedia.org/wiki/HTTP_302). You can directly return the new HTML fragment.

Also the response headers above are not provided to htmx for processing with 3xx Redirect response codes like [HTTP 302 (Redirect)](https://en.wikipedia.org/wiki/HTTP_302). Instead, the browser will intercept the redirection internally and return the headers and response from the redirected URL. Where possible use alternative response codes like 200 to allow returning of these response headers.

### Request Order of Operations {#request-operations}

The order of operations in a htmx request are:
Expand Down Expand Up @@ -1660,16 +1662,17 @@ listed below:
| `htmx.config.disableSelector` | defaults to `[hx-disable], [data-hx-disable]`, htmx will not process elements with this attribute on it or a parent |
| `htmx.config.withCredentials` | defaults to `false`, allow cross-site Access-Control requests using credentials such as cookies, authorization headers or TLS client certificates |
| `htmx.config.timeout` | defaults to 0, the number of milliseconds a request can take before automatically being terminated |
| `htmx.config.scrollBehavior` | defaults to 'smooth', the behavior for a boosted link on page transitions. The allowed values are `auto` and `smooth`. Smooth will smoothscroll to the top of the page while auto will behave like a vanilla link. |
| `htmx.config.scrollBehavior` | defaults to 'instant', the scroll behavior when using the [show](@/attributes/hx-swap.md#scrolling-scroll-show) modifier with `hx-swap`. The allowed values are `instant` (scrolling should happen instantly in a single jump), `smooth` (scrolling should animate smoothly) and `auto` (scroll behavior is determined by the computed value of [scroll-behavior](https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior)). |
| `htmx.config.defaultFocusScroll` | if the focused element should be scrolled into view, defaults to false and can be overridden using the [focus-scroll](@/attributes/hx-swap.md#focus-scroll) swap modifier. |
| `htmx.config.getCacheBusterParam` | defaults to false, if set to true htmx will append the target element to the `GET` request in the format `org.htmx.cache-buster=targetElementId` |
| `htmx.config.globalViewTransitions` | if set to `true`, htmx will use the [View Transition](https://developer.mozilla.org/en-US/docs/Web/API/View_Transitions_API) API when swapping in new content. |
| `htmx.config.methodsThatUseUrlParams` | defaults to `["get"]`, htmx will format requests with these methods by encoding their parameters in the URL, not the request body |
| `htmx.config.methodsThatUseUrlParams` | defaults to `["get", "delete"]`, htmx will format requests with these methods by encoding their parameters in the URL, not the request body |
| `htmx.config.selfRequestsOnly` | defaults to `true`, whether to only allow AJAX requests to the same domain as the current document |
| `htmx.config.ignoreTitle` | defaults to `false`, if set to `true` htmx will not update the title of the document when a `title` tag is found in new content |
| `htmx.config.disableInheritance` | disables attribute inheritance in htmx, which can then be overridden by the [`hx-inherit`](@/attributes/hx-inherit.md) attribute |
| `htmx.config.scrollIntoViewOnBoost` | defaults to `true`, whether or not the target of a boosted element is scrolled into the viewport. If `hx-target` is omitted on a boosted element, the target defaults to `body`, causing the page to scroll to the top. |
| `htmx.config.triggerSpecsCache` | defaults to `null`, the cache to store evaluated trigger specifications into, improving parsing performance at the cost of more memory usage. You may define a simple object to use a never-clearing cache, or implement your own system using a [proxy object](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Proxy) |
| `htmx.config.responseHandling` | the default [Response Handling](@/docs.md#response-handling) behavior for response status codes can be configured here to either swap or error |
| `htmx.config.allowNestedOobSwaps` | defaults to `true`, whether to process OOB swaps on elements that are nested within the main response element. See [Nested OOB Swaps](@/attributes/hx-swap-oob.md#nested-oob-swaps). |

</div>
Expand Down
4 changes: 4 additions & 0 deletions www/content/headers/hx-location.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,3 +28,7 @@ Path is required and is url to load the response from. The rest of the data mirr
* `values` - values to submit with the request
* `headers` - headers to submit with the request
* `select` - allows you to select the content you want swapped from a response

## Notes

Response headers are not processed on 3xx response codes. see [Response Headers](@/docs.md#response-headers)
4 changes: 4 additions & 0 deletions www/content/headers/hx-push-url.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,7 @@ The possible values for this header are:
1. A URL to be pushed into the location bar.
This may be relative or absolute, as per [`history.pushState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/pushState).
2. `false`, which prevents the browser’s history from being updated.

## Notes

Response headers are not processed on 3xx response codes. see [Response Headers](@/docs.md#response-headers)
17 changes: 17 additions & 0 deletions www/content/headers/hx-redirect.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
+++
title = "HX-Redirect Response Header"
+++

This response header can be used to trigger a client side redirection to a new url that will do a full reload of the whole page. It uses the browser to redirect to the new location which can be useful when redirecting to non htmx endpoints that may contain different HTML `head` content or scripts. See [`HX-Location`](@/headers/hx-location.md) if you want more control over the redirect or want to use ajax requests instead of full browser reloads.

A sample response would be:

```html
HX-Redirect: /test
```

Which would push the client to test as if the user had entered this url manually or clicked on a non-boosted link `<a href="/test">`

## Notes

Response headers are not processed on 3xx response codes. see [Response Headers](@/docs.md#response-headers)
4 changes: 4 additions & 0 deletions www/content/headers/hx-replace-url.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,7 @@ The possible values for this header are:
1. A URL to replace the current URL in the location bar.
This may be relative or absolute, as per [`history.replaceState()`](https://developer.mozilla.org/en-US/docs/Web/API/History/replaceState), but must have the same origin as the current URL.
2. `false`, which prevents the browser’s current URL from being updated.

## Notes

Response headers are not processed on 3xx response codes. see [Response Headers](@/docs.md#response-headers)
4 changes: 4 additions & 0 deletions www/content/headers/hx-trigger.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,3 +78,7 @@ You may also trigger multiple events with no additional details by sending event
`HX-Trigger: event1, event2`

Using events gives you a lot of flexibility to add functionality to normal htmx responses.

## Notes

Response headers are not processed on 3xx response codes. see [Response Headers](@/docs.md#response-headers)
Loading

0 comments on commit c2a29ce

Please sign in to comment.