File Coverage

blib/lib/Text/UnicodeBox/Table.pm
Criterion Covered Total %
statement 1 3 33.3
branch n/a
condition n/a
subroutine 1 1 100.0
pod n/a
total 2 4 50.0


line stmt bran cond sub pod time code
1             package Text::UnicodeBox::Table;
2              
3             =encoding utf-8
4              
5             =head1 NAME
6              
7             Text::UnicodeBox::Table - High level interface providing easy table drawing
8              
9             =head1 SYNOPSIS
10              
11             my $table = Text::UnicodeBox::Table->new();
12              
13             $table->add_header('id', 'name');
14             $table->add_row('1', 'George Washington');
15             $table->add_row('2', 'Thomas Jefferson');
16             print $table->render();
17              
18             # Prints:
19             # ┌────┬───────────────────┐
20             # │ id │ name │
21             # ├────┼───────────────────┤
22             # │ 1 │ George Washington │
23             # │ 2 │ Thomas Jefferson │
24             # └────┴───────────────────┘
25              
26             =head1 DESCRIPTION
27              
28             This module provides an easy high level interface over L<Text::UnicodeBox>.
29              
30             =cut
31              
32 2     2   74645 use Moose;
  0            
  0            
33             use Text::UnicodeBox::Text qw(:all);
34             use Text::UnicodeBox::Control qw(:all);
35             use List::Util qw(sum max);
36             extends 'Text::UnicodeBox';
37              
38             has 'lines' => ( is => 'rw', default => sub { [] } );
39             has 'max_column_widths' => ( is => 'rw', default => sub { [] } );
40             has 'style' => ( is => 'rw', default => 'light' );
41             has 'is_rendered' => ( is => 'rw' );
42             has 'split_lines' => ( is => 'rw' );
43             has 'max_width' => ( is => 'rw' );
44             has 'column_widths' => ( is => 'rw' );
45             has 'break_words' => ( is => 'rw' );
46              
47             =head1 METHODS
48              
49             =head2 new
50              
51             Pass any arguments you would to L<Text::UnicodeBox/new> but with the following additions.
52              
53             =over 4
54              
55             =item split_lines
56              
57             If set, line breaks in cell data will result in new rows rather then breaks in the rendering.
58              
59             =item max_width
60              
61             If set, the width of the table will ever exceed the given width. Data will be attempted to fit with wrapping at word boundaries.
62              
63             =item break_words
64              
65             If set, wrapping may break words
66              
67             =item column_widths
68              
69             column_widths => [ undef, 40, 60 ],
70             # First column may be any width but the second and third have specified widths
71              
72             Specify the exact width of each column, sans padding and box formatting.
73              
74             =item style
75              
76             my $table = Text::UnicodeBox::Table->new( style => 'horizontal_double ');
77              
78             You may specify a certain style for the table to be drawn. This may be overridden on a per row basis.
79              
80             =over 4
81              
82             =item light
83              
84             All lines are light.
85              
86             =item heavy
87              
88             All lines are heavy.
89              
90             =item double
91              
92             All lines are double.
93              
94             =item horizontal_double
95              
96             All horizontal lines are double, where vertical lines are single.
97              
98             =item heavy_header
99              
100             The lines drawing the header are heavy, all others are light.
101              
102             =back
103              
104             =back
105              
106             =head2 add_header ( [\%opt,] @parts )
107              
108             $table->add_header({ bottom => 'heavy' }, 'Name', 'Age', 'Address');
109              
110             Same as C<add_row> but sets the option ('header' => 1)
111              
112             Draws one line of output with a border on the top and bottom.
113              
114             =head2 add_row ( [\%opt,] @parts )
115              
116             If the first argument to this method is a hashref, it is interpreted as an options hash. This hash takes the following parameters:
117              
118             =over 4
119              
120             =item style (default: 'light')
121              
122             What style will be used for all box characters involved in this line of output. Options are: 'light', 'double', 'heavy'
123              
124             =item alignment
125              
126             alignment => [ 'right', 'left', 'right' ]
127            
128             Pass a list of 'right' and 'left', corresponding with the number of columns of output. This will control the alignment of this row, and if passed to C<add_header>, all following rows as well. By default, values looking like a number are aligned to the right, with all other values aligned to the left.
129              
130             =item header_alignment
131              
132             The header will always be aligned to the left unless you pass this array ref to specify custom alignment.
133              
134             =item top
135              
136             =item bottom
137              
138             If set, draw a line above or below the current line.
139              
140             =item header
141              
142             Same as passing C<top> and C<bottom> to the given style (or the default style C<style>)
143              
144             =back
145              
146             =cut
147              
148             sub add_header {
149             my $self = shift;
150             my %opt = ref $_[0] ? %{ shift @_ } : ();
151             $opt{header} = 1;
152              
153             # Support special table-wide styles
154             if ($self->style) {
155             if ($self->style eq 'horizontal_double') {
156             $opt{bottom} = $opt{top} = 'double';
157             }
158             elsif ($self->style eq 'heavy_header') {
159             $opt{bottom} = $opt{top} = $opt{style} = 'heavy';
160             }
161             else {
162             $opt{style} ||= $self->style;
163             }
164             }
165              
166             $self->_push_line(\%opt, @_);
167             }
168              
169             sub add_row {
170             my $self = shift;
171             my %opt = ref $_[0] ? %{ shift @_ } : ();
172              
173             # Support special table-wide styles
174             if ($self->style && $self->style =~ m{^(heavy|double|light)$}) {
175             $opt{style} = $self->style;
176             }
177              
178             $self->_push_line(\%opt, @_);
179             }
180              
181             around 'render' => sub {
182             my $orig = shift;
183             my $self = shift;
184              
185             if ($self->is_rendered) {
186             return $self->buffer;
187             }
188              
189             my @alignment;
190              
191             my $lines = $self->lines;
192             my $max_column_widths = $self->max_column_widths;
193              
194             if ($self->_is_width_constrained || $self->split_lines) {
195             if ($self->max_width && ! $self->column_widths) {
196             $self->_determine_column_widths();
197             }
198             ($lines, $max_column_widths) = $self->_fit_lines_to_widths($lines);
199             }
200              
201             my $last_line_index = $#{ $lines };
202             foreach my $i (0..$last_line_index) {
203             my ($opts, $columns) = @{ $lines->[$i] };
204             my %start = (
205             style => $opts->{style} || 'light',
206             );
207             if ($opts->{header} || $i == 0 || $opts->{top}) {
208             $start{top} = $opts->{top} || $start{style};
209             }
210             if ($opts->{header} || $i == $last_line_index || $opts->{bottom}) {
211             $start{bottom} = $opts->{bottom} || $start{style};
212             }
213              
214             # Support special table-wide styles
215             if ($self->style) {
216             if ($self->style eq 'horizontal_double' && $i == $last_line_index) {
217             $start{bottom} = 'double';
218             }
219             }
220              
221             if ($opts->{alignment}) {
222             @alignment = @{ $opts->{alignment} };
223             }
224              
225             my @parts = ( BOX_START(%start) );
226             foreach my $j (0..$#{$columns}) {
227             my $align = $opts->{header_alignment} ? $opts->{header_alignment}[$j]
228             : $opts->{header} ? 'left'
229             : $alignment[$j] || undef;
230              
231             push @parts, $columns->[$j]->align_and_pad(
232             width => $max_column_widths->[$j],
233             align => $align,
234             );
235              
236             if ($j != $#{$columns}) {
237             push @parts, BOX_RULE;
238             }
239             elsif ($j == $#{$columns}) {
240             push @parts, BOX_END;
241             }
242             }
243             $self->add_line(@parts);
244             }
245              
246             $self->is_rendered(1);
247             $self->$orig();
248             };
249              
250             sub _push_line {
251             my ($self, $opt, @columns) = @_;
252              
253             # Allow undef to be passed in columns; map it to ''
254             $columns[$_] = '' foreach grep { ! defined $columns[$_] } 0..$#columns;
255              
256             my $do_split_lines = defined $opt->{split_lines} ? $opt->{split_lines} : $self->split_lines;
257              
258             # Convert each column into a ::Text object so that I can figure out the length as
259             # well as record max column widths
260             my @strings;
261             foreach my $i (0..$#columns) {
262             my $string = BOX_STRING($columns[$i]);
263             my $string_length = $string->length;
264             push @strings, $string;
265              
266             if ($do_split_lines && $columns[$i] =~ m/\n/) {
267             # Asking for the longest_line_length will automatically split the string on newlines
268             $string_length = $string->longest_line_length;
269             }
270              
271             # Update record of max column widths
272             $self->max_column_widths->[$i] = max($string_length, $self->max_column_widths->[$i] || 0);
273             }
274              
275             push @{ $self->lines }, [ $opt, \@strings ];
276             }
277              
278             sub _is_width_constrained {
279             my $self = shift;
280             return $self->max_width || $self->column_widths;
281             }
282              
283             ## _determine_column_widths
284             #
285             # Pass no args, return nothing. Figure out what the column widths should be where the caller has specified a custom max_width value that they'd like the whole table to be constrained to.
286              
287             sub _determine_column_widths {
288             my $self = shift;
289             return if $self->column_widths;
290             return if ! $self->max_width;
291              
292             # Max width represents the max width of the rendered table, with padding and box characters
293             # Let's figure out how many characters will be used for rendering and padding
294             my $column_count = int @{ $self->max_column_widths };
295             my $padding_width = 1;
296             my $rendering_characters_width =
297             ($column_count * ($padding_width * 2)) # space on left and right of each cell text
298             + $column_count + 1; # bars on right of each column + one on left in beginning
299              
300             # Prepare a checker for determining success
301             my $widths_over = sub {
302             my @column_widths = @_;
303             return (sum (@column_widths) + $rendering_characters_width) - $self->max_width;
304             };
305             my $widths_fit = sub {
306             my @column_widths = @_;
307             if ($widths_over->(@column_widths) <= 0) {
308             $self->column_widths( \@column_widths );
309             return 1;
310             }
311             return 0;
312             };
313              
314             # Escape early if the max column widths already fit the constraint
315             return if $widths_fit->(@{ $self->max_column_widths });
316              
317             # FIXME
318             if ($self->break_words) {
319             warn "Passing max_width and break_words without column_widths is not yet implemented\n";
320             }
321              
322             # Figure out longest word lengths
323             my @longest_word_lengths;
324             foreach my $line (@{ $self->lines }) {
325             foreach my $column_index (0..$#{ $line->[1] }) {
326             my $length = $line->[1][$column_index]->longest_word_length;
327             $longest_word_lengths[$column_index] = max($length, $longest_word_lengths[$column_index] || 0);
328             }
329             }
330              
331             # Sanity check about if it's even possible to proceed
332             if ($widths_over->(@longest_word_lengths) > 0) {
333             die "It's not possible to fit the table in width ".$self->max_width." without break_words => 1\n";
334             }
335              
336             # Reduce the amout of wrapping as much as possible. Try and fit in the max_width with breaking the
337             # fewest possible columns.
338              
339             my @column_widths = @{ $self->max_column_widths };
340             my @column_index_by_width = sort { $column_widths[$b] <=> $column_widths[$a] } 0..$#column_widths;
341              
342             while (! $widths_fit->(@column_widths)) {
343             # Select the next widest column and try shortening it
344             my $column_index = shift @column_index_by_width;
345             if (! defined $column_index) {
346             die "Shortened all the columns and found no way to fit";
347             }
348              
349             my $overage = $widths_over->(@column_widths);
350             my $new_width = $column_widths[$column_index] - $overage;
351             if ($new_width < $longest_word_lengths[$column_index]) {
352             $new_width = $longest_word_lengths[$column_index];
353             }
354             $column_widths[$column_index] = $new_width;
355             }
356              
357             return;
358             }
359              
360             ## _fit_lines_to_widths (\@lines, \@column_widths)
361             #
362             # Pass an array ref of lines (most likely from $self->lines). Return an array ref of lines wrapped to the $self->column_widths values, and an array ref of the new max column widths.
363              
364             sub _fit_lines_to_widths {
365             my ($self, $lines, @column_widths) = @_;
366              
367             @column_widths = @{ $self->column_widths } if ! @column_widths && $self->column_widths;
368             @column_widths = @{ $self->max_column_widths } if ! @column_widths;
369             if (! @column_widths) {
370             die "Can't call _fit_lines_to_widths() without column_widths set or passed";
371             }
372             my @max_column_widths;
373              
374             my @new_lines;
375             foreach my $line (@$lines) {
376             my ($opts, $strings) = @$line;
377             my @new_line;
378             foreach my $column_index (0..$#column_widths) {
379             my $string = $strings->[$column_index];
380             my $width = $column_widths[$column_index];
381              
382             # As long as this string doesn't span multiple lines, and
383             # if no width constraint or if this string already fits, store and move on
384             if ($string->line_count == 1 && (! $width || $string->length <= $width)) {
385             $new_line[0][$column_index] = $string;
386             next;
387             }
388              
389             my ($store_buffer, $add_string_to_buffer);
390             {
391             my $row_index = 0;
392             my $length = 0;
393             my $buffer = '';
394             $store_buffer = sub {
395             return unless $length;
396             $new_line[$row_index++][$column_index] = BOX_STRING($buffer);
397             $length = 0;
398             $buffer = '';
399             };
400             $add_string_to_buffer = sub {
401             my ($word_value, $word_length) = @_;
402             if ($width && $length + $word_length > $width) {
403             $store_buffer->();
404             }
405             $buffer .= $word_value;
406             $length += $word_length;
407             };
408             }
409              
410             foreach my $line ($string->lines) {
411              
412             # If no width constraint or if this string already fits, store and move on
413             if (! $width || $line->length <= $width) {
414             $add_string_to_buffer->($line->value, $line->length);
415             $store_buffer->();
416             next;
417             }
418              
419             foreach my $segment ($line->split( break_words => $self->break_words, max_width => $width )) {
420             $add_string_to_buffer->($segment->value, $segment->length);
421             $store_buffer->();
422             }
423             next;
424             }
425             }
426             foreach my $row_index (0..$#new_line) {
427             # Every cell needs to have a string object
428             foreach my $column_index (0..$#column_widths) {
429             $new_line[$row_index][$column_index] ||= BOX_STRING('');
430              
431             # Update max_column_widths
432             my $width = $new_line[$row_index][$column_index]->length;
433             $max_column_widths[$column_index] = $width
434             if ! $max_column_widths[$column_index] || $max_column_widths[$column_index] < $width;
435             }
436             push @new_lines, [ $opts, $new_line[$row_index] ];
437             }
438             }
439              
440             return (\@new_lines, \@max_column_widths);
441             }
442              
443             =head2 output_width
444              
445             Returns the width of the table if it were rendered right now without additional rows added.
446              
447             =cut
448              
449             sub output_width {
450             my $self = shift;
451              
452             my $width = 1; # first pipe char
453            
454             foreach my $column_width (@{ $self->max_column_widths }) {
455             $width += $column_width + 3; # 2: padding, 1: trailing pipe char
456             }
457              
458             if ($self->max_width && $width > $self->max_width) {
459             return $self->max_width; # FIXME: is this realistic? What about for very small values of max_width and large count of columns?
460             }
461              
462             return $width;
463             }
464              
465             =head1 COPYRIGHT
466              
467             Copyright (c) 2012 Eric Waters and Shutterstock Images (http://shutterstock.com). All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
468              
469             The full text of the license can be found in the LICENSE file included with this module.
470              
471             =head1 AUTHOR
472              
473             Eric Waters <ewaters@gmail.com>
474              
475             =cut
476              
477             1;