# 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 TextComponent < ViewComponent::Base KIND = "plain_text" # Allows accessing the plain text of the component directly attr_accessor :plain_text 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 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) block_content = block.block_contents.find_by(panda_cms_page_id: Current.page.id) @plain_text = block_content&.content content = prepare_content(@plain_text) if @editable @options[:contenteditable] = "plaintext-only" @options[:contenteditable] = "true" @options[:data] = { controller: "editable", action: "focusout->editable#save", "editable-target": "source", "editable-page-value": Current.page.id, "editable-blockcontent-value": block_content&.id, "editable-initial-class": "w-full panda-cms-transition-all panda-cms-duration-1000 panda-cms-mt-2 panda-cms-bg-yellow-100 panda-cms-border-dashed panda-cms-border-2 panda-cms-border-yellow-500 panda-cms-rounded-sm panda-cms-p-2 panda-cms-focus:outline-yellow-500", "editable-success-class": "w-full panda-cms-transition-all panda-cms-duration-1000 panda-cms-mt-2 panda-cms-bg-green-100 panda-cms-border-dashed panda-cms-border-2 panda-cms-border-green-500 panda-cms-rounded-sm panda-cms-p-2", "editable-error-class": "w-full panda-cms-transition-all panda-cms-duration-1000 panda-cms-mt-2 panda-cms-bg-red-100 panda-cms-border-dashed panda-cms-border-2 panda-cms-border-red-500 panda-cms-rounded-sm panda-cms-p-2" } @options[:class] = @options[:data]["editable-initial-class"] @options[:id] = "editor" end content_tag(:div, content, @options) end def prepare_content(content) content end # Check if the element is editable def before_render # TODO: Check if the current user is authenticated and is allowed to save # TODO: And we're within an iFrame? # Only mark elements as editable if we've passed the correct page ID as a parameter @editable &&= params[:embed_id].present? && params[:embed_id] == Current.page.id end end end