Class: PandaCms::TextComponent

Inherits:
ViewComponent::Base
  • Object
show all
Defined in:
app/components/panda_cms/text_component.rb

Overview

Text component

Constant Summary collapse

KIND =
"plain_text"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key: :text_component, text: "Lorem ipsum...", editable: true, **options) ⇒ TextComponent

Returns a new instance of TextComponent.



15
16
17
18
19
20
21
# File 'app/components/panda_cms/text_component.rb', line 15

def initialize(key: :text_component, text: "Lorem ipsum...", editable: true, **options)
  @key = key
  @text = text
  @options = options || {}
  @options[:id] ||= "text-#{key.to_s.dasherize}"
  @editable = editable
end

Instance Attribute Details

#plain_textObject

Allows accessing the plain text of the component directly



13
14
15
# File 'app/components/panda_cms/text_component.rb', line 13

def plain_text
  @plain_text
end

Instance Method Details

#before_renderObject

Check if the element is editable TODO: Check user permissions



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
# File 'app/components/panda_cms/text_component.rb', line 44

def before_render
  @editable &&= params[:embed_id].present? && params[:embed_id] == Current.page.id

  block = PandaCms::Block.find_by(kind: KIND, key: @key, panda_cms_template_id: Current.page.panda_cms_template_id)

  if block.nil?
    return false
  end

  block_content = block.block_contents.find_by(panda_cms_page_id: Current.page.id)
  plain_text = block_content&.content.to_s
  if @editable
    @options[:contenteditable] = "plaintext-only"
    @options[:data] = {
      "editable-kind": "plain_text",
      "editable-page-id": Current.page.id,
      "editable-block-content-id": block_content&.id
    }

    @options[:id] = "editor-#{block_content&.id}"
    @content = plain_text
  else
    @content = prepare_content_for_display(plain_text)
  end
end

#callObject



23
24
25
26
27
28
29
30
31
# File 'app/components/panda_cms/text_component.rb', line 23

def call
  (:span, @content, @options, false) # Don't escape the content
rescue
  if !Rails.env.production? || is_defined?(Sentry)
    raise PandaCms::MissingBlockError.new("Block with key #{@key} not found for page #{Current.page.title}")
  else
    false
  end
end

#prepare_content_for_display(content) ⇒ Object

Prepares content for display



37
38
39
40
# File 'app/components/panda_cms/text_component.rb', line 37

def prepare_content_for_display(content)
  # Replace \n characters with <br> tags
  content.gsub("\n", "<br>")
end