Sha256: cc6b4580d672e0fe28c18f4f7041f33fd5da245c7f486c0df6931e1b3c8dd134

Contents?: true

Size: 1.99 KB

Versions: 1

Compression:

Stored size: 1.99 KB

Contents

# frozen_string_literal: true

module PandaCms
  # Text component
  # @param key [Symbol] The key to use for the text component
  # @param text [String] The text to display
  # @param editable [Boolean] If the text is editable or not (defaults to true)
  # @param options [Hash] The options to pass to the content_tag
  class CodeComponent < ViewComponent::Base
    KIND = "code"

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

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

      if block.nil?
        raise PandaCms::MissingBlockError("Block with key #{@key} not found") unless Rails.env.production?
        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 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?
        content_tag(:div, code_content, @options, true)
      else
        code_content.html_safe
      end
    end

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

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
panda_cms-0.6.0 app/components/panda_cms/code_component.rb