| 1 | package Uniform::HTMX::Dancer2; | ||
| 2 | |||
| 3 | 1 | ▶ | use strict; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 4 | 1 | ▶ | use warnings; |
|
Subroutine
BEGIN: called CC=1 SCAR=0.0
| |||
| 5 | 0 | ▶ | use Dancer2::Plugin; |
|
Subroutine
BEGIN: called CC=1 SCAR=2.6
| |||
| 6 | use Dancer2::Core::Hook; | ||
| 7 | use Uniform::HTMX; | ||
| 8 | |||
| 9 | our $VERSION = '1.00'; | ||
| 10 | |||
| 11 | # One driver, shared by every request. driver() hands back a coderef that | ||
| 12 | # builds a fresh Uniform::HTMX (sub)instance per call - see "extending | ||
| 13 | # Uniform::HTMX" in the Uniform::HTMX docs. | ||
| 14 | my $htmx_driver = Uniform::HTMX->driver( | ||
| 15 | extract => sub { | ||
| 16 | my ($app) = @_; | ||
| 17 | my $headers = $app->request->headers; | ||
| 18 | return map { $_ => scalar $headers->header($_) } | ||
| 19 | $headers->header_field_names; | ||
| 20 | }, | ||
| 21 | apply => sub { | ||
| 22 | my ( $self, $app, $out_headers ) = @_; | ||
| 23 | for my $name ( keys %$out_headers ) { | ||
| 24 | $app->response->header( $name => $out_headers->{$name} ); | ||
| 25 | } | ||
| 26 | }, | ||
| 27 | ); | ||
| 28 | |||
| 29 | # Flush whatever headers were accumulated on the request's Uniform::HTMX | ||
| 30 | # instance (if one was ever created) into the real response, right before | ||
| 31 | # Dancer2 sends it. | ||
| 32 | on_plugin_import { | ||
| 33 | my $dsl = shift; | ||
| 34 | $dsl->app->add_hook( | ||
| 35 | Dancer2::Core::Hook->new( | ||
| 36 | name => 'after', | ||
| 37 | code => sub { | ||
| 38 | my $app = $dsl->app; | ||
| 39 | my $instance = $app->request->var('_uniform_htmx'); | ||
| 40 | $instance->apply($app) if $instance; | ||
| 41 | }, | ||
| 42 | ) | ||
| 43 | ); | ||
| 44 | }; | ||
| 45 | |||
| 46 | register htmx => sub { | ||
| 47 | my $dsl = shift; | ||
| 48 | my $app = $dsl->app; | ||
| 49 | |||
| 50 | # Cache one instance per request so repeated calls to `htmx` within the | ||
| 51 | # same route accumulate onto the same outbound headers. | ||
| 52 | my $instance = $app->request->var('_uniform_htmx'); | ||
| 53 | unless ($instance) { | ||
| 54 | $instance = $htmx_driver->($app); | ||
| 55 | $app->request->var( _uniform_htmx => $instance ); | ||
| 56 | } | ||
| 57 | |||
| 58 | return $instance; | ||
| 59 | }; | ||
| 60 | |||
| 61 | register is_htmx => sub { | ||
| 62 | my $dsl = shift; | ||
| 63 | return $dsl->htmx->is_htmx ? 1 : 0; | ||
| 64 | }; | ||
| 65 | |||
| 66 | register_plugin; | ||
| 67 | |||
| 68 | 1; | ||
| 69 | |||
| 70 | __END__ | ||