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 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
|
# frozen_string_literal: true
require "active_support/concern"
require "active_support/inflector/inflections"
require "view_component/slot"
module ViewComponent
module Slotable
extend ActiveSupport::Concern
RESERVED_NAMES = {
singular: %i[content render].freeze,
plural: %i[contents renders].freeze
}.freeze
private_constant :RESERVED_NAMES
included do
class_attribute :registered_slots, default: {}
end
class_methods do
##
# Registers a sub-component
#
# = Example
#
# renders_one :header -> (classes:) do
# HeaderComponent.new(classes: classes)
# end
#
# # OR
#
# renders_one :header, HeaderComponent
#
# where `HeaderComponent` is defined as:
#
# class HeaderComponent < ViewComponent::Base
# def initialize(classes:)
# @classes = classes
# end
# end
#
# and has the following template:
#
# <header class="<%= @classes %>">
# <%= content %>
# </header>
#
# = Rendering sub-component content
#
# The component's sidecar template can access the sub-component by calling a
# helper method with the same name as the sub-component.
#
# <h1>
# <%= header do %>
# My header title
# <% end %>
# </h1>
#
# = Setting sub-component content
#
# Consumers of the component can render a sub-component by calling a
# helper method with the same name as the slot prefixed with `with_`.
#
# <%= render_inline(MyComponent.new) do |component| %>
# <% component.with_header(classes: "Foo") do %>
# <p>Bar</p>
# <% end %>
# <% end %>
#
# Additionally, content can be set by calling `with_SLOT_NAME_content`
# on the component instance.
#
# <%= render_inline(MyComponent.new.with_header_content("Foo")) %>
def renders_one(slot_name, callable = nil)
__vc_validate_singular_slot_name(slot_name)
if callable.is_a?(Hash) && callable.key?(:types)
__vc_register_polymorphic_slot(slot_name, callable[:types], collection: false)
else
__vc_validate_plural_slot_name(ActiveSupport::Inflector.pluralize(slot_name).to_sym)
setter_method_name = :"with_#{slot_name}"
define_method setter_method_name do |*args, **kwargs, &block|
__vc_set_slot(slot_name, nil, *args, **kwargs, &block)
end
self::GeneratedSlotMethods.define_method slot_name do
__vc_get_slot(slot_name)
end
self::GeneratedSlotMethods.define_method :"#{slot_name}?" do
__vc_get_slot(slot_name).present?
end
define_method :"with_#{slot_name}_content" do |content|
send(setter_method_name) { content.to_s }
self
end
__vc_register_slot(slot_name, collection: false, callable: callable)
end
end
##
# Registers a collection sub-component
#
# = Example
#
# renders_many :items, -> (name:) { ItemComponent.new(name: name }
#
# # OR
#
# renders_many :items, ItemComponent
#
# = Rendering sub-components
#
# The component's sidecar template can access the slot by calling a
# helper method with the same name as the slot.
#
# <h1>
# <% items.each do |item| %>
# <%= item %>
# <% end %>
# </h1>
#
# = Setting sub-component content
#
# Consumers of the component can set the content of a slot by calling a
# helper method with the same name as the slot prefixed with `with_`. The
# method can be called multiple times to append to the slot.
#
# <%= render_inline(MyComponent.new) do |component| %>
# <% component.with_item(name: "Foo") do %>
# <p>One</p>
# <% end %>
#
# <% component.with_item(name: "Bar") do %>
# <p>two</p>
# <% end %>
# <% end %>
def renders_many(slot_name, callable = nil)
__vc_validate_plural_slot_name(slot_name)
if callable.is_a?(Hash) && callable.key?(:types)
__vc_register_polymorphic_slot(slot_name, callable[:types], collection: true)
else
singular_name = ActiveSupport::Inflector.singularize(slot_name)
__vc_validate_singular_slot_name(ActiveSupport::Inflector.singularize(slot_name).to_sym)
setter_method_name = :"with_#{singular_name}"
define_method setter_method_name do |*args, **kwargs, &block|
__vc_set_slot(slot_name, nil, *args, **kwargs, &block)
end
define_method :"with_#{singular_name}_content" do |content|
send(setter_method_name) { content.to_s }
self
end
define_method :"with_#{slot_name}" do |collection_args = nil, &block|
collection_args.map do |args|
if args.respond_to?(:to_hash)
__vc_set_slot(slot_name, nil, **args, &block)
else
__vc_set_slot(slot_name, nil, *args, &block)
end
end
end
self::GeneratedSlotMethods.define_method slot_name do
__vc_get_slot(slot_name)
end
self::GeneratedSlotMethods.define_method :"#{slot_name}?" do
__vc_get_slot(slot_name).present?
end
__vc_register_slot(slot_name, collection: true, callable: callable)
end
end
def slot_type(slot_name)
registered_slot = registered_slots[slot_name]
if registered_slot
registered_slot[:collection] ? :collection : :single
else
plural_slot_name = ActiveSupport::Inflector.pluralize(slot_name).to_sym
plural_registered_slot = registered_slots[plural_slot_name]
plural_registered_slot&.fetch(:collection) ? :collection_item : nil
end
end
def inherited(child)
# Clone slot configuration into child class
# see #test_slots_pollution
child.registered_slots = registered_slots.clone
# Add a module for slot methods, allowing them to be overriden by the component class
# see #test_slot_name_can_be_overriden
unless child.const_defined?(:GeneratedSlotMethods, false)
generated_slot_methods = Module.new
child.const_set(:GeneratedSlotMethods, generated_slot_methods)
child.include generated_slot_methods
end
super
end
# @private
# Called by the compiler, as instance methods are not defined when slots are first registered
def __vc_register_default_slots
registered_slots.each do |slot_name, config|
default_method_name = :"default_#{slot_name}"
config[:default_method] = instance_methods.find { |method_name| method_name == default_method_name }
registered_slots[slot_name] = config
end
end
private
def __vc_register_slot(slot_name, **kwargs)
registered_slots[slot_name] = __vc_define_slot(slot_name, **kwargs)
end
def __vc_register_polymorphic_slot(slot_name, types, collection:)
self::GeneratedSlotMethods.define_method(slot_name) do
__vc_get_slot(slot_name)
end
self::GeneratedSlotMethods.define_method(:"#{slot_name}?") do
__vc_get_slot(slot_name).present?
end
renderable_hash = types.each_with_object({}) do |(poly_type, poly_attributes_or_callable), memo|
if poly_attributes_or_callable.is_a?(Hash)
poly_callable = poly_attributes_or_callable[:renders]
poly_slot_name = poly_attributes_or_callable[:as]
else
poly_callable = poly_attributes_or_callable
poly_slot_name = nil
end
poly_slot_name ||=
if collection
"#{ActiveSupport::Inflector.singularize(slot_name)}_#{poly_type}"
else
"#{slot_name}_#{poly_type}"
end
memo[poly_type] = __vc_define_slot(
poly_slot_name, collection: collection, callable: poly_callable
)
setter_method_name = :"with_#{poly_slot_name}"
if method_defined?(setter_method_name)
raise AlreadyDefinedPolymorphicSlotSetterError.new(setter_method_name, poly_slot_name)
end
define_method(setter_method_name) do |*args, **kwargs, &block|
__vc_set_polymorphic_slot(slot_name, poly_type, *args, **kwargs, &block)
end
define_method :"with_#{poly_slot_name}_content" do |content|
send(setter_method_name) { content.to_s }
self
end
end
registered_slots[slot_name] = {
collection: collection,
renderable_hash: renderable_hash
}
end
def __vc_define_slot(slot_name, collection:, callable:)
slot = {collection: collection}
return slot unless callable
# If callable responds to `render_in`, we set it on the slot as a renderable
if callable.respond_to?(:method_defined?) && callable.method_defined?(:render_in)
slot[:renderable] = callable
elsif callable.is_a?(String)
# If callable is a string, we assume it's referencing an internal class
slot[:renderable_class_name] = callable
elsif callable.respond_to?(:call)
# If slot doesn't respond to `render_in`, we assume it's a proc,
# define a method, and save a reference to it to call when setting
method_name = :"_call_#{slot_name}"
define_method method_name, &callable
slot[:renderable_function] = instance_method(method_name)
else
raise(InvalidSlotDefinitionError)
end
slot
end
def __vc_validate_plural_slot_name(slot_name)
if RESERVED_NAMES[:plural].include?(slot_name.to_sym)
raise ReservedPluralSlotNameError.new(name, slot_name)
end
__vc_raise_if_slot_name_uncountable(slot_name)
__vc_raise_if_slot_conflicts_with_call(slot_name)
__vc_raise_if_slot_ends_with_question_mark(slot_name)
__vc_raise_if_slot_registered(slot_name)
end
def __vc_validate_singular_slot_name(slot_name)
if slot_name.to_sym == :content
raise ContentSlotNameError.new(name)
end
if RESERVED_NAMES[:singular].include?(slot_name.to_sym)
raise ReservedSingularSlotNameError.new(name, slot_name)
end
__vc_raise_if_slot_conflicts_with_call(slot_name)
__vc_raise_if_slot_ends_with_question_mark(slot_name)
__vc_raise_if_slot_registered(slot_name)
end
def __vc_raise_if_slot_registered(slot_name)
if registered_slots.key?(slot_name)
raise RedefinedSlotError.new(name, slot_name)
end
end
def __vc_raise_if_slot_ends_with_question_mark(slot_name)
raise SlotPredicateNameError.new(name, slot_name) if slot_name.to_s.end_with?("?")
end
def __vc_raise_if_slot_conflicts_with_call(slot_name)
if slot_name.start_with?("call_")
raise InvalidSlotNameError, "Slot cannot start with 'call_'. Please rename #{slot_name}"
end
end
def __vc_raise_if_slot_name_uncountable(slot_name)
slot_name = slot_name.to_s
if slot_name.pluralize == slot_name.singularize
raise UncountableSlotNameError.new(name, slot_name)
end
end
end
def __vc_get_slot(slot_name)
@__vc_set_slots ||= {}
content unless defined?(@__vc_content_evaluated) && @__vc_content_evaluated # ensure content is loaded so slots will be defined
# If the slot is set, return it
return @__vc_set_slots[slot_name] if @__vc_set_slots[slot_name]
# If there is a default method for the slot, call it
if (default_method = registered_slots[slot_name][:default_method])
renderable_value = send(default_method)
slot = Slot.new(self)
if renderable_value.respond_to?(:render_in)
slot.__vc_component_instance = renderable_value
else
slot.__vc_content = renderable_value
end
slot
elsif self.class.registered_slots[slot_name][:collection]
# If empty slot is a collection, return an empty array
[]
end
end
def __vc_set_slot(slot_name, slot_definition = nil, *args, **kwargs, &block)
slot_definition ||= self.class.registered_slots[slot_name]
slot = Slot.new(self)
# Passing the block to the sub-component wrapper like this has two
# benefits:
#
# 1. If this is a `content_area` style sub-component, we will render the
# block via the `slot`
#
# 2. Since we have to pass block content to components when calling
# `render`, evaluating the block here would require us to call
# `view_context.capture` twice, which is slower
if block
slot.__vc_content_block = block
# Capture the virtual path at the time the block is defined, so that
# translations resolve relative to where the block was created, not where it's rendered
slot.__vc_content_block_virtual_path = view_context.instance_variable_get(:@virtual_path)
end
# If class
if slot_definition[:renderable]
slot.__vc_component_instance = slot_definition[:renderable].new(*args, **kwargs)
# If class name as a string
elsif slot_definition[:renderable_class_name]
slot.__vc_component_instance =
self.class.const_get(slot_definition[:renderable_class_name]).new(*args, **kwargs)
# If passed a lambda
elsif slot_definition[:renderable_function]
# Use `bind(self)` to ensure lambda is executed in the context of the
# current component. This is necessary to allow the lambda to access helper
# methods like `content_tag` as well as parent component state.
renderable_function = slot_definition[:renderable_function].bind(self)
renderable_value =
if block
renderable_function.call(*args, **kwargs) do |*rargs|
with_captured_virtual_path(@old_virtual_path) do
view_context.capture(*rargs, &block)
end
end
else
renderable_function.call(*args, **kwargs)
end
# Function calls can return components, so if it's a component handle it specially
if renderable_value.respond_to?(:render_in)
slot.__vc_component_instance = renderable_value
else
slot.__vc_content = renderable_value
end
end
@__vc_set_slots ||= {}
if slot_definition[:collection]
@__vc_set_slots[slot_name] ||= []
@__vc_set_slots[slot_name].push(slot)
else
@__vc_set_slots[slot_name] = slot
end
slot
end
def __vc_set_polymorphic_slot(slot_name, poly_type = nil, *args, **kwargs, &block)
slot_definition = self.class.registered_slots[slot_name]
if !slot_definition[:collection] && defined?(@__vc_set_slots) && @__vc_set_slots[slot_name]
raise ContentAlreadySetForPolymorphicSlotError.new(slot_name)
end
poly_def = slot_definition[:renderable_hash][poly_type]
__vc_set_slot(slot_name, poly_def, *args, **kwargs, &block)
end
end
end
|