758caf567986449bc1888cb7a697992cc02f4449
[catagits/Reaction.git] / lib / Reaction / UI / ViewPort / Field / Role / Mutable / Simple.pm
1 package Reaction::UI::ViewPort::Field::Role::Mutable::Simple;
2
3 use Reaction::Role::Parameterized;
4
5 use aliased 'Reaction::UI::ViewPort::Field::Role::Mutable';
6
7 use namespace::clean -except => [ qw(meta) ];
8
9 parameter value_type => (
10     predicate => 'has_value_type'
11 );
12
13 role {
14
15 my $p = shift;
16
17 with Mutable, $p->has_value_type ? { value_type => $p->value_type } : ();
18
19 has value_string => (
20   is => 'rw', lazy_build => 1, trigger => sub { shift->adopt_value_string },
21 );
22
23 # FIXME - Copied from Reaction::UI::ViewPort::Field::Role::Mutable
24 #         as we broke has '+attr' in Moose.
25 has is_modified => ( #sould be bool?
26   is => 'ro', writer => '_set_modified',
27   required => 1, default => 0, init_arg => undef
28 );
29
30 around value_string => sub {
31   my $orig = shift;
32   my $self = shift;
33   if (@_) {
34     # recursive call. be VERY careful we don't go infinite here
35     my $old = $self->value_string;
36     my $new = $_[0];
37     if ((defined $old xor defined $new) || (defined $old && $old ne $new)) {
38       $self->_set_modified(1);
39     } else {
40       return;
41     }
42   }
43   if (@_ && defined($_[0]) && !ref($_[0]) && $_[0] eq ''
44       && !$self->value_is_required) {
45     $self->clear_value;
46     return undef;
47   }
48   return $self->$orig(@_);
49 };
50
51 # the user needs to implement this because, honestly, you're always going
52 # to need to do something custom and the only common thing really is
53 # "you probably set $self->value at the end"
54 requires 'adopt_value_string';
55
56 around accept_events => sub { ('value_string', shift->(@_)) };
57
58 around force_events => sub { (value_string => '', shift->(@_)) };
59
60 };
61
62 1;