Skip to content

Commit 463a474

Browse files
authored
feat: Improve hxLocation() redirect (#80)
* feat: Improve `hxLocation()` defining the path * tests: Add tests for `hxLocation()` * docs: Add note for `hxLocation()`
1 parent fda8a5c commit 463a474

File tree

3 files changed

+21
-0
lines changed

3 files changed

+21
-0
lines changed

docs/redirect_response.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ Sets the `HX-Location` header to redirect without reloading the whole page.
1313
```php
1414
return redirect()->hxLocation('/path');
1515
```
16+
For convenience, the set path with `http(s)://` will be converted to relative. Like this: `http://example.com/articles/` it will become `/articles/`.
1617

1718
For more information, please see [hx-location](https://htmx.org/headers/hx-location/).
1819

src/HTTP/RedirectResponse.php

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,11 @@ public function hxLocation(
2121
?array $values = null,
2222
?array $headers = null
2323
): RedirectResponse {
24+
// single_service
25+
if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
26+
$path = (string) service('uri', $path, false)->withScheme('')->setHost('');
27+
}
28+
2429
$data = ['path' => '/' . ltrim($path, '/')];
2530

2631
if ($source !== null) {

tests/HTTP/RedirectResponseTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,21 @@ public function testHxLocation(): void
3131
$this->assertSame(200, $this->response->getStatusCode());
3232
}
3333

34+
public function testHxLocationWithFullPath(): void
35+
{
36+
$this->response = $this->response->hxLocation('https://example.com/foo1');
37+
38+
$this->assertSame(json_encode(['path' => '/foo1']), $this->response->getHeaderLine('HX-Location'));
39+
40+
$this->response = $this->response->hxLocation('http://example.com/foo2');
41+
42+
$this->assertSame(json_encode(['path' => '/foo2']), $this->response->getHeaderLine('HX-Location'));
43+
44+
$this->response = $this->response->hxLocation('http://example.com/foo3?page=1&sort=ASC#top');
45+
46+
$this->assertSame(json_encode(['path' => '/foo3?page=1&sort=ASC#top']), $this->response->getHeaderLine('HX-Location'));
47+
}
48+
3449
public function testHxLocationWithSourceAndEvent(): void
3550
{
3651
$this->response = $this->response->hxLocation(path: '/foo', source: '#myElem', event: 'doubleclick');

0 commit comments

Comments
 (0)