Module: LiveComponent::Base::Overrides

Defined in:
lib/live_component/base.rb

Instance Method Summary collapse

Instance Method Details

#initialize(__lc_attributes: {}, **props, &block) ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/live_component/base.rb', line 188

def initialize(__lc_attributes: {}, **props, &block)
  @__lc = { ruby_class: self.class.name }
  @__lc_attributes = __lc_attributes

  UseContext.use_context(:__lc_context, :slot_name) do |slot_name|
    @__lc_slot_name = slot_name if slot_name
  end

  self.class.__lc_compile_if_necessary!

  super(**props, &block)
end

#render_in(view_context, &block) ⇒ Object



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
# File 'lib/live_component/base.rb', line 201

def render_in(view_context, &block)
  props = {
    __lc_attributes: @__lc_attributes.merge(
      "data-id" => __lc_id
    )
  }

  current_state = State.new(
    klass: self.class,
    props: props,
    slots: @__lc[:slots] || {},
    children: @__lc[:children] || {},
  )

  result = UseContext.use_context(:__lc_context, :state) do |parent_state|
    if !parent_state
      current_state.root!
    end

    if parent_state
      if @__lc_slot_name
        parent_state.slots[@__lc_slot_name] ||= []
        parent_state.slots[@__lc_slot_name] << current_state
      else
        parent_state.children[__lc_id] = current_state
      end
    end

    UseContext.provide_context(:__lc_context, { state: current_state }) do
      super
    end
  end

  self.class.__lc_init_args.each do |(type, name)|
    if type == :key || type == :keyreq
      props[name] = instance_variable_get(:"@#{name}")
    elsif type == :keyrest
      props.merge!(instance_variable_get(:"@#{name}"))
    end
  end

  if @__vc_content
    @__lc[:content] = Utils.normalize_html_whitespace(@__vc_content)
    current_state.content = @__lc[:content]
  end

  attributes = {
    "data-id" => __lc_id,
    "data-controller" => __lc_controller,
    "data-livecomponent" => "true",
    "data-component" => self.class.name,
    **@__lc_attributes,
  }

  if current_state.root?
    attributes["data-state"] = current_state.to_json
  end

  if @__lc_slot_name
    attributes["data-slot-name"] = @__lc_slot_name
  end

  (__lc_tag_name, result, **attributes)
end