blib/lib/Web/Components/Navigation.pm untested

filter: Statementstmt 0.0% 0 / 224 Branchbran 0.0% 0 / 38 Conditioncond 0.0% 0 / 27 MC/DCmcdc 0.0% 0 / 18 Subroutinesub 0.0% 0 / 24 Podpod 0.0% 0 / 11 totaltotal 0.0% 0 / 342 CC 16 SCAR 22.1
CC
16
Cov
0%
item
30.0
_add_global
20.0
crud
6.0
CRAP 9.1
1 package Web::Components::Navigation;
2  
3 use Web::ComposableRequest::Constants qw( EXCEPTION_CLASS FALSE NUL SPC TRUE );
4  
5 use HTTP::Status qw( HTTP_OK );
6 use Unexpected::Types qw( ArrayRef Bool HashRef Object PositiveInt Str );
7 use Web::Components::Util qw( clear_redirect formpost throw );
8 use Ref::Util qw( is_hashref );
9 use Scalar::Util qw( blessed );
10 use Type::Utils qw( class_type );
11 use Unexpected::Functions qw( UnknownMethod Unspecified );
12 use HTML::Tiny;
13 use JSON::MaybeXS;
14 use Try::Tiny;
15 use Moo;
16  
17 =encoding utf-8
18  
19 =head1 Name
20  
21 Web::Components::Navigation - Context sensitive menu builder
22  
23 =head1 Synopsis
24  
25 use Web::Components::Navigation;
26  
27 =head1 Description
28  
29 Context sensitive menu builder
30  
31 =head2 JavaScript
32  
33 Files F<wcom-*.js> are included in the F<share/js> directory of the source
34 tree. These will be installed to the F<File::ShareDir> distribution level
35 shared data files. Nothing further is done with these files. They should be
36 concatenated in sort order by filename and the result placed under the
37 webservers document root. Link to this from the web applications pages. Doing
38 this is outside the scope of this distribution
39  
40 =head1 Configuration and Environment
41  
42 Defines the following attributes;
43  
44 =over 3
45  
46 =item C<confirm_message>
47  
48 Immutable string. The default "Are you sure ?" message
49  
50 =cut
51  
52 has 'confirm_message' => is => 'ro', isa => Str, default => 'Are you sure ?';
53  
54 =item C<container_class>
55  
56 Lazy string combining C<container_name> and C<container_layout>. This can be
57 applied as a class name to the HTML container element by the application's
58 page layout template
59  
60 =cut
61  
62 has 'container_class' =>
63 is => 'lazy',
64 isa => Str,
65 default => sub {
66 my $self = shift;
67  
68 return $self->container_name . SPC . $self->container_layout;
69 };
70  
71 =item C<container_layout>
72  
73 A mutable string which defaults to C<centred>. Used as a class name in the HTML
74 it is also shared with the JS code
75  
76 =cut
77  
78 has 'container_layout' => is => 'rw', isa => Str, default => 'centred';
79  
80 =item C<container_name>
81  
82 An immutable string which defaults to C<standard>. Used as a class name in the
83 HTML it is also shared with the JS code
84  
85 =cut
86  
87 has 'container_name' => is => 'ro', isa => Str, default => 'standard';
88  
89 =item C<container_tag>
90  
91 An immutable string which default to C<div>. The HTML element to render
92  
93 =cut
94  
95 has 'container_tag' => is => 'ro', isa => Str, default => 'div';
96  
97 =item C<content_class>
98  
99 A lazy immutable string which defaults to C<content_name>
100  
101 =cut
102  
103 has 'content_class' =>
104 is => 'lazy',
105 isa => Str,
106 default => sub { $_[0]->content_name };
107  
108 =item C<content_name>
109  
110 An immutable string which defaults to C<panel>. Used as an id and a class name
111 in the HTML it is also shared with the JS code
112  
113 =cut
114  
115 has 'content_name' => is => 'ro', isa => Str, default => 'panel';
116  
117 =item C<context>
118  
119 An immutable required weak reference to the C<context> object
120  
121 =cut
122  
123 has 'context' =>
124 is => 'ro',
125 isa => Object,
126 required => TRUE,
127 weak_ref => TRUE;
128  
129 =item C<control_icon>
130  
131 An immutable string which defaults to C<user-settings>. The name of the symbol
132 in the SVG icons file for the user settings menu
133  
134 =cut
135  
136 has 'control_icon' => is => 'ro', isa => Str, default => 'user-settings';
137  
138 =item C<global>
139  
140 An immutable array reference with an empty default. Contains a list of action
141 paths used to create the top level of the navigation menus. It is expected
142 that this will be populated at object construction time
143  
144 =cut
145  
146 has 'global' => is => 'ro', isa => ArrayRef, default => sub { [] };
147  
148 =item C<icons>
149  
150 A lazy string representation of a partial URI. This should point to an SVG file
151 containing named symbols. Defaults to C<< img/icons.svg >>
152  
153 =cut
154  
155 has 'icons' =>
156 is => 'lazy',
157 isa => Str,
158 init_arg => undef,
159 default => sub {
160 my $self = shift;
161  
162 return $self->context->request->uri_for($self->_icons)->as_string;
163 };
164  
165 has '_icons' =>
166 is => 'ro',
167 isa => Str,
168 init_arg => 'icons',
169 default => 'img/icons.svg';
170  
171 =item C<json_view>
172  
173 An immutable string which defaults to C<json>. Stashed by C<finalise> as the
174 view which will serialise the response as JSON
175  
176 =cut
177  
178 has 'json_view' => is => 'ro', isa => Str, default => 'json';
179  
180 =item C<link_display>
181  
182 A lazy string which defaults to either the value is the C<session> if it
183 exists or the string C<both>. An enumerated type with values; C<both>, C<icon>,
184 or C<text>. Controls how the C<global> menu display links
185  
186 =cut
187  
188 has 'link_display' =>
189 is => 'lazy',
190 isa => Str,
191 init_arg => undef,
192 default => sub {
193 my $self = shift;
194 my $session = $self->context->session;
195  
196 return $session->link_display || $self->_link_display;
197 };
198  
199 has '_link_display' =>
200 is => 'ro',
201 isa => Str,
202 init_arg => 'link_display',
203 default => 'both';
204  
205 =item C<logo>
206  
207 A optional lazy string representation of a partial URI with a null
208 default. This should point to an image file containing the logo if one is
209 required
210  
211 =cut
212  
213 has 'logo' =>
214 is => 'lazy',
215 isa => Str,
216 init_arg => undef,
217 default => sub {
218 my $self = shift;
219  
220 return $self->context->request->uri_for($self->_logo)->as_string
221 if $self->_logo;
222  
223 return NUL;
224 };
225  
226 has '_logo' => is => 'ro', isa => Str, init_arg => 'logo', default => NUL;
227  
228 =item C<media_break>
229  
230 An immutable positive integer with a default of C<680> pixels. When the
231 display window's <innerWidth> drop below this (due to a resize event)
232 C<link_display> is set to C<icon> which reduces the display width requirement
233  
234 =cut
235  
236 has 'media_break' => is => 'ro', isa => PositiveInt, default => 680;
237  
238 =item C<menu_location>
239  
240 A lazy string which defaults to C<header>. Can be set to C<sidebar>. Effects
241 where the navigation menus are rendered
242  
243 =cut
244  
245 has 'menu_location' =>
246 is => 'lazy',
247 isa => Str,
248 init_arg => undef,
249 default => sub {
250 my $self = shift;
251 my $session = $self->context->session;
252  
253 return $session->menu_location || $self->_menu_location;
254 };
255  
256 has '_menu_location' =>
257 is => 'ro',
258 isa => Str,
259 init_arg => 'menu_location',
260 default => 'header';
261  
262 =item C<message_action>
263  
264 An immutable string which defaults to C<api/navigation_messages>. This is the
265 action path for the API call that the message object in the JS will make to
266 collect messages
267  
268 =cut
269  
270 has 'message_action' =>
271 is => 'ro',
272 isa => Str,
273 default => 'api/navigation_messages';
274  
275 =item C<messages>
276  
277 An immutable hash reference with an empty default. The attributes are used to
278 configure the JS message collection and display code. Attributes are;
279  
280 =over 3
281  
282 =item buffer-limit
283  
284 Maximum number of messages to buffer. Defaults to C<3>
285  
286 =item display-time
287  
288 How long in seconds to display each message for. Defaults to C<20> seconds
289  
290 =back
291  
292 =cut
293  
294 has 'messages' => is => 'ro', isa => HashRef, default => sub { {} };
295  
296 =item C<model>
297  
298 An immutable required object reference to the model component that is handling
299 the current request
300  
301 =cut
302  
303 has 'model' => is => 'ro', isa => Object, required => TRUE;
304  
305 =item C<title>
306  
307 An immutable string which defaults to null. If set will be displayed as the
308 application title along with the logo in the page header
309  
310 =cut
311  
312 has 'title' => is => 'ro', isa => Str, default => NUL;
313  
314 =item C<title_abbrev>
315  
316 An immutable string which defaults to C<Nav>. Used to set the pages C<title>
317 attribute in the HTML head. This is used in turn is used by the browser to
318 create history links (the back button). Would set this from configuration to
319 the abbreviation for the application
320  
321 =cut
322  
323 has 'title_abbrev' => is => 'ro', isa => Str, default => 'Nav';
324  
325 =item C<title_entry>
326  
327 A lazy string. The default constructor sets it to the current pages navigation
328 label. This is appended to C<title_abbrev> to form the labels in the browser
329 history
330  
331 =cut
332  
333 has 'title_entry' =>
334 is => 'lazy',
335 isa => Str,
336 default => sub {
337 my $self = shift;
338 my @parts = split m{ / }mx, $self->context->action;
339 my $label = $self->_get_nav_label($parts[0] . '/' . $parts[-1]);
340  
341 return (split m{ \| }mx, $label)[0] // NUL;
342 };
343  
344 # Private attributes
345 has '_base_url' =>
346 is => 'lazy',
347 isa => class_type('URI'),
348 default => sub {
349 return shift->context->request->uri_for(NUL);
350 };
351  
352 has '_container' =>
353 is => 'lazy',
354 isa => Str,
355 default => sub {
356 my $self = shift;
357 my $tag = $self->container_tag;
358  
359 return $self->_html->$tag($self->_data);
360 };
361  
362 has '_data' =>
363 is => 'lazy',
364 isa => HashRef,
365 default => sub {
366 my $self = shift;
367 my $location = 'navigation-' . $self->menu_location;
368 my $display = 'link-display-' . $self->link_display;
369  
370 return {
371 'id' => 'navigation',
372 'class' => "navigation ${location} ${display}",
373 'data-navigation-config' => $self->_json->encode({
374 'menus' => $self->_menus,
375 'messages' => $self->_messages,
376 'moniker' => $self->model->moniker,
377 'properties' => {
378 'base-url' => $self->_base_url,
379 'confirm' => $self->confirm_message,
380 'container-layout' => $self->container_layout,
381 'container-name' => $self->container_name,
382 'content-name' => $self->content_name,
383 'control-icon' => $self->control_icon,
384 'icons' => $self->icons,
385 'link-display' => $self->link_display,
386 'location' => $self->menu_location,
387 'logo' => $self->logo,
388 'media-break' => $self->media_break,
389 'skin' => $self->context->session->skin,
390 'title' => $self->title,
391 'title-abbrev' => $self->title_abbrev,
392 'verify-token' => $self->context->verification_token,
393 'version' => MCat->VERSION,
394 },
395 }),
396 };
397 };
398  
399 has '_html' =>
400 is => 'ro',
401 isa => class_type('HTML::Tiny'),
402 default => sub { HTML::Tiny->new };
403  
404 has '_json' =>
405 is => 'ro',
406 isa => class_type(JSON::MaybeXS::JSON),
407 default => sub {
408 return JSON::MaybeXS->new( convert_blessed => TRUE, utf8 => FALSE );
409 };
410  
411 has '_lists' => is => 'ro', isa => HashRef, default => sub { {} };
412  
413 has '_menus' =>
414 is => 'lazy',
415 isa => HashRef,
416 default => sub {
417 my $self = shift;
418  
419 return { map { $_ => $self->_lists->{$_} } @{$self->_order} };
420 };
421  
422 has '_messages' =>
423 is => 'lazy',
424 isa => HashRef,
425 default => sub {
426 my $self = shift;
427 my $context = $self->context;
428  
429 return {
430 %{$self->messages},
431 'messages-url' => $context->uri_for_action($self->message_action)
432 };
433 };
434  
435 has '_name' => is => 'rwp', isa => Str, default => NUL;
436  
437 has '_order' => is => 'ro', isa => ArrayRef, default => sub { [] };
438  
439 =back
440  
441 =head1 Subroutines/Methods
442  
443 Defines the following methods;
444  
445 =over 3
446  
447 =item C<BUILDARGS>
448  
449 Wraps around the constructor call. If the C<context> object has a reference to
450 the C<config> object which has a reference to a C<navigation> attribute, then
451 that hash reference is merged into the attributes passed to the constructor
452  
453 =cut
454  
455 around 'BUILDARGS' => sub {
456 my ($orig, $self, @args) = @_;
457  
458 my $attr = $orig->($self, @args);
459 my $context = $attr->{context};
460  
461 throw Unspecified, ['context'] unless $context;
462  
463 return $attr unless $context->can('config');
464  
465 my $config = $context->config;
466  
467 throw UnknownMethod, [blessed $config, 'navigation']
468 unless $config->can('navigation');
469  
470 return { %{$attr}, %{$config->navigation} };
471 };
472  
473 =item C<crud>
474  
475 $self = $self->crud($moniker, $existing_id, $create_id);
476  
477 A convenience method which calls C<item> up to four times. If C<create_id> is
478 passed C<item> is called with an action path of C<moniker/create>. The
479 C<existing_id> is required and C<item> is called three times with the action
480 paths; C<moniker/delete>, C<moniker/edit> and C<moniker/view>
481  
482 =cut
483  
484 sub crud {
485 my ($self, $moniker, $existing_id, $create_id) = @_;
486  
487 $self->item("${moniker}/create", [$create_id]) if $create_id;
488 $self->item(formpost, "${moniker}/delete", [$existing_id]);
489 $self->item("${moniker}/edit", [$existing_id]);
490 $self->item("${moniker}/view", [$existing_id]);
491 return $self;
492 }
493  
494 =item C<finalise>
495  
496 Populates the stash with the data that represents the menu which will be
497 serialised to JSON
498  
499 =cut
500  
501 sub finalise {
502 my $self = shift;
503 my $context = $self->context;
504 my $request = $context->request;
505  
506 return unless $self->is_script_request
507 && $request->query_parameters->{navigation};
508  
509 $self->_add_global;
510  
511 my $data = {
512 'container-layout' => $self->container_layout,
513 'menus' => $self->_menus,
514 'title-entry' => $self->title_entry,
515 'verify-token' => $context->verification_token,
516 };
517  
518 $context->stash(
519 code => HTTP_OK,
520 finalised => TRUE,
521 json => $data,
522 view => $self->json_view
523 );
524 return;
525 }
526  
527 =item C<finalise_script_request>
528  
529 If C<is_script_request> is true then stash an OK HTTP return code. When using
530 JS navigation all HTTP responses must be OK or the browser (which sniffs the
531 fetch responses) will automatically navigate
532  
533 =cut
534  
535 sub finalise_script_request {
536 my $self = shift;
537  
538 $self->context->stash(code => HTTP_OK) if $self->is_script_request;
539  
540 return;
541 }
542  
543 =item C<is_script_request>
544  
545 Returns true if the request has come from the JS in the browser
546  
547 =cut
548  
549 sub is_script_request {
550 my $self = shift;
551 my $header = $self->context->request->header('x-requested-with') // NUL;
552  
553 return lc $header eq 'xmlhttprequest' ? TRUE : FALSE;
554 }
555  
556 =item C<item>
557  
558 $self = $self->item('action path', $args, $params);
559 $self = $self->item(formpost, 'action path', $args, $params);
560  
561 The first example will add a single link to the current C<list>. The display
562 text is set by the C<Nav> subroutine attribute of the endpoint, the C<href>
563 is supplied by C<context> C<uri_for_action>
564  
565 In the second example C<formpost> is imported from L<Web::Components::Util>
566 and causes the rendered menu item to be a form with a button on it (it is
567 expected that this will be styled like a link). This is used for delete
568 operations since we don't do deletes with a GET
569  
570 =cut
571  
572 sub item {
573 my ($self, @args) = @_;
574  
575 my $label;
576  
577 if (is_hashref $args[0]) {
578 $label = shift @args;
579 $label->{name} = $self->_get_nav_label($args[0]);
580 }
581 else { $label = $self->_get_nav_label($args[0]) }
582  
583 if ($self->model->is_authorised($self->context, $args[0])) {
584 my $list = $self->_lists->{$self->_name}->[1];
585 my ($text, $icon);
586  
587 if (is_hashref $label) {
588 ($text, $icon) = split m{ \| }mx, $label->{name};
589 $label->{name} = $text;
590 $text = $label;
591 }
592 else { ($text, $icon) = split m{ \| }mx, $label }
593  
594 $icon = $self->context->request->uri_for($icon)
595 if $icon && $icon =~ m{ / }mx;
596  
597 push @{$list}, [$text => $self->_uri(@args), $icon];
598 }
599 else { clear_redirect $self->context }
600  
601 return $self;
602 }
603  
604 =item C<list>
605  
606 $self = $self->list('list name', 'optional title');
607  
608 Sets the current list to the name provided. If this list does not exist it
609 is created. Once a list has been created C<item> is called to add entries to it
610  
611 =cut
612  
613 sub list {
614 my ($self, $name, $title) = @_;
615  
616 $self->_set__name($name);
617  
618 unless (exists $self->_lists->{$name}) {
619 $self->_lists->{$name} = [ $title // NUL, [] ];
620 push @{$self->_order}, $name;
621 }
622  
623 return $self;
624 }
625  
626 =item C<menu>
627  
628 $self = $self->menu('list name');
629  
630 If the named list exists add it to the current list. This is how you created
631 nested lists
632  
633 =cut
634  
635 sub menu {
636 my ($self, $name) = @_;
637  
638 my $lists = $self->_lists;
639  
640 push @{$lists->{$self->_name}->[1]}, $name if exists $lists->{$name};
641  
642 return $self;
643 }
644  
645 =item C<render>
646  
647 Returns the HTML for inclusion on the web page
648  
649 =cut
650  
651 sub render {
652 my $self = shift;
653 my $output;
654  
655 $self->_add_global;
656  
657 try { $output = $self->_container }
658 catch { $output = $_ };
659  
660 return $output;
661 }
662  
663 # Private methods
664 sub _add_global {
665 my $self = shift;
666 my $list = $self->list('_global');
667  
668 for my $action (@{$self->global}) {
669 my ($moniker, $method) = split m{ / }mx, $action;
670  
671 if ($self->model->is_authorised($self->context, $action)) {
672 if ($method and $method eq 'menu') {
673 $self->context->models->{$moniker}->menu($self->context);
674 $self->_set__name('_global');
675 }
676  
677 push @{$self->_lists->{$self->_name}->[1]}, $moniker
678 if exists $self->_lists->{$moniker};
679  
680 $list->item($action);
681 }
682 else { clear_redirect $self->context }
683 }
684  
685 return;
686 }
687  
688 sub _get_nav_label {
689 my ($self, $action) = @_;
690  
691 my $attr = try { $self->context->get_attributes($action) };
692  
693 return $attr->{Nav}->[0] if $attr && defined $attr->{Nav};
694  
695 return NUL;
696 }
697  
698 sub _uri {
699 my ($self, @args) = @_;
700  
701 my $action = $args[0];
702  
703 return NUL if $action =~ m{ /menu \z }mx;
704  
705 return $self->context->uri_for_action(@args);
706 }
707  
708 use namespace::autoclean;
709  
710 1;
711  
712 __END__