Class: Panda::CMS::CodeComponent

Inherits:
ViewComponent::Base
  • Object
show all
Defined in:
app/components/panda/cms/code_component.rb

Overview

Text component

Constant Summary collapse

KIND =
"code"

Instance Method Summary collapse

Constructor Details

#initialize(key: :text_component, text: "", editable: true, **options) ⇒ CodeComponent

Returns a new instance of CodeComponent.

Raises:



13
14
15
16
17
18
19
20
21
# File 'app/components/panda/cms/code_component.rb', line 13

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

  raise BlockError, "Key 'code' is not allowed for CodeComponent" if key == :code
end

Instance Method Details

#callObject



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
# File 'app/components/panda/cms/code_component.rb', line 23

def call
  # TODO: For the non-editable version, grab this from a cache or similar?
  block = Panda::CMS::Block.find_by(kind: KIND, key: @key,
    panda_cms_template_id: Current.page.panda_cms_template_id)

  if block.nil?
    unless Rails.env.production?
      raise Panda::CMS::MissingBlockError, "Block with key #{@key} not found for page #{Current.page.title}"
    end

    return false
  end

  block_content = block.block_contents.find_by(panda_cms_page_id: Current.page.id)
  code_content = block_content&.content.to_s

  if component_is_editable?
    @options[:contenteditable] = "plaintext-only"
    @options[:data] = {
      "editable-kind": "html",
      "editable-page-id": Current.page.id,
      "editable-block-content-id": block_content&.id
    }
    @options[:class] = "block bg-yellow-50 font-mono text-xs p-2 border-2 border-yellow-700"
    @options[:style] = "white-space: pre-wrap;"

    @options[:id] = "editor-#{block_content&.id}"

    # TODO: Switch between the HTML and the preview?
    (:div, code_content, @options, true)
  else
    code_content.html_safe
  end
end

#component_is_editable?Boolean

Returns:

  • (Boolean)


58
59
60
61
# File 'app/components/panda/cms/code_component.rb', line 58

def component_is_editable?
  # TODO: Permissions
  @editable && is_embedded? && Current.user&.admin
end

#is_embedded?Boolean

Returns:

  • (Boolean)


63
64
65
66
# File 'app/components/panda/cms/code_component.rb', line 63

def is_embedded?
  # TODO: Check security on this - embed_id should match something?
  request.params[:embed_id].present?
end