Sha256: 49e21ce07b549d23c0fd99677fb5b6f9b6a45afd458ebf22db532a85c3ba35b9

Contents?: true

Size: 1.35 KB

Versions: 73

Compression:

Stored size: 1.35 KB

Contents

module Coco
  module AlpineHelper
    include TagHelper

    def x_data(name = nil, data = {})
      if name.is_a?(Hash)
        data = name
        name = nil
      end

      props_str = data.present? ? jsify_data(data) : nil

      expression = if name.present?
        "#{jsify_var_name(name)}#{"(#{props_str})" if props_str.present?}"
      else
        props_str
      end

      expression.html_safe
    end

    def x_attrs(attrs, root: false)
      attrs.symbolize_keys!

      if root && !attrs.key?(:data)
        attrs[:data] = "" # Add empty x-data attribute if none has been specified
      end

      attrs.transform_values! { (_1 == true) ? "" : _1 } # convert boolean x-attributes

      # prefix attributes where needed
      attrs.transform_keys do |key|
        key = key.to_s
        key.first.in?(["@", ":"]) ? key : "x-#{key}"
      end
    end

    protected

    def jsify_data(hash)
      result = hash.reduce("") do |str, (k, v)|
        key = jsify_var_name(k)
        value = if v.is_a?(Hash)
          jsify_data(v)
        else
          v.to_json.gsub("'", "\\\\'").tr("\"", "'")
        end

        "#{"#{str}, " if str.present?}#{key}: #{value}"
      end

      "{#{result}}"
    end

    def jsify_var_name(name)
      name.to_s.tr("-", "_").camelize(:lower)
    end

    private

    include ActionView::Helpers::JavaScriptHelper
  end
end

Version data entries

73 entries across 73 versions & 1 rubygems

Version Path
coveragebook_components-0.19.8 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.19.7 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.19.6 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.19.5 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.19.4 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.19.3 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.19.2 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.19.1 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.19.0 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.18.8 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.18.7 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.18.0 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.17.7 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.17.6 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.17.5 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.17.4 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.17.3 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.17.2 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.17.1 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.17.0 app/helpers/coco/alpine_helper.rb