71ee6faddd43538fed327aecec04cdf9d73e8960
[catagits/Reaction.git] / lib / Reaction / UI / ViewPort / Field.pm
1 package Reaction::UI::ViewPort::Field;
2
3 use Reaction::Class;
4 use aliased 'Reaction::InterfaceModel::Object';
5 use aliased 'Reaction::Meta::InterfaceModel::Object::ParameterAttribute';
6
7 class Field is 'Reaction::UI::ViewPort', which {
8
9   has value        => (is => 'rw', lazy_build => 1);
10   has name         => (is => 'rw', isa => 'Str', lazy_build => 1);
11   has label        => (is => 'rw', isa => 'Str', lazy_build => 1);
12   has value_string => (is => 'rw', isa => 'Str', lazy_build => 1);
13
14   has model     => (is => 'ro', isa => Object,             required => 1);
15   has attribute => (is => 'ro', isa => ParameterAttribute, required => 1);
16
17   implements adopt_value => as {};
18
19   implements _build_name => as { shift->attribute->name };
20   implements _build_value_string => as { shift->value };
21
22   implements _build_label => as {
23     join(' ', map { ucfirst } split('_', shift->name));
24   };
25
26   #unlazify and move it to build. to deal with array use typeconstraints and coercions
27   implements _build_value => as {
28     my ($self) = @_;
29     my $reader = $self->attribute->get_read_method;
30     my $predicate = $self->attribute->predicate;
31     #this is bound to blow the fuck if !model->$predicate what to do?
32     return $self->model->$reader if (!$predicate || $self->model->$predicate);
33     return;
34   };
35
36   implements adopt_value => as {
37     my ($self) = @_;
38     $self->needs_sync(1) if $self->has_attribute;
39   };
40
41   implements value_string => as { shift->value };
42
43   implements sync_to_action => as {
44     my ($self) = @_;
45     return unless $self->needs_sync && $self->has_attribute && $self->has_value;
46     my $attr = $self->attribute;
47     if (my $tc = $attr->type_constraint) {
48       my $value = $self->value;
49       if ($tc->has_coercion) {
50         $value = $tc->coercion->coerce($value);
51       }
52       my $error = $tc->validate($self->value);
53       if (defined $error) {
54         $self->message($error);
55         return;
56       }
57     }
58     my $writer = $attr->get_write_method;
59     confess "No writer for attribute" unless defined($writer);
60     $self->action->$writer($self->value);
61     $self->needs_sync(0);
62   };
63
64   implements sync_from_action => as {
65     my ($self) = @_;
66     return unless !$self->needs_sync && $self->has_attribute;
67     $self->message($self->action->error_for($self->attribute)||'');
68   };
69
70   override accept_events => sub { ('value', super()) };
71
72 };
73
74 1;