pantographe / view_component-form

Rails FormBuilder for ViewComponent
MIT License
208 stars 16 forks source link

Create preview for components #52

Open nicolas-brousse opened 3 years ago

nicolas-brousse commented 3 years ago
Spone commented 3 years ago

When it's ready, do you think we should host the lookbook publicly somewhere? It would help documenting the available components.

dlupu commented 2 years ago

Hi guys,

Thanks for the great work you are doing!

I was wondering if you managed to create previews using Lookbook for the form components. All form components require a form to be passed as argument, but I cannot figure out how to do this in Lookbook.

Thank you in advance for your feedback. D

nicolas-brousse commented 2 years ago

Hi @dlupu,

On one of my project I did the following to preview a form component with lookbook.

# spec/components/previews/form/preview.rb

require "view_component/form/test_helpers"

# @hidden
class Form::Preview < ViewComponent::Preview
  include ViewComponent::Form::TestHelpers

  protected

  def form_builder(object_name = nil, object = nil, options = {})
    My::FormBuilder.new(object_name, object, template, options)
  end

  def template
    lookup_context = ActionView::LookupContext.new(ActionController::Base.view_paths)

    ActionView::Base.new(lookup_context, {}, ActionController::Base.new)
  end
end

And for example to test TextAreaComponent I did:

class Form::TextAreaComponentPreview < Form::Preview
  layout "small_container"

  # Form components are used the same way than basic rails forms.
  #
  # ```erb
  # <%= form_with model: @user do |f| %>
  #   <%= f.text_area :name %>
  # <% end %>
  # ```
  #
  # See [https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-text_area](https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-text_area).
  def basic(method: :comment)
    render Form::TextAreaComponent.new(form_builder, nil, method)
  end
end
boardfish commented 2 years ago

It could also be worth considering rendering via form helpers if that's an option, e.g.:

<%= fields do |f| %>
  <%= f.text_area :name %>
<% end %>

Setting the default form builder for previews might get interesting, though.