Skip to content

Commit

Permalink
Use select value to set the selected attribute on options
Browse files Browse the repository at this point in the history
This is how React does it:
https://reactjs.org/docs/forms.html#the-select-tag

Related to #14 because it's doing some validation too.
  • Loading branch information
aalin committed Sep 29, 2022
1 parent a67aa8d commit 17aeb95
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 9 deletions.
35 changes: 30 additions & 5 deletions lib/mayu/component/special_components.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,6 @@ def render
class A < Component::Base
EXTERNAL_LINK_RE = T.let(%r{\A[a-z0-9]+://}, Regexp)

sig { params(_: T.untyped, href: String).void }
def handle_click(_, href)
helpers.navigate(href.to_s)
end

sig { override.returns(T.nilable(VDOM::Descriptor)) }
def render
overridden_props =
Expand All @@ -52,6 +47,36 @@ def render
)
end
end

class Select < Component::Base
class InvalidNestingError < StandardError
end

sig { override.returns(T.nilable(VDOM::Descriptor)) }
def render
value = props[:value]

options =
Array(children).flatten.compact.map do |descriptor|
unless descriptor.type == :option
raise InvalidNestingError,
"Only option are valid children for select, you passed #{descriptor.type}"
end

h.create_element(
descriptor.type,
descriptor.props[:children],
{
**descriptor.props,
key: descriptor.key,
selected: !value.nil? && value == descriptor.props[:value]
}
)
end

h.create_element(:__mayu_select, options, props.except(:value))
end
end
end
end
end
12 changes: 8 additions & 4 deletions lib/mayu/vdom/descriptor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -125,16 +125,20 @@ def convert_special_type(type)
case type
when :head
Component::SpecialComponents::Head
when :body
Component::SpecialComponents::Body
when :a
Component::SpecialComponents::A
when :__mayu_head
:head
when :body
Component::SpecialComponents::Body
when :__mayu_body
:body
when :a
Component::SpecialComponents::A
when :__mayu_a
:a
when :select
Component::SpecialComponents::Select
when :__mayu_select
:select
else
type
end
Expand Down

0 comments on commit 17aeb95

Please sign in to comment.