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

filter: Statementstmt 0.0% 0 / 309 Branchbran 0.0% 0 / 84 Conditioncond 0.0% 0 / 53 MC/DCmcdc 0.0% 0 / 30 Subroutinesub 0.0% 0 / 27 Podpod n/a totaltotal 0.0% 0 / 503 CC 1 SCAR 6.9
CC
1
Cov
0%
BEGIN
2.0
BEGIN
2.0
BEGIN
2.0
CRAP 2.0
1 package Term::Fabulous::Widget::ColorPicker;
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::Box;
11  
12 our $VERSION = '0.05';
13  
14 # A color chooser built from other widgets: a field for the color as
15 # text, a sample of it, sliders for its channels (RGB or HSL, switched by
16 # a segmented control), an optional alpha slider and an optional list of
17 # named swatches. The parts' own events stop at them; the picker fires
18 # its own Change and Submit.
19 class Term::Fabulous::Widget::ColorPicker
20 :isa(Term::Fabulous::Widget::Box)
21 :strict(params)
22 {
23 use Clay::XS qw(sizing_fixed sizing_grow CLAY_TOP_TO_BOTTOM);
24 use Feature::Compat::Try;
25 use List::Util qw(first max min);
26 use Scalar::Util qw(weaken);
27 use Term::Fabulous::Check qw(boolean color describe one_of optional positive_integer string);
28 use Term::Fabulous::Color;
29 use Term::Fabulous::Event::Change;
30 use Term::Fabulous::Event::Submit;
31 use Term::Fabulous::Unicode qw(string_columns);
32 use Term::Fabulous::Widget::SegmentedControl;
33 use Term::Fabulous::Widget::Slider;
34 use Term::Fabulous::Widget::Table;
35 use Term::Fabulous::Widget::Table::Frame qw(framed);
36 use Term::Fabulous::Widget::Text;
37 use Term::Fabulous::Widget::TextField;
38  
39 use constant SAMPLE => "\x{2588}" x 3; # full blocks in the swatch's color
40 use constant FIELD_WIDTH => 22; # the field shrinks to FIELD_MINIMUM on a narrow screen
41 use constant FIELD_MINIMUM => 10;
42 use constant LABEL_MINIMUM => 20; # the swatch labels keep up to this many columns
43 use constant LIST_FURNITURE => 2 + 6 + 1 + 1; # the frame's borders, the sample column, the gap after it, the scrollbar
44 use constant SAMPLE_WIDTH => 6;
45  
46 # The three channel sliders of each mode: their labels and maximums.
47 my %CHANNELS_OF_MODE = (
48 rgb => [ [ R => 255 ], [ G => 255 ], [ B => 255 ] ],
49 hsl => [ [ H => 359 ], [ S => 100 ], [ L => 100 ] ],
50 );
51  
52 my $pickers_built = 0; # for the ids of pickers built without one
53  
54 field $alpha :param = 1;
55 field $sliders :param = 'rgb';
56 field $list_rows :param = 12;
57  
58 field $chosen; # the spec chosen now: a swatch's value or a color, or undef
59 field $_rgba; # the color of $chosen as [r, g, b, a], or undef
60 field @_swatches; # { value, label, rgba }, in order
61  
62 field $_field;
63 field $_sample;
64 field $_switch;
65 field @_channel_sliders;
66 field @_channel_labels;
67 field $_alpha_slider;
68 field $_alpha_row;
69 field $_column;
70 field $_list;
71 field $_frame;
72  
73 ADJUST :params ( :$value = undef, :$swatches = undef ) {
74 $alpha = boolean( $self, alpha => $alpha );
75 $sliders = one_of( $self, sliders => $sliders, keys %CHANNELS_OF_MODE );
76 $list_rows = positive_integer( $self, list_rows => $list_rows );
77 @_swatches = $self->_parsed_swatches($swatches);
78  
79 my $layout = $self->layout;
80 $self->layout( { child_gap => 2, %$layout, sizing => { width => sizing_grow(), %{ $layout->{sizing} // {} } } } );
81 $self->add_child( $self->_swatch_list ) if @_swatches;
82 $self->add_child( $self->_editor );
83 $self->_use_sliders;
84 $self->_show_value($value);
85 }
86  
87 # ---------------------------------------------------------------------
88 # Parameters
89 # ---------------------------------------------------------------------
90  
91 # Swatches as { value, label, rgba }: a value (a non-empty string,
92 # unique), a label (the value when left out) and a color (none when
93 # left out).
94 method _parsed_swatches ($swatches) {
95 return () unless defined $swatches;
96 die ref($self) . ": swatches must be an array reference, got " . describe($swatches) unless ref $swatches eq 'ARRAY';
97 my ( @parsed, %seen );
98 foreach my $swatch (@$swatches) {
99 die ref($self) . ": a swatch must be an array reference [ value, label, color ], got " . describe($swatch) unless ref $swatch eq 'ARRAY' && @$swatch >= 1 && @$swatch <= 3;
100 my ( $spec, $label, $rgba ) = @$swatch;
101 die ref($self) . ": the value of a swatch must be a non-empty string, got " . describe($spec) unless defined $spec && !ref $spec && length $spec;
102 die ref($self) . ": two swatches have the value '$spec'" if $seen{$spec}++;
103 push @parsed,
104 {
105 value => $spec,
106 label => optional( \&string, $self, "the label of the swatch '$spec'" => $label ) // $spec,
107 rgba => optional( \&color, $self, "the color of the swatch '$spec'" => $rgba ),
108 };
109 }
110 return @parsed;
111 }
112  
113 method _swatch_of ($spec) {
114 return undef unless defined $spec;
115 return first { $_->{value} eq $spec } @_swatches;
116 }
117  
118 # ---------------------------------------------------------------------
119 # The parts
120 # ---------------------------------------------------------------------
121  
122 method _swatch_list () {
123 my %rgba_of = map { $_->{value} => $_->{rgba} } @_swatches;
124 $_list = Term::Fabulous::Widget::Table->new(
125 id => ( $self->id // 'color-picker-' . ++$pickers_built ) . '/list',
126 row_id => 'value',
127 selection => 'single',
128 header => 0,
129 border => 'none',
130 column_lines => 'none',
131 columns => [
132 { key => 'sample', width => 'fixed(6)', cell_style => sub ($cell) { my $rgba = $rgba_of{ $cell->{row}{value} }; return defined $rgba ? { text_color => $rgba } : {} } },
133 { key => 'label', width => 'grow' },
134 ],
135 rows => [ map { { value => $_->{value}, label => $_->{label}, sample => defined $_->{rgba} ? SAMPLE : '' } } @_swatches ],
136 layout => { sizing => { width => sizing_grow(), height => sizing_grow() } },
137 );
138 $_list->on( CursorMove => sub ( $self, $event ) { $self->_swatch_chosen( $event->row_id ) if defined $event->row_id; return }, owner => $self );
139 $_list->on( RowActivate => sub ( $self, $event ) { $self->_swatch_submitted( $event->row_id ); return }, owner => $self );
140 $_frame = framed( $_list, $list_rows );
141 my $layout = $_frame->layout;
142 $_frame->layout( { %$layout, sizing => { %{ $layout->{sizing} }, width => sizing_grow( $self->_list_minimum_width ) } } );
143 return $_frame;
144 }
145  
146 # Wide enough for the swatch labels (up to LABEL_MINIMUM columns), so
147 # that a narrow screen shrinks the field and the sliders first.
148 method _list_minimum_width () {
149 my $longest = max map { string_columns( $_->{label} ) } @_swatches;
150 return LIST_FURNITURE + min( $longest, LABEL_MINIMUM );
151 }
152  
153 # The field and the sample, the RGB/HSL switch, the channel sliders and
154 # the alpha slider.
155 method _editor () {
156 weaken( my $weak_self = $self ); # for the validator, which the field keeps
157 $_column = Term::Fabulous::Widget::Box->new( layout => { layout_direction => CLAY_TOP_TO_BOTTOM, sizing => { width => sizing_grow() } } );
158  
159 $_field = Term::Fabulous::Widget::TextField->new(
160 placeholder => $self->_placeholder,
161 max_length => 32,
162 validator => sub ($text) { $weak_self ? $weak_self->_color_problem($text) : undef },
163 layout => { sizing => { width => sizing_grow( FIELD_MINIMUM, FIELD_WIDTH ) } },
164 );
165 $_sample = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_fixed(SAMPLE_WIDTH), height => sizing_fixed(1) } } );
166 my $top = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow() }, child_gap => 1, padding => { bottom => 1 } } );
167 $top->add_child( $_field, $_sample );
168 $_field->on( Change => sub ( $self, $event ) { $self->_typed( $event->value ); return }, owner => $self );
169 $_field->on( Submit => sub ( $self, $event ) { $self->_submit; return }, owner => $self );
170  
171 $_switch = Term::Fabulous::Widget::SegmentedControl->new( options => [ [ RGB => 'rgb' ], [ HSL => 'hsl' ] ], value => $sliders );
172 $_switch->on( Change => sub ( $self, $event ) { $self->sliders( $event->value ); return }, owner => $self );
173 $_column->add_child( $top, $_switch );
174  
175 foreach ( 1 .. 3 ) {
176 my ( $row, $label, $slider ) = $self->_slider_row;
177 push @_channel_sliders, $slider;
178 push @_channel_labels, $label;
179 $_column->add_child($row);
180 }
181 ( $_alpha_row, my $alpha_label, $_alpha_slider ) = $self->_slider_row;
182 $alpha_label->text('A');
183 $_alpha_slider->set_range( min => 0, max => 255 );
184 $_column->add_child($_alpha_row) if $alpha;
185 return $_column;
186 }
187  
188 # A label and a slider in a row; moving the slider writes the value.
189 method _slider_row () {
190 my $label = Term::Fabulous::Widget::Text->new( text => ' ' );
191 my $slider = Term::Fabulous::Widget::Slider->new( min => 0, max => 255, value_format => '%3d', layout => { sizing => { width => sizing_grow() } } );
192 my $row = Term::Fabulous::Widget::Box->new( layout => { sizing => { width => sizing_grow() }, child_gap => 1 } );
193 $row->add_child( $label, $slider );
194 $slider->on( Change => sub ( $self, $event ) { $self->_slid; return }, owner => $self );
195 return ( $row, $label, $slider );
196 }
197  
198 method _placeholder () {
199 return $alpha ? '#rrggbb or #rrggbbaa' : '#rrggbb';
200 }
201  
202 # What is wrong with a typed color, or undef: the field's validator.
203 method _color_problem ($text) {
204 my $rgba = _parsed_color($text);
205 return 'Please enter a color: #rrggbb, rgb(...), hsl(...) or a color name.' unless defined $rgba;
206 return 'Please enter a color without transparency.' if !$alpha && $rgba->[3] != 255;
207 return undef;
208 }
209  
210 # The color a text stands for as [r, g, b, a], or undef when it is none.
211 sub _parsed_color ($text) {
212 my $rgba;
213 try {
214 $rgba = color( __PACKAGE__, color => $text );
215 }
216 catch ($error) {
217 $rgba = undef;
218 }
219 return $rgba;
220 }
221  
222 sub _hex_of ( $red, $green, $blue, $opacity ) {
223 return sprintf( '#%02x%02x%02x', $red, $green, $blue ) if $opacity == 255;
224 return sprintf( '#%02x%02x%02x%02x', $red, $green, $blue, $opacity );
225 }
226  
227 # ---------------------------------------------------------------------
228 # Showing the value
229 # ---------------------------------------------------------------------
230  
231 # Sets the value from the program: the field, the sliders and the list
232 # follow. Dies on a value that is neither a swatch's nor a color.
233 method _show_value ($spec) {
234 my $swatch = $self->_swatch_of($spec);
235 my $rgba = defined $spec && !defined $swatch ? $self->_checked_color($spec) : undef;
236 ( $chosen, $_rgba ) = ( $spec, defined $swatch ? $swatch->{rgba} : $rgba );
237 $_field->value( defined $swatch ? ( $spec =~ /\A#/ ? $spec : '' ) : $spec // '' );
238 $_field->editor->select_all; # typing replaces the color
239 $self->_show_in_list($swatch);
240 $self->_show_on_sliders;
241 $self->_show_sample;
242 return;
243 }
244  
245 method _checked_color ($spec) {
246 my $rgba = color( $self, value => $spec );
247 die ref($self) . ": value must be opaque without alpha, got " . describe($spec) if !$alpha && $rgba->[3] != 255;
248 return $rgba;
249 }
250  
251 # Selects the swatch in the list, scrolled so that it is near the
252 # middle; without one, the list has no selection.
253 method _show_in_list ($swatch) {
254 return unless defined $_list;
255 return $_list->set_selection unless defined $swatch;
256 my ($index) = grep { $_swatches[$_] == $swatch } 0 .. $#_swatches;
257 my $below = min( $#_swatches, $index + int( $list_rows / 2 ) );
258 $_list->cursor( $_swatches[$below]{value} );
259 $_list->cursor( $swatch->{value} );
260 $_list->set_selection( $swatch->{value} );
261 return;
262 }
263  
264 # The sliders show the color in the current mode; without a color,
265 # black.
266 method _show_on_sliders () {
267 my ( $red, $green, $blue, $opacity ) = defined $_rgba ? @$_rgba : ( 0, 0, 0, 255 );
268 my @levels = $sliders eq 'hsl' ? Term::Fabulous::Color->rgb_to_hsl( $red, $green, $blue ) : ( $red, $green, $blue );
269 $_channel_sliders[$_]->value( $levels[$_] ) foreach 0 .. 2;
270 $_alpha_slider->value($opacity);
271 return;
272 }
273  
274 method _show_sample () {
275 return $_sample->background_color($_rgba) if defined $_rgba && $_rgba->[3] > 0;
276 $_sample->reset_look('background_color');
277 return;
278 }
279  
280 # The channel sliders take the ranges and labels of the mode, then
281 # read the color again; the value stays as it is.
282 method _use_sliders () {
283 my $channels = $CHANNELS_OF_MODE{$sliders};
284 foreach my $index ( 0 .. 2 ) {
285 my ( $label, $maximum ) = @{ $channels->[$index] };
286 $_channel_sliders[$index]->set_range( min => 0, max => $maximum );
287 $_channel_labels[$index]->text($label);
288 }
289 $self->_show_on_sliders;
290 return;
291 }
292  
293 # ---------------------------------------------------------------------
294 # What the user does
295 # ---------------------------------------------------------------------
296  
297 method _typed ($text) {
298 return unless length $text && $_field->is_valid;
299 ( $chosen, $_rgba ) = ( $text, _parsed_color($text) );
300 $_list->set_selection if defined $_list;
301 $self->_show_on_sliders;
302 $self->_show_sample;
303 $self->_fire_change;
304 return;
305 }
306  
307 # A slider moved: the value is written from the sliders, which stay
308 # as they are (HSL in whole numbers cannot reach every RGB color).
309 method _slid () {
310 my @levels = map { $_->value } @_channel_sliders;
311 my @rgb = $sliders eq 'hsl' ? Term::Fabulous::Color->hsl_to_rgb(@levels) : @levels;
312 my $opacity = $alpha ? $_alpha_slider->value : 255;
313 $chosen = _hex_of( @rgb, $opacity );
314 $_rgba = [ @rgb, $opacity ];
315 $_field->value($chosen);
316 $_list->set_selection if defined $_list;
317 $self->_show_sample;
318 $self->_fire_change;
319 return;
320 }
321  
322 method _swatch_chosen ($spec) {
323 my $swatch = $self->_swatch_of($spec);
324 ( $chosen, $_rgba ) = ( $spec, $swatch->{rgba} );
325 $_field->value( $spec =~ /\A#/ ? $spec : '' );
326 $_list->set_selection($spec);
327 $self->_show_on_sliders;
328 $self->_show_sample;
329 $self->_fire_change;
330 return;
331 }
332  
333 # Enter on a swatch row: a row under the cursor but not chosen (after
334 # typing or sliding) is chosen first.
335 method _swatch_submitted ($spec) {
336 $self->_swatch_chosen($spec) if defined $spec && ( $chosen // '' ) ne $spec;
337 $self->_submit;
338 return;
339 }
340  
341 method _fire_change () {
342 $self->fire_event( Term::Fabulous::Event::Change->new( value => $chosen ) );
343 return;
344 }
345  
346 method _submit () {
347 $self->fire_event( Term::Fabulous::Event::Submit->new( value => $chosen ) );
348 return;
349 }
350  
351 # ---------------------------------------------------------------------
352 # Accessors
353 # ---------------------------------------------------------------------
354  
355 method value (@new) {
356 return $chosen unless @new;
357 $self->_show_value( optional( \&string, $self, value => $new[0] ) );
358 return $chosen;
359 }
360  
361 method rgba () {
362 return defined $_rgba ? [@$_rgba] : undef;
363 }
364  
365 method sliders (@new) {
366 return $sliders unless @new;
367 $sliders = one_of( $self, sliders => $new[0], keys %CHANNELS_OF_MODE );
368 $_switch->value($sliders);
369 $self->_use_sliders;
370 return $sliders;
371 }
372  
373 method alpha (@new) {
374 return $alpha unless @new;
375 my $wanted = boolean( $self, alpha => $new[0] );
376 die ref($self) . ": cannot turn alpha off while the value " . describe($chosen) . " is translucent"
377 if !$wanted && defined $_rgba && $_rgba->[3] != 255 && !defined $self->_swatch_of($chosen);
378 $alpha = $wanted;
379 $_column->add_child($_alpha_row) if $alpha && !$_column->has_child($_alpha_row);
380 $_column->remove_child($_alpha_row) unless $alpha;
381 $_field->placeholder( $self->_placeholder );
382 $_field->validate;
383 return $alpha;
384 }
385  
386 method list_rows (@new) {
387 return $list_rows unless @new;
388 $list_rows = positive_integer( $self, list_rows => $new[0] );
389 if ( defined $_frame ) {
390 my $layout = $_frame->layout;
391 $_frame->layout( { %$layout, sizing => { %{ $layout->{sizing} }, height => sizing_fixed( $list_rows + 2 ) } } );
392 }
393 return $list_rows;
394 }
395  
396 # The field's validation: what Prompt and forms read.
397 method validate () { return $_field->validate }
398 method error () { return $_field->error }
399 method is_valid () { return $_field->is_valid }
400  
401 method layout_properties :common () {
402 return ( $class->SUPER::layout_properties, ( map { $_ => 'scalar' } qw(value sliders list_rows) ), alpha => 'boolean' );
403 }
404 }
405  
406 1;
407  
408 __END__