Sha256: 49e21ce07b549d23c0fd99677fb5b6f9b6a45afd458ebf22db532a85c3ba35b9

Contents?: true

Size: 1.35 KB

Versions: 74

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

74 entries across 74 versions & 1 rubygems

Version Path
coveragebook_components-0.8.5 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.8.4 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.8.3 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.8.2 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.8.1 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.8.0 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.8.0.beta.3 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.8.0.beta.2 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.8.0.beta.1 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.10 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.9 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.8 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.7 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.6 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.5 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.4 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.3 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.2 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.1 app/helpers/coco/alpine_helper.rb
coveragebook_components-0.7.0 app/helpers/coco/alpine_helper.rb