blib/lib/Term/Fabulous/Widget/Prompt.pm untested

filter: Statementstmt 0.0% 0 / 257 Branchbran 0.0% 0 / 84 Conditioncond 0.0% 0 / 63 MC/DCmcdc 0.0% 0 / 38 Subroutinesub 0.0% 0 / 20 Podpod 0.0% 0 / 1 totaltotal 0.0% 0 / 463 CC 1 SCAR 6.9
CC
1
Cov
0%
BUILDARGS
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package Term::Fabulous::Widget::Prompt;
2  
3 use v5.32;
4 use warnings;
5 use feature 'signatures';
6 no warnings 'experimental::signatures';
7  
8 use Object::Pad 0.825;
9  
10 use Term::Fabulous::Widget::Dialog;
11  
12 our $VERSION = '0.03';
13  
14 class Term::Fabulous::Widget::Prompt
15 :isa(Term::Fabulous::Widget::Dialog)
16 :strict(params)
17 {
18 use Clay::XS qw(sizing_fixed sizing_grow CLAY_TOP_TO_BOTTOM);
19 use List::Util qw(first max);
20 use Scalar::Util qw(blessed weaken);
21 use Term::Fabulous::Check qw(boolean describe optional positive_integer string);
22 use Term::Fabulous::Event::Answer;
23 use Term::Fabulous::Unicode qw(string_columns);
24 use Term::Fabulous::Widget::Box;
25 use Term::Fabulous::Widget::Button;
26 use Term::Fabulous::Widget::RichText;
27 use Term::Fabulous::Widget::Text;
28 use Term::Fabulous::Widget::TextField;
29  
30 use constant DEFAULT_WIDTH => 60;
31 use constant CANCEL => 'cancel';
32  
33 field $title :param = '';
34 field $message :param = '';
35 field $focus :param = undef;
36 field $check :param = undef;
37  
38 field @_fields; # [ { name, label, input } ], in order
39 field @_buttons; # [ { id, label, primary, widget } ], in order
40 field $_title_text;
41 field $_message_text;
42 field $_error_text;
43  
44 # A prompt is a dialog with room around its text: two columns at the
45 # sides, a row above and below, and the width the program asks for,
46 # or the width of the screen when that is narrower.
47 sub BUILDARGS ( $class, %params ) {
48 my $width = positive_integer( $class, width => $params{width} // DEFAULT_WIDTH );
49 my $layout = $params{layout} // {};
50 $params{layout} = {
51 padding => { left => 2, right => 2, top => 1, bottom => 1 },
52 %$layout,
53 sizing => { width => sizing_grow( 0, $width ), %{ $layout->{sizing} // {} } },
54 };
55 return $class->SUPER::BUILDARGS(%params);
56 }
57  
58 ADJUST :params ( :$fields = [], :$buttons = [ { id => 'ok', label => 'OK', primary => 1 } ], :$width = undef ) {
59 $title = string( $self, title => $title );
60 $message = string( $self, message => $message );
61 die ref($self) . ": check must be a code reference or undef, got " . describe($check) if defined $check && ref $check ne 'CODE';
62 @_fields = $self->_parsed_fields($fields);
63 @_buttons = $self->_parsed_buttons($buttons);
64 $focus = $self->_checked_focus($focus);
65  
66 weaken( my $weak_self = $self );
67 $_title_text = Term::Fabulous::Widget::Text->new( text => $title, bold => 1 );
68 $_message_text = Term::Fabulous::Widget::RichText->new( markup => $message );
69 $_error_text = Term::Fabulous::Widget::Text->new( text => '' );
70 $self->add_child($_title_text) if length $title;
71 $self->add_child($_message_text) if length $message;
72 $self->add_child( $self->_field_rows ) if @_fields;
73 $self->add_child( $self->_button_row );
74  
75 $self->on( Submit => sub ($event) { $weak_self->answer( $weak_self->default_button ); return } );
76 }
77  
78 # ---------------------------------------------------------------------
79 # Parameters
80 # ---------------------------------------------------------------------
81  
82 method _parsed_fields ($fields) {
83 die ref($self) . ": fields must be an array reference, got " . describe($fields) unless ref $fields eq 'ARRAY';
84 my ( @parsed, %seen );
85 foreach my $field (@$fields) {
86 die ref($self) . ": a field must be a hash reference with a name and an input, got " . describe($field) unless ref $field eq 'HASH';
87 my %rest = %$field;
88 my $name = string( $self, 'the name of a field' => delete $rest{name} );
89 my $label = optional( \&string, $self, "the label of the field '$name'" => delete $rest{label} );
90 my $input = delete $rest{input};
91 die ref($self) . ": the field '$name' needs an input widget that has a value, got " . describe($input)
92 unless blessed $input && $input->can('value') && $input->isa('Term::Fabulous::Widget');
93 die ref($self) . ": the field '$name' has unknown keys: " . join( ', ', sort keys %rest ) if %rest;
94 die ref($self) . ": two fields are named '$name'" if $seen{$name}++;
95 push @parsed, { name => $name, label => $label, input => $input };
96 }
97 return @parsed;
98 }
99  
100 method _parsed_buttons ($buttons) {
101 die ref($self) . ": buttons must be a non-empty array reference, got " . describe($buttons) unless ref $buttons eq 'ARRAY' && @$buttons;
102 my ( @parsed, %seen );
103 foreach my $button (@$buttons) {
104 die ref($self) . ": a button must be a hash reference with an id and a label, got " . describe($button) unless ref $button eq 'HASH';
105 my %rest = %$button;
106 my $id = string( $self, 'the id of a button' => delete $rest{id} );
107 my $label = string( $self, "the label of the button '$id'" => delete $rest{label} );
108 my $primary = boolean( $self, "the primary flag of the button '$id'" => delete $rest{primary} );
109 die ref($self) . ": the button '$id' has unknown keys: " . join( ', ', sort keys %rest ) if %rest;
110 die ref($self) . ": two buttons have the id '$id'" if $seen{$id}++;
111 push @parsed, { id => $id, label => $label, primary => $primary };
112 }
113 return @parsed;
114 }
115  
116 # The field or button to focus when the prompt opens: a name that is
117 # both is ambiguous.
118 method _checked_focus ($name) {
119 return undef unless defined $name;
120 $name = string( $self, focus => $name );
121 my $is_field = grep { $_->{name} eq $name } @_fields;
122 my $is_button = grep { $_->{id} eq $name } @_buttons;
123 die ref($self) . ": focus '$name' names both a field and a button" if $is_field && $is_button;
124 die ref($self) . ": focus '$name' names no field and no button" unless $is_field || $is_button;
125 return $name;
126 }
127  
128 # ---------------------------------------------------------------------
129 # The parts
130 # ---------------------------------------------------------------------
131  
132 # One row per field, the labels in a column as wide as the longest.
133 method _field_rows () {
134 my $label_columns = max( 0, map { string_columns( $_->{label} // '' ) } @_fields );
135 my $rows = Term::Fabulous::Widget::Box->new( layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_grow() }, child_gap => 1 } );
136 foreach my $field (@_fields) {
137 my $row = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow() }, child_gap => 1 } );
138 if ($label_columns) {
139 my $label = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_fixed($label_columns) } } );
140 $label->add_child( Term::Fabulous::Widget::Text->new( text => $field->{label} // '' ) );
141 $row->add_child($label);
142 }
143 $row->add_child( $field->{input} );
144 $rows->add_child($row);
145 }
146 return $rows;
147 }
148  
149 method _button_row () {
150 weaken( my $weak_self = $self );
151 my $row = Term::Fabulous::Widget::Box->new( layout => { child_gap => 2 } );
152 foreach my $button (@_buttons) {
153 my $id = $button->{id};
154 my $widget = Term::Fabulous::Widget::Button->new( bordered => 1, classes => $button->{primary} ? ['primary'] : [], layout => { padding => { left => 1, right => 1 } } );
155 $widget->add_child( Term::Fabulous::Widget::Text->new( text => $button->{label} ) );
156 $widget->on( Activate => sub ($event) { $weak_self->answer($id); return } );
157 $button->{widget} = $widget;
158 $row->add_child($widget);
159 }
160 return $row;
161 }
162  
163 # Shows what is wrong in the line above the buttons, in the color of
164 # an invalid input; an empty text takes the line away.
165 method _show_error ($text) {
166 $_error_text->text($text);
167 $_error_text->text_color( $self->family_look( input => 'text', 'invalid' ) ) if length $text;
168 my $shown = $self->has_child($_error_text);
169 if ( length $text && !$shown ) {
170 $self->insert_children( scalar( @{ $self->children } ) - 1, $_error_text );
171 }
172 elsif ( !length $text && $shown ) {
173 $self->remove_child($_error_text);
174 }
175 return;
176 }
177  
178 # ---------------------------------------------------------------------
179 # Accessors
180 # ---------------------------------------------------------------------
181  
182 method title (@new) {
183 return $title unless @new;
184 $title = string( $self, title => $new[0] );
185 $_title_text->text($title);
186 $self->_show_part( $_title_text, length $title, 0 );
187 return $title;
188 }
189  
190 method message (@new) {
191 return $message unless @new;
192 my $markup = string( $self, message => $new[0] );
193 $_message_text->markup($markup);
194 $message = $markup;
195 $self->_show_part( $_message_text, length $message, $self->has_child($_title_text) ? 1 : 0 );
196 return $message;
197 }
198  
199 # Puts the title or the message into the prompt at its place, or takes
200 # it out.
201 method _show_part ( $part, $wanted, $index ) {
202 my $shown = $self->has_child($part);
203 $self->insert_children( $index, $part ) if $wanted && !$shown;
204 $self->remove_child($part) if !$wanted && $shown;
205 return;
206 }
207  
208 method field_names () {
209 return map { $_->{name} } @_fields;
210 }
211  
212 method button_ids () {
213 return map { $_->{id} } @_buttons;
214 }
215  
216 method input ($name) {
217 my $field = first { $_->{name} eq $name } @_fields;
218 die ref($self) . ": the prompt has no field named " . describe($name) unless defined $field;
219 return $field->{input};
220 }
221  
222 method button ($id) {
223 my $button = first { $_->{id} eq $id } @_buttons;
224 die ref($self) . ": the prompt has no button with the id " . describe($id) unless defined $button;
225 return $button->{widget};
226 }
227  
228 method values () {
229 return { map { $_->{name} => $_->{input}->value } @_fields };
230 }
231  
232 # The button Enter in a text field presses: the first primary one, or
233 # the first one.
234 method default_button () {
235 my $primary = first { $_->{primary} } @_buttons;
236 return ( $primary // $_buttons[0] )->{id};
237 }
238  
239 method error () {
240 my $text = $_error_text->text;
241 return length $text ? $text : undef;
242 }
243  
244 # ---------------------------------------------------------------------
245 # Opening and answering
246 # ---------------------------------------------------------------------
247  
248 method open :override ($ui) {
249 return $self if $self->is_open;
250 $self->_show_error('');
251 $self->SUPER::open($ui);
252 $self->_focus_named($focus) if defined $focus;
253 return $self;
254 }
255  
256 method _focus_named ($name) {
257 my $field = first { $_->{name} eq $name } @_fields;
258 $self->_focus_into( defined $field ? $field->{input} : $self->button($name) );
259 return;
260 }
261  
262 # Focuses the widget, or the first focusable widget inside it when it
263 # cannot take the focus itself (an input made of other inputs, such
264 # as a color picker).
265 method _focus_into ($widget) {
266 my $interaction = $self->ui->interaction;
267 my ($target) = $interaction->focusables( within => $widget );
268 $interaction->set_focused_widget($target) if defined $target;
269 return;
270 }
271  
272 # What a button press does. A primary button checks the fields first
273 # and keeps the prompt open while something is wrong.
274 method answer ($id) {
275 my $button = first { $_->{id} eq $id } @_buttons;
276 die ref($self) . ": the prompt has no button with the id " . describe($id) unless defined $button;
277 die ref($self) . ": answer needs an open prompt" unless $self->is_open;
278 return $self if $button->{primary} && !$self->_values_are_fine;
279  
280 my $values = $self->values;
281 $self->SUPER::close; # the dialog's close: an answer with a button is no dismissal
282 $self->fire_event( Term::Fabulous::Event::Answer->new( button => $id, values => $values ) );
283 return $self;
284 }
285  
286 # Checks every field, then the whole prompt; shows the first problem
287 # and focuses the field it is about.
288 method _values_are_fine () {
289 foreach my $field (@_fields) {
290 my $input = $field->{input};
291 my $error = $input->can('validate') ? $input->validate : undef;
292 next unless defined $error;
293 $self->_show_error( ( $field->{label} // $field->{name} ) . ": $error" );
294 $self->_focus_into( $self->_invalid_part_of($input) // $input );
295 return 0;
296 }
297 my $problem = defined $check ? $check->( $self->values ) : undef;
298 if ($problem) {
299 $self->_show_error($problem);
300 return 0;
301 }
302 $self->_show_error('');
303 return 1;
304 }
305  
306 # The first invalid input inside a field that can take the focus (a
307 # color picker's text field rather than its swatch list), or undef.
308 method _invalid_part_of ($input) {
309 my $interaction = $self->ui->interaction;
310 return first { $interaction->can_take_focus($_) } $input->invalid_inputs;
311 }
312  
313 # Escape, or close from the program: the prompt answers cancel, after
314 # the dialog's Close.
315 method close :override () {
316 return $self unless $self->is_open;
317 $self->SUPER::close;
318 $self->fire_event( Term::Fabulous::Event::Answer->new( button => CANCEL, values => $self->values, dismissed => 1 ) );
319 return $self;
320 }
321  
322 # ---------------------------------------------------------------------
323 # Prompts in one call
324 # ---------------------------------------------------------------------
325  
326 method alert :common ( $ui, %params ) {
327 my $ok = delete $params{ok} // 'OK';
328 return $class->new( %params, buttons => [ { id => 'ok', label => $ok, primary => 1 } ] )->open($ui);
329 }
330  
331 method confirm :common ( $ui, %params ) {
332 my $ok = delete $params{ok} // 'OK';
333 my $cancel = delete $params{cancel} // 'Cancel';
334 return $class->new( %params, buttons => [ { id => 'ok', label => $ok, primary => 1 }, { id => CANCEL, label => $cancel } ] )->open($ui);
335 }
336  
337 method ask :common ( $ui, %params ) {
338 my %field = map { exists $params{$_} ? ( $_ => delete $params{$_} ) : () } qw(value placeholder required validator);
339 my $label = delete $params{label};
340 my $ok = delete $params{ok} // 'OK';
341 my $cancel = delete $params{cancel} // 'Cancel';
342 my $input = Term::Fabulous::Widget::TextField->new( %field, layout => { sizing => { width => sizing_grow() } } );
343 $input->editor->select_all; # typing replaces what the field starts with
344 return $class->new(
345 %params,
346 fields => [ { name => 'value', label => $label, input => $input } ],
347 buttons => [ { id => 'ok', label => $ok, primary => 1 }, { id => CANCEL, label => $cancel } ],
348 )->open($ui);
349 }
350 }
351  
352 1;
353  
354 __END__