-
Notifications
You must be signed in to change notification settings - Fork 22
/
error_summary.rb
87 lines (72 loc) · 2.01 KB
/
error_summary.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
module GOVUKDesignSystemFormBuilder
module Elements
class ErrorSummary < Base
include Traits::Error
def initialize(builder, object_name, title, link_base_errors_to:)
super(builder, object_name, nil)
@title = title
@link_base_errors_to = link_base_errors_to
end
def html
return nil unless object_has_errors?
tag.div(class: summary_class, **summary_options) do
safe_join([title, summary])
end
end
private
def title
tag.h2(@title, id: summary_title_id, class: summary_class('title'))
end
def summary
tag.div(class: summary_class('body')) do
tag.ul(class: [%(#{brand}-list), summary_class('list')]) do
safe_join(list)
end
end
end
def list
@builder.object.errors.messages.map do |attribute, messages|
list_item(attribute, messages.first)
end
end
def list_item(attribute, message)
tag.li(link_to(message, same_page_link(field_id(attribute)), data: { turbolinks: false }))
end
def same_page_link(target)
'#'.concat(target)
end
def summary_class(part = nil)
if part
%(#{brand}-error-summary).concat('__', part)
else
%(#{brand}-error-summary)
end
end
def field_id(attribute)
if attribute.eql?(:base) && @link_base_errors_to.present?
build_id('field', attribute_name: @link_base_errors_to)
else
build_id('field-error', attribute_name: attribute)
end
end
def summary_title_id
'error-summary-title'
end
def object_has_errors?
@builder.object.errors.any?
end
def summary_options
{
tabindex: -1,
role: 'alert',
data: {
module: %(#{brand}-error-summary)
},
aria: {
labelledby: summary_title_id
}
}
end
end
end
end