Visitar URL original
Reusable slots · Issue #1038 · github/view_component · GitHub
The Wayback Machine - https://web.archive.org/web/20220709112543/https://github.com/github/view_component/issues/1038
Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Reusable slots #1038

Open
romaricpascal opened this issue Aug 13, 2021 · 9 comments
Open

Reusable slots #1038

romaricpascal opened this issue Aug 13, 2021 · 9 comments

Comments

@romaricpascal
Copy link

@romaricpascal romaricpascal commented Aug 13, 2021

Feature request

Allow a component to render the same slot multiple times with different outputs. At the moment, each subsequent output of a given slot produces the same output as the first.

This gets in the way when trying to create a component looping over some records internally, rendering the same slot for each. But offering a unique entry point for configuring the rendering of that slot.

<%= render LoopingComponent.new (records) do |component| %>
 <% component.slot do |slot| %>
    <%# Pick how to render the record %>
 <% end %>
<% end %>
<% records.each do |record| %>
 <% slot.record = record %>
 <%= slot %>
<% end %>

Something like a data table would be a prime use case for it.

Looking at the code, it seems the main blocker for it is that Line 29 in SlotV2

This can be worked around with:

<% slot.remove_instance_variable(:@content) if slot.instance_variable_defined?(:@content) %>

However, how safe an API is it to reach for that @content instance variable?

It'd be great to have an API to handle that, either through:

  1. a clear_content method on SlotV2 that exectutes the workaround
  2. an option for SlotV2's constructor to not cache the content and a way for renders_one/renders_many to pass that through? Or maybe to pass the class of the slot to use, allowing users to extend if necessary?
class ReusableSlot < ViewComponent::SlotV2
	def initialize(*args, **kwargs)
		super(*args, cache: false, **kwargs)
	end
end

renders_one :slot, ComponentForTheSlot, slot: ReusableSlot

There's also the option of disabling the caching altogether, but I guess if it's there it's because it must bring some performance gains in some situations.

@romaricpascal
Copy link
Author

@romaricpascal romaricpascal commented Aug 13, 2021

It seems that there'd also be some changes to make in the Base component for reuse to work when blocks are passed to the slots. The @__vc_content caches the content so would only be evaluated for the first render. This would prevent to do things like formatting values:

<%= render LoopingComponent.new (records) do |component| %>
 <% component.slot do |slot| %>
	<%= slot.record.date.strftime('%d %b %Y') %>
 <% end %>
<% end %>

I've noticed that render_in resets @__vc_content_evaluated but doesn't do anything towards @__vc_content. Won't that lead to content_evaluated? being false, but the content not being evaluated on the next content call as it's stored in @__vc_content?

@boardfish
Copy link
Collaborator

@boardfish boardfish commented Aug 13, 2021

I had a reply drafted for this and lost it, so I might end up skipping necessary details here, apologies.

So it looks to me like the ask is to be able to change the content passed to a renders_one slot each time it's rendered, if I'm understanding your requirements correctly. Right now that strikes me as something that I think feels "off menu" and should perhaps stay outside the API.

What I would recommend doing instead is either:

  • using a renders_many slot and creating a component as a wrapper, then rendering it like this:
<% data.each do |record| %>
  <% c.slot do %>
    <% Do things with the content here %>
  <% end %>
<% end %>

or:

  • passing the data in as an instance variable.

Using a lambda slot with has_many or using the latter option would also let you choose which component to render in the slot based on some feature of the record, e.g. its type if you're looping through a polymorphic association.

Hope this helps!

@romaricpascal
Copy link
Author

@romaricpascal romaricpascal commented Aug 15, 2021 •

Thanks for the reply. I think I need to add some clarifications as the two options don't really help solve what made me look for lifting the caching of the content:

  • the slots I'm trying to reuse are actually renders_many
  • I'd like to keep the looping over the record encapsulated in the "root" component
  • the aim is not to pick a "child" component based on the record, but really to re-run the block inside the content, taking advantage of the fact that the "child" component will be passed to it and can provide new values for various helper methods.

The concrete use case I'm working on is building a data table component. In terms of slots (and with the described caching mechanism lifted), it uses two renders_many for headings and cells. A cell + a heading define a column of the data table, allowing users to define how the data is rendered in two calls (actually one through a column method that creates both).

class DataTableComponent < ViewComponent::Base
  renders_many :headings, HeadingComponent # Not repeated
  renders_many :cells, CellComponent # <- That's the repeated one
  
  def initialize(records: [])
  end
  
  def column(*args, **kwargs, &block)
    # Arguments passed as is for brevity, but some triaging would happen here
    # to pick what goes to which part of the column
    heading(*args, **kwargs)
    cell(*args, **kwargs, &block)
  end
end

The table encapsulates the looping as its doesn't naively iterate over the records. As examples, it also needs to:

  • be able to render extra columns like a checkbox for selecting specific records for bulk operations (param in the constructor creates a new column at initialization)
  • add or reference an accessibly hidden column that can be referred to for labelling form fields or disembiguating recurring link labels for example.

When used the aim is to provide an API similar to:

<%= render DataTableComponent.new(selectable: true) do |table| %>
	<% table.column :name, accessible_name: true %>
	<% table.column :email, cell_attributes: {class: 'text-muted'} %>
	<% table.column :edit do |cell| %>
	  <%= link_to "Edit", record_edit_path(table.current_record), 'aria-labelledby': "#{cell.heading_id} #{table.accessible_name_cell_id}" %>
	<% end %>
<% end %>

By reusing the CellComponent and re-running the block, the content of the cell gets the right references for each record of the table, based on the internal state of the DataTable component.

I'm aware that this could be achieved with something like:

class DataTableComponent < ViewComponent::Base
  renders_many :headings, HeadingComponent # Not repeated
  
  def initialize(records: [])
	@cells = []
  end

  def cell(*args, **kwargs, &block)
  	@cells.push([args, kwargs, block])
  end
  
  def column(*args, **kwargs, &block)
    heading(*args, **kwargs)
    cell(*args, **kwargs, &block)
  end
end
<% @records.each do |record| %>
  <% @cells.each do |cell| %>
  	<%= render CellComponent.new(*cell[0],**cell[1]), &cell[2] %>
  <% end %>
<% end %>

However, this makes things look like the table has a cell slot, while actually it doesn't. And it requires it to re-create something for collecting the cells that the slots already to. Which is why I was hoping to introduce a way to re-use the existing slots rather than create new component instances each time.

Hope this makes what I'm trying to achieve clearer 😄

@boardfish
Copy link
Collaborator

@boardfish boardfish commented Aug 19, 2021

Hey Romaric, sorry for the radio silence on my part - I'm hoping to sit down and have a proper look at this at some point soon. Hopefully one of the others can tag in to help in the meantime.

@romaricpascal
Copy link
Author

@romaricpascal romaricpascal commented Aug 24, 2021

No worries, it's not blocking for me. It's just something I think could be handy to have out of the box in the library as it really helps encapsulate little front-end helper logic on components that iterate over data.

@romaricpascal
Copy link
Author

@romaricpascal romaricpascal commented Sep 6, 2021

Would you be open to a PR adding a clear_content method to the SlotV2 class, as well as the ViewComponent::Base, both for doing the necessary cleanup if needed?

@joelhawksley
Copy link
Contributor

@joelhawksley joelhawksley commented Sep 8, 2021

@romaricpascal at this point I would not accept a patch for adding clear_content. I don't think it's a good idea to add that API.

@boardfish do you have time to look into this more, or should I take it on?

@boardfish
Copy link
Collaborator

@boardfish boardfish commented Sep 9, 2021

I wanted to take the time to get my head around it but I haven't been able to make that time for a while. It might be best for you to pick it up @joelhawksley. Thanks!

@romaricpascal
Copy link
Author

@romaricpascal romaricpascal commented Oct 3, 2021

No worries. In the meantime, I did find something that works without reaching to instance variables for configuring a slot once, but rendering it repeatedly. It relies on taking advantage that missing methods on the Slot will get forwarded to the component it holds (but only if it's a ViewComponent::Base it seems.

# in component
renders_many :items, -> (*args, **kwargs, &block) {
  ComponentTemplate.new(TagComponent, *args, **kwargs, &block)
}
<% records.each do |record| %>
  <%= items.each do |item| %>
    <% item.render_within(self, record: record) %>
  <% end %>
<% end %>

The ComponentTemplate class looks as such:

# Needs to be a ViewComponent::Base so that the slot forwards the missing_method
class ComponentTemplate < ViewComponent::Base

  def initialize(component_class, *args, **attributes, &block)
    @component_class = component_class
    @attributes = attributes
    @block = block
  end

  def render_within(parent_component, **attributes)
    @parent_component = parent_component
    @parent_component.render(@component_class.new(merge_attributes(attributes, @attributes)), &@block)
  end

  def merge_attributes(*attributes_list, **attributes)
    @parent_component.helpers.merge_attributes(*attributes_list, **attributes)
  end

  def call
    raise "ComponentTemplate is meant to be used through `#render_within`"
  end
end

Besides accessing the helpers bit (which I think may be specific to what what I'm trying to do), the parent_component is necessary so we can render the component with the same block that was provided to the slot at the start.

That's a bit of gymnatics but I guess less risky than continuing to reach for these instance variables.

It'd still be great to have an API where we can just do:

class Table
  renders_many :cells, reusable: true
  
  def initialize(records: nil)
    @records = records
  end
end

And then

<table>
<% @records.each do |record| %>
  <tr>
    <%= cells.each do |cell| %>
  	  <%# 
  	    `with_` could be a marker for slots to forward the method 
        but return itself so `to_s` could be invoked 
      %>
      <% cell.with_attributes(record: record) %>
    <% end %>
  </tr>
<% end %>
</table>

It's not just useful for tables, things like a TabsComponent displaying tabs for each records but providing help with all the ids and such required for accessibility would also benefit from being able to reuse slots. I guess anytime you need to iterate on records, but also on slots.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants