Sha256: 72f11a711d76dc8ec6eb11a2e7406eb12ee0f7365966d12b09c102929528b1f0

Contents?: true

Size: 1.35 KB

Versions: 9

Compression:

Stored size: 1.35 KB

Contents

# frozen_string_literal: true

module SCSSLint
  # Checks for unnecessary units on zero values.
  class Linter::ZeroUnit < Linter
    include LinterRegistry

    def visit_script_string(node)
      return unless node.type == :identifier
      return if node.value.start_with?('calc(')

      node.value.scan(ZERO_UNIT_REGEX) do |match|
        next unless zero_with_length_units?(match.first)
        add_lint(node, MESSAGE_FORMAT % match.first)
      end
    end

    def visit_script_number(node)
      length = source_from_range(node.source_range)[ZERO_UNIT_REGEX, 1]
      return unless zero_with_length_units?(length)

      add_lint(node, MESSAGE_FORMAT % length)
    end

    def visit_script_funcall(node)
      # Don't report errors for values within `calc` expressions, since they
      # require units in order to work
      yield unless node.name == 'calc'
    end

  private

    ZERO_UNIT_REGEX = /
      \b
      (?<!\.|\#)    # Ignore zeroes following `#` (colors) or `.` (decimals)
      (0[a-z]+)     # Zero followed by letters indicating some sort of unit
      \b
    /ix

    MESSAGE_FORMAT = '`%s` should be written without units as `0`'.freeze

    LENGTH_UNITS = %w[em ex ch rem vw vh vmin vmax cm mm in pt pc px].to_set

    def zero_with_length_units?(string)
      string =~ /^0([a-z]+)/ && LENGTH_UNITS.include?(Regexp.last_match(1))
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
scss_lint-0.57.1 lib/scss_lint/linter/zero_unit.rb
scss_lint-0.57.0 lib/scss_lint/linter/zero_unit.rb
scss_lint-0.56.0 lib/scss_lint/linter/zero_unit.rb
scss_lint-0.55.0 lib/scss_lint/linter/zero_unit.rb
scss_lint-0.54.0 lib/scss_lint/linter/zero_unit.rb
scss_lint-0.53.0 lib/scss_lint/linter/zero_unit.rb
scss_lint-0.52.0 lib/scss_lint/linter/zero_unit.rb
scss_lint-0.51.0 lib/scss_lint/linter/zero_unit.rb
scss_lint-0.50.3 lib/scss_lint/linter/zero_unit.rb