Module: Sass::Script::Functions
- Included in:
- EvaluationContext
- Defined in:
- /home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb
Overview
Methods in this module are accessible from the SassScript context. For example, you can write
$color: hsl(120deg, 100%, 50%)
and it will call #hsl.
The following functions are provided:
Note: These functions are described in more detail below.
RGB Functions
rgb($red, $green, $blue) : Creates a Color from red, green, and blue values.
rgba($red, $green, $blue, $alpha) : Creates a Color from red, green, blue, and alpha values.
red($color) : Gets the red component of a color.
green($color) : Gets the green component of a color.
blue($color) : Gets the blue component of a color.
mix($color1, $color2, [$weight]) : Mixes two colors together.
HSL Functions
hsl($hue, $saturation, $lightness) : Creates a Color from hue, saturation, and lightness values.
hsla($hue, $saturation, $lightness, $alpha) : Creates a Color from hue, saturation, lightness, and alpha values.
hue($color) : Gets the hue component of a color.
saturation($color) : Gets the saturation component of a color.
lightness($color) : Gets the lightness component of a color.
adjust-hue($color, $degrees) : Changes the hue of a color.
lighten($color, $amount) : Makes a color lighter.
darken($color, $amount) : Makes a color darker.
saturate($color, $amount) : Makes a color more saturated.
desaturate($color, $amount) : Makes a color less saturated.
grayscale($color) : Converts a color to grayscale.
complement($color) : Returns the complement of a color.
invert($color, [$weight]) : Returns the inverse of a color.
Opacity Functions
alpha($color) / opacity($color) : Gets the alpha component (opacity) of a color.
rgba($color, $alpha) : Changes the alpha component for a color.
opacify($color, $amount) / fade-in($color, $amount) : Makes a color more opaque.
transparentize($color, $amount) / fade-out($color, $amount) : Makes a color more transparent.
Other Color Functions
adjust-color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) : Increases or decreases one or more components of a color.
scale-color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha]) : Fluidly scales one or more properties of a color.
change-color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) : Changes one or more properties of a color.
ie-hex-str($color) : Converts a color into the format understood by IE filters.
String Functions
unquote($string) : Removes quotes from a string.
quote($string) : Adds quotes to a string.
str-length($string) : Returns the number of characters in a string.
str-insert($string, $insert, $index) : Inserts $insert into $string at $index.
str-index($string, $substring) : Returns the index of the first occurrence of $substring in $string.
str-slice($string, $start-at, [$end-at]) : Extracts a substring from $string.
to-upper-case($string) : Converts a string to upper case.
to-lower-case($string) : Converts a string to lower case.
Number Functions
percentage($number) : Converts a unitless number to a percentage.
round($number) : Rounds a number to the nearest whole number.
ceil($number) : Rounds a number up to the next whole number.
floor($number) : Rounds a number down to the previous whole number.
abs($number) : Returns the absolute value of a number.
min($numbers...) : Finds the minimum of several numbers.
max($numbers...) : Finds the maximum of several numbers.
random([$limit]) : Returns a random number.
List Functions #list-functions
Lists in Sass are immutable; all list functions return a new list rather than updating the existing list in-place.
All list functions work for maps as well, treating them as lists of pairs.
length($list) : Returns the length of a list.
nth($list, $n) : Returns a specific item in a list.
set-nth($list, $n, $value) : Replaces the nth item in a list.
join($list1, $list2, [$separator, $bracketed]) : Joins together two lists into one.
append($list1, $val, [$separator]) : Appends a single value onto the end of a list.
zip($lists...) : Combines several lists into a single multidimensional list.
index($list, $value) : Returns the position of a value within a list.
list-separator($list) : Returns the separator of a list.
is-bracketed($list) : Returns whether a list has square brackets.
Map Functions #map-functions
Maps in Sass are immutable; all map functions return a new map rather than updating the existing map in-place.
map-get($map, $key) : Returns the value in a map associated with a given key.
map-merge($map1, $map2) : Merges two maps together into a new map.
map-remove($map, $keys...) : Returns a new map with keys removed.
map-keys($map) : Returns a list of all keys in a map.
map-values($map) : Returns a list of all values in a map.
map-has-key($map, $key) : Returns whether a map has a value associated with a given key.
keywords($args) : Returns the keywords passed to a function that takes variable arguments.
Selector Functions
Selector functions are very liberal in the formats they support for selector arguments. They can take a plain string, a list of lists as returned by & or anything in between:
- A plain string, such as
".foo .bar, .baz .bang". - A space-separated list of strings such as
(".foo" ".bar"). - A comma-separated list of strings such as
(".foo .bar", ".baz .bang"). - A comma-separated list of space-separated lists of strings such as
((".foo" ".bar"), (".baz" ".bang")).
In general, selector functions allow placeholder selectors (%foo) but disallow parent-reference selectors (&).
selector-nest($selectors...) : Nests selector beneath one another like they would be nested in the stylesheet.
selector-append($selectors...) : Appends selectors to one another without spaces in between.
selector-extend($selector, $extendee, $extender) : Extends $extendee with $extender within $selector.
selector-replace($selector, $original, $replacement) : Replaces $original with $replacement within $selector.
selector-unify($selector1, $selector2) : Unifies two selectors to produce a selector that matches elements matched by both.
is-superselector($super, $sub) : Returns whether $super matches all the elements $sub does, and possibly more.
simple-selectors($selector) : Returns the simple selectors that comprise a compound selector.
selector-parse($selector) : Parses a selector into the format returned by &.
Introspection Functions
feature-exists($feature) : Returns whether a feature exists in the current Sass runtime.
variable-exists($name) : Returns whether a variable with the given name exists in the current scope.
global-variable-exists($name) : Returns whether a variable with the given name exists in the global scope.
function-exists($name) : Returns whether a function with the given name exists.
mixin-exists($name) : Returns whether a mixin with the given name exists.
content-exists() : Returns whether the current mixin was passed a content block.
inspect($value) : Returns the string representation of a value as it would be represented in Sass.
type-of($value) : Returns the type of a value.
unit($number) : Returns the unit(s) associated with a number.
unitless($number) : Returns whether a number has units.
comparable($number1, $number2) : Returns whether two numbers can be added, subtracted, or compared.
call($function, $args...) : Dynamically calls a Sass function reference returned by get-function.
get-function($name, $css: false) : Looks up a function with the given name in the current lexical scope and returns a reference to it.
Miscellaneous Functions
if($condition, $if-true, $if-false) : Returns one of two values, depending on whether or not $condition is true.
unique-id() : Returns a unique CSS identifier.
Adding Custom Functions
New Sass functions can be added by adding Ruby methods to this module. For example:
module Sass::Script::Functions
def reverse(string)
assert_type string, :String
Sass::Script::Value::String.new(string.value.reverse)
end
declare :reverse, [:string]
end
Calling Functions.declare tells Sass the argument names for your function. If omitted, the function will still work, but will not be able to accept keyword arguments. Functions.declare can also allow your function to take arbitrary keyword arguments.
There are a few things to keep in mind when modifying this module. First of all, the arguments passed are Value objects. Value objects are also expected to be returned. This means that Ruby values must be unwrapped and wrapped.
Most Value objects support the value accessor for getting their Ruby values. Color objects, though, must be accessed using rgb, red, green, or blue.
Second, making Ruby functions accessible from Sass introduces the temptation to do things like database access within stylesheets. This is generally a bad idea; since Sass files are by default only compiled once, dynamic code is not a great fit.
If you really, really need to compile Sass on each request, first make sure you have adequate caching set up. Then you can use Engine to render the code, using the options parameter to pass in data that can be accessed from your Sass functions.
Within one of the functions in this module, methods of EvaluationContext can be used.
Caveats
When creating new Value objects within functions, be aware that it's not safe to call #to_s (or other methods that use the string representation) on those objects without first setting the #options attribute.
Defined Under Namespace
Classes: EvaluationContext, Signature
Class Method Summary (collapse)
- + declare(method_name, args, options = {})
Declare a Sass signature for a Ruby-defined function.
- + (Random) random_number_generator
Get Sass's internal random number generator.
- + (Integer) random_seed=(seed)
Sets the random seed used by Sass's internal random number generator.
- + ({Symbol => Object}?) signature(method_name, arg_arity, kwarg_arity)
Determine the correct signature for the number of arguments passed in for a given function.
Instance Method Summary (collapse)
- - (Sass::Script::Value::Number) abs($number)
Returns the absolute value of a number.
- - (Sass::Script::Value::Color) adjust_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
Increases or decreases one or more properties of a color.
- - (Sass::Script::Value::Color) adjust_hue($color, $degrees)
Changes the hue of a color.
- - (Sass::Script::Value::Number) alpha($color)
Returns the alpha component (opacity) of a color.
- - (Sass::Script::Value::List) append($list, $val, $separator:auto)
Appends a single value onto the end of a list.
- - (Sass::Script::Value::Number) blue($color)
Gets the blue component of a color.
- - call($function, $args...)
Dynamically calls a function.
- - (Sass::Script::Value::Number) ceil($number)
Rounds a number up to the next whole number.
- - (Sass::Script::Value::Color) change_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
Changes one or more properties of a color.
- - (Sass::Script::Value::Bool) comparable($number1, $number2)
Returns whether two numbers can added, subtracted, or compared.
- - (Sass::Script::Value::Color) complement($color)
Returns the complement of a color.
- - (Sass::Script::Value::Bool) content_exists
Check whether a mixin was passed a content block.
- - (Sass::Script::Value::String) counter($args...)
This function only exists as a workaround for IE7's
content: counterbug. - - (Sass::Script::Value::String) counters($args...)
This function only exists as a workaround for IE7's
content: counterbug. - - (Sass::Script::Value::Color) darken($color, $amount)
Makes a color darker.
- - (Sass::Script::Value::Color) desaturate($color, $amount)
Makes a color less saturated.
- - (Sass::Script::Value::Bool) feature_exists($feature)
Returns whether a feature exists in the current Sass runtime.
- - (Sass::Script::Value::Number) floor($number)
Rounds a number down to the previous whole number.
- - (Sass::Script::Value::Bool) function_exists($name)
Check whether a function with the given name exists.
- - (Sass::Script::Value::Function) get_function($name, $css:false)
Returns a reference to a function for later invocation with the
call()function. - - (Sass::Script::Value::Bool) global_variable_exists($name)
Check whether a variable with the given name exists in the global scope (at the top level of the file).
- - (Sass::Script::Value::Color) grayscale($color)
Converts a color to grayscale.
- - (Sass::Script::Value::Number) green($color)
Gets the green component of a color.
- - (Sass::Script::Value::Color) hsl($hue, $saturation, $lightness)
Creates a Color from hue, saturation, and lightness values.
- - (Sass::Script::Value::Color) hsla($hue, $saturation, $lightness, $alpha)
Creates a Color from hue, saturation, lightness, and alpha values.
- - (Sass::Script::Value::Number) hue($color)
Returns the hue component of a color.
- - (Sass::Script::Value::String) ie_hex_str($color)
Converts a color into the format understood by IE filters.
- - (Sass::Script::Value::Base) if($condition, $if-true, $if-false)
Returns one of two values, depending on whether or not
$conditionis true. - - (Sass::Script::Value::Number, Sass::Script::Value::Null) index($list, $value)
Returns the position of a value within a list.
- - (Sass::Script::Value::String) inspect($value)
Return a string containing the value as its Sass representation.
- - (Sass::Script::Value::Color) invert(color, weight = number(100))
Returns the inverse (negative) of a color.
- - (Sass::Script::Value::Bool) is_bracketed($list)
Returns whether a list uses square brackets.
- - (Sass::Script::Value::Bool) is_superselector($super, $sub)
Returns whether
$superis a superselector of$sub. - - (Sass::Script::Value::List) join($list1, $list2, $separator:auto, $bracketed:auto)
Joins together two lists into one.
- - (Sass::Script::Value::Map) keywords($args)
Returns the map of named arguments passed to a function or mixin that takes a variable argument list.
- - (Sass::Script::Value::Number) length($list)
Return the length of a list.
- - (Sass::Script::Value::Color) lighten($color, $amount)
Makes a color lighter.
- - (Sass::Script::Value::Number) lightness($color)
Returns the lightness component of a color.
- - (Sass::Script::Value::String) list_separator($list)
Returns the separator of a list.
- - (Sass::Script::Value::Base) map_get($map, $key)
Returns the value in a map associated with the given key.
- - (Sass::Script::Value::Bool) map_has_key($map, $key)
Returns whether a map has a value associated with a given key.
- - (List) map_keys($map)
Returns a list of all keys in a map.
- - (Sass::Script::Value::Map) map_merge($map1, $map2)
Merges two maps together into a new map.
- - (Sass::Script::Value::Map) map_remove($map, $keys...)
Returns a new map with keys removed.
- - (List) map_values($map)
Returns a list of all values in a map.
- - (Sass::Script::Value::Number) max($numbers...)
Finds the maximum of several numbers.
- - (Sass::Script::Value::Number) min($numbers...)
Finds the minimum of several numbers.
- - (Sass::Script::Value::Color) mix($color1, $color2, $weight:50%)
Mixes two colors together.
- - (Sass::Script::Value::Bool) mixin_exists($name)
Check whether a mixin with the given name exists.
- - (Sass::Script::Value::Base) nth($list, $n)
Gets the nth item in a list.
- - (Sass::Script::Value::Color) opacify($color, $amount) (also: #fade_in)
Makes a color more opaque.
- - (Sass::Script::Value::Number) opacity($color)
Returns the alpha component (opacity) of a color.
- - (Sass::Script::Value::Number) percentage($number)
Converts a unitless number to a percentage.
- - (Sass::Script::Value::String) quote($string)
Add quotes to a string if the string isn't quoted, or returns the same string if it is.
- - random(limit = nil)
- - (Sass::Script::Value::Number) red($color)
Gets the red component of a color.
- - (Sass::Script::Value::Color) rgb($red, $green, $blue)
Creates a Color object from red, green, and blue values.
- - rgba(*args)
Creates a Color from red, green, blue, and alpha values.
- - (Sass::Script::Value::Number) round($number)
Rounds a number to the nearest whole number.
- - (Sass::Script::Value::Color) saturate($color, $amount)
Makes a color more saturated.
- - (Sass::Script::Value::Number) saturation($color)
Returns the saturation component of a color.
- - (Sass::Script::Value::Color) scale_color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha])
Fluidly scales one or more properties of a color.
- - (Sass::Script::Value::List) selector_append($selectors...)
Return a new selector with all selectors in
$selectorsappended one another as though they had been nested in the stylesheet as$selector1 { &$selector2 { ... } }. - - (Sass::Script::Value::List) selector_extend($selector, $extendee, $extender)
Returns a new version of
$selectorwith$extendeeextended with$extender. - - (Sass::Script::Value::List) selector_nest($selectors...)
Return a new selector with all selectors in
$selectorsnested beneath one another as though they had been nested in the stylesheet as$selector1 { $selector2 { ... } }. - - (Sass::Script::Value::List) selector_parse($selector)
Parses a user-provided selector into a list of lists of strings as returned by
&. - - (Sass::Script::Value::List) selector_replace($selector, $original, $replacement)
Replaces all instances of
$originalwith$replacementin$selector. - - (Sass::Script::Value::List, Sass::Script::Value::Null) selector_unify($selector1, $selector2)
Unifies two selectors into a single selector that matches only elements matched by both input selectors.
- - (Sass::Script::Value::List) set
Return a new list, based on the list provided, but with the nth element changed to the value given.
- - (Sass::Script::Value::List) simple_selectors($selector)
Returns the simple selectors that comprise the compound selector
$selector. - - (Sass::Script::Value::Number, Sass::Script::Value::Null) str_index($string, $substring)
Returns the index of the first occurrence of
$substringin$string. - - (Sass::Script::Value::String) str_insert($string, $insert, $index)
Inserts
$insertinto$stringat$index. - - (Sass::Script::Value::Number) str_length($string)
Returns the number of characters in a string.
- - (Sass::Script::Value::String) str_slice($string, $start-at, $end-at:-1)
Extracts a substring from
$string. - - (Sass::Script::Value::String) to_lower_case($string)
Convert a string to lower case,.
- - (Sass::Script::Value::String) to_upper_case($string)
Converts a string to upper case.
- - (Sass::Script::Value::Color) transparentize($color, $amount) (also: #fade_out)
Makes a color more transparent.
- - (Sass::Script::Value::String) type_of($value)
Returns the type of a value.
- - (Sass::Script::Value::String) unique_id
Returns a unique CSS identifier.
- - (Sass::Script::Value::String) unit($number)
Returns the unit(s) associated with a number.
- - (Sass::Script::Value::Bool) unitless($number)
Returns whether a number has units.
- - (Sass::Script::Value::String) unquote($string)
Removes quotes from a string.
- - (Sass::Script::Value::Bool) variable_exists($name)
Check whether a variable with the given name exists in the current scope or in the global scope.
- - (Sass::Script::Value::List) zip($lists...)
Combines several lists into a single multidimensional list.
Class Method Details
+ declare(method_name, args, options = {})
Declare a Sass signature for a Ruby-defined function. This includes the names of the arguments, whether the function takes a variable number of arguments, and whether the function takes an arbitrary set of keyword arguments.
It's not necessary to declare a signature for a function. However, without a signature it won't support keyword arguments.
A single function can have multiple signatures declared as long as each one takes a different number of arguments. It's also possible to declare multiple signatures that all take the same number of arguments, but none of them but the first will be used unless the user uses keyword arguments.
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 416
def self.declare(method_name, args, options = {})
delayed_args = []
args = args.map do |a|
a = a.to_s
if a[0] == ?&
a = a[1..-1]
delayed_args << a
end
a
end
# We don't expose this functionality except to certain builtin methods.
if delayed_args.any? && method_name != :if
raise ArgumentError.new("Delayed arguments are not allowed for method #{method_name}")
end
@signatures[method_name] ||= []
@signatures[method_name] << Signature.new(
args,
delayed_args,
options[:var_args],
options[:var_kwargs],
options[:deprecated] && options[:deprecated].map {|a| a.to_s})
end |
+ (Random) random_number_generator
Get Sass's internal random number generator.
490 491 492 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 490
def self.random_number_generator
@random_number_generator ||= Random.new
end |
+ (Integer) random_seed=(seed)
Sets the random seed used by Sass's internal random number generator.
This can be used to ensure consistent random number sequences which allows for consistent results when testing, etc.
483 484 485 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 483
def self.random_seed=(seed)
@random_number_generator = Random.new(seed)
end |
+ ({Symbol => Object}?) signature(method_name, arg_arity, kwarg_arity)
Determine the correct signature for the number of arguments passed in for a given function. If no signatures match, the first signature is returned for error messaging.
450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 450
def self.signature(method_name, arg_arity, kwarg_arity)
return unless @signatures[method_name]
@signatures[method_name].each do |signature|
sig_arity = signature.args.size
return signature if sig_arity == arg_arity + kwarg_arity
next unless sig_arity < arg_arity + kwarg_arity
# We have enough args.
# Now we need to figure out which args are varargs
# and if the signature allows them.
t_arg_arity, t_kwarg_arity = arg_arity, kwarg_arity
if sig_arity > t_arg_arity
# we transfer some kwargs arity to args arity
# if it does not have enough args -- assuming the names will work out.
t_kwarg_arity -= (sig_arity - t_arg_arity)
t_arg_arity = sig_arity
end
if (t_arg_arity == sig_arity || t_arg_arity > sig_arity && signature.var_args) &&
(t_kwarg_arity == 0 || t_kwarg_arity > 0 && signature.var_kwargs)
return signature
end
end
@signatures[method_name].first
end |
Instance Method Details
- (Sass::Script::Value::Number) abs($number)
Returns the absolute value of a number.
1865 1866 1867 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1865
def abs(number)
numeric_transformation(number) {|n| n.abs}
end |
- (Sass::Script::Value::Color) adjust_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
Increases or decreases one or more properties of a color. This can change the red, green, blue, hue, saturation, value, and alpha properties. The properties are specified as keyword arguments, and are added to or subtracted from the color's current value for that property.
All properties are optional. You can't specify both RGB properties ($red, $green, $blue) and HSL properties ($hue, $saturation, $value) at the same time.
1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1147
def adjust_color(color, kwargs)
assert_type color, :Color, :color
with = Sass::Util.map_hash(
"red" => [-255..255, ""],
"green" => [-255..255, ""],
"blue" => [-255..255, ""],
"hue" => nil,
"saturation" => [-100..100, "%"],
"lightness" => [-100..100, "%"],
"alpha" => [-1..1, ""]
) do |name, (range, units)|
val = kwargs.delete(name)
next unless val
assert_type val, :Number, name
Sass::Util.check_range("$#{name}: Amount", range, val, units) if range
adjusted = color.send(name) + val.value
adjusted = [0, Sass::Util.restrict(adjusted, range)].max if range
[name.to_sym, adjusted]
end
unless kwargs.empty?
name, val = kwargs.to_a.first
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
end
color.with(with)
end |
- (Sass::Script::Value::Color) adjust_hue($color, $degrees)
Changes the hue of a color. Takes a color and a number of degrees (usually between -360deg and 360deg), and returns a color with the hue rotated along the color wheel by that amount.
1089 1090 1091 1092 1093 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1089
def adjust_hue(color, degrees)
assert_type color, :Color, :color
assert_type degrees, :Number, :degrees
color.with(:hue => color.hue + degrees.value)
end |
- (Sass::Script::Value::Number) alpha($color)
Returns the alpha component (opacity) of a color. This is 1 unless otherwise specified.
This function also supports the proprietary Microsoft alpha(opacity=20) syntax as a special case.
919 920 921 922 923 924 925 926 927 928 929 930 931 932 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 919
def alpha(*args)
if args.all? do |a|
a.is_a?(Sass::Script::Value::String) && a.type == :identifier &&
a.value =~ /^[a-zA-Z]+\s*=/
end
# Support the proprietary MS alpha() function
return identifier("alpha(#{args.map {|a| a.to_s}.join(', ')})")
end
raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1
assert_type args.first, :Color, :color
number(args.first.alpha)
end |
- (Sass::Script::Value::List) append($list, $val, $separator:auto)
Appends a single value onto the end of a list.
Unless the $separator argument is passed, if the list had only one item, the resulting list will be space-separated.
Like all list functions, append() returns a new list rather than modifying its argument in place.
2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2088
def append(list, val, separator = identifier("auto"))
assert_type separator, :String, :separator
unless %w(auto space comma).include?(separator.value)
raise ArgumentError.new("Separator name must be space, comma, or auto")
end
list.with_contents(list.to_a + [val],
separator:
if separator.value == 'auto'
list.separator || :space
else
separator.value.to_sym
end)
end |
- (Sass::Script::Value::Number) blue($color)
Gets the blue component of a color. Calculated from HSL where necessary via this algorithm.
849 850 851 852 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 849
def blue(color)
assert_type color, :Color, :color
number(color.blue)
end |
- call($function, $args...)
Dynamically calls a function. This can call user-defined functions, built-in functions, or plain CSS functions. It will pass along all arguments, including keyword arguments, to the called function.
2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2370
def call(name, *args)
unless name.is_a?(Sass::Script::Value::String) ||
name.is_a?(Sass::Script::Value::Function)
assert_type name, :Function, :function
end
if name.is_a?(Sass::Script::Value::String)
name = if function_exists(name).to_bool
get_function(name)
else
get_function(name, "css" => bool(true))
end
Sass::Util.sass_warn(<<WARNING)
DEPRECATION WARNING: Passing a string to call() is deprecated and will be illegal
in Sass 4.0. Use call(#{name.to_sass}) instead.
WARNING
end
kwargs = args.last.is_a?(Hash) ? args.pop : {}
funcall = Sass::Script::Tree::Funcall.new(
name.value,
args.map {|a| Sass::Script::Tree::Literal.new(a)},
Sass::Util.map_vals(kwargs) {|v| Sass::Script::Tree::Literal.new(v)},
nil,
nil)
funcall.line = environment.stack.frames.last.line
funcall.filename = environment.stack.frames.last.filename
funcall.options = options
perform(funcall)
end |
- (Sass::Script::Value::Number) ceil($number)
Rounds a number up to the next whole number.
1837 1838 1839 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1837
def ceil(number)
numeric_transformation(number) {|n| n.ceil}
end |
- (Sass::Script::Value::Color) change_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha])
Changes one or more properties of a color. This can change the red, green, blue, hue, saturation, value, and alpha properties. The properties are specified as keyword arguments, and replace the color's current value for that property.
All properties are optional. You can't specify both RGB properties ($red, $green, $blue) and HSL properties ($hue, $saturation, $value) at the same time.
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1279
def change_color(color, kwargs)
assert_type color, :Color, :color
with = Sass::Util.map_hash(
'red' => ['Red value', 0..255],
'green' => ['Green value', 0..255],
'blue' => ['Blue value', 0..255],
'hue' => [],
'saturation' => ['Saturation', 0..100, '%'],
'lightness' => ['Lightness', 0..100, '%'],
'alpha' => ['Alpha channel', 0..1]
) do |name, (desc, range, unit)|
val = kwargs.delete(name)
next unless val
assert_type val, :Number, name
if range
val = Sass::Util.check_range(desc, range, val, unit)
else
val = val.value
end
[name.to_sym, val]
end
unless kwargs.empty?
name, val = kwargs.to_a.first
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
end
color.with(with)
end |
- (Sass::Script::Value::Bool) comparable($number1, $number2)
Returns whether two numbers can added, subtracted, or compared.
1790 1791 1792 1793 1794 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1790
def comparable(number1, number2)
assert_type number1, :Number, :number1
assert_type number2, :Number, :number2
bool(number1.comparable_to?(number2))
end |
- (Sass::Script::Value::Color) complement($color)
Returns the complement of a color. This is identical to adjust-hue(color, 180deg).
1398 1399 1400 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1398
def complement(color)
adjust_hue color, number(180)
end |
- (Sass::Script::Value::Bool) content_exists
Check whether a mixin was passed a content block.
Unless content-exists() is called directly from a mixin, an error will be raised.
2525 2526 2527 2528 2529 2530 2531 2532 2533 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2525
def content_exists
# frames.last is the stack frame for this function,
# so we use frames[-2] to get the frame before that.
mixin_frame = environment.stack.frames[-2]
unless mixin_frame && mixin_frame.type == :mixin
raise Sass::SyntaxError.new("Cannot call content-exists() except within a mixin.")
end
bool(!environment.caller.content.nil?)
end |
- (Sass::Script::Value::String) counter($args...)
This function only exists as a workaround for IE7's content: counter bug. It works identically to any other plain-CSS function, except it avoids adding spaces between the argument commas.
2409 2410 2411 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2409
def counter(*args)
identifier("counter(#{args.map {|a| a.to_s(options)}.join(',')})")
end |
- (Sass::Script::Value::String) counters($args...)
This function only exists as a workaround for IE7's content: counter bug. It works identically to any other plain-CSS function, except it avoids adding spaces between the argument commas.
2423 2424 2425 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2423
def counters(*args)
identifier("counters(#{args.map {|a| a.to_s(options)}.join(',')})")
end |
- (Sass::Script::Value::Color) darken($color, $amount)
Makes a color darker. Takes a color and a number between 0% and 100%, and returns a color with the lightness decreased by that amount.
1028 1029 1030 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1028
def darken(color, amount)
_adjust(color, amount, :lightness, 0..100, :-, "%")
end |
- (Sass::Script::Value::Color) desaturate($color, $amount)
Makes a color less saturated. Takes a color and a number between 0% and 100%, and returns a color with the saturation decreased by that value.
1070 1071 1072 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1070
def desaturate(color, amount)
_adjust(color, amount, :saturation, 0..100, :-, "%")
end |
- (Sass::Script::Value::Bool) feature_exists($feature)
Returns whether a feature exists in the current Sass runtime.
The following features are supported:
global-variable-shadowingindicates that a local variable will shadow a global variable unless!globalis used.extend-selector-pseudoclassindicates that@extendwill reach into selector pseudoclasses like:not.units-level-3indicates full support for unit arithmetic using units defined in the Values and Units Level 3 spec.at-errorindicates that the Sass@errordirective is supported.custom-propertyindicates that the Custom Properties Level 1 spec is supported. This means that custom properties are parsed statically, with only interpolation treated as SassScript.
1689 1690 1691 1692 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1689
def feature_exists(feature)
assert_type feature, :String, :feature
bool(Sass.has_feature?(feature.value))
end |
- (Sass::Script::Value::Number) floor($number)
Rounds a number down to the previous whole number.
1851 1852 1853 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1851
def floor(number)
numeric_transformation(number) {|n| n.floor}
end |
- (Sass::Script::Value::Bool) function_exists($name)
Check whether a function with the given name exists.
2485 2486 2487 2488 2489 2490 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2485
def function_exists(name)
assert_type name, :String, :name
exists = Sass::Script::Functions.callable?(name.value.tr("-", "_"))
exists ||= environment.caller.function(name.value)
bool(exists)
end |
- (Sass::Script::Value::Function) get_function($name, $css:false)
Returns a reference to a function for later invocation with the call() function.
If $css is false, the function reference may refer to a function defined in your stylesheet or built-in to the host environment. If it's true it will refer to a plain-CSS function.
1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1712
def get_function(name, kwargs = {})
assert_type name, :String, :name
css = if kwargs.has_key?("css")
v = kwargs.delete("css")
assert_type v, :Bool, :css
v.value
else
false
end
if kwargs.any?
raise ArgumentError.new("Illegal keyword argument '#{kwargs.keys.first}'")
end
if css
return Sass::Script::Value::Function.new(
Sass::Callable.new(name.value, nil, nil, nil, nil, nil, "function", :css))
end
callable = environment.caller.function(name.value) ||
(Sass::Script::Functions.callable?(name.value.tr("-", "_")) &&
Sass::Callable.new(name.value, nil, nil, nil, nil, nil, "function", :builtin))
if callable
Sass::Script::Value::Function.new(callable)
else
raise Sass::SyntaxError.new("Function not found: #{name}")
end
end |
- (Sass::Script::Value::Bool) global_variable_exists($name)
Check whether a variable with the given name exists in the global scope (at the top level of the file).
2467 2468 2469 2470 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2467
def global_variable_exists(name)
assert_type name, :String, :name
bool(environment.global_env.var(name.value))
end |
- (Sass::Script::Value::Color) grayscale($color)
Converts a color to grayscale. This is identical to desaturate(color, 100%).
1382 1383 1384 1385 1386 1387 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1382
def grayscale(color)
if color.is_a?(Sass::Script::Value::Number)
return identifier("grayscale(#{color})")
end
desaturate color, number(100)
end |
- (Sass::Script::Value::Number) green($color)
Gets the green component of a color. Calculated from HSL where necessary via this algorithm.
833 834 835 836 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 833
def green(color)
assert_type color, :Color, :color
number(color.green)
end |
- (Sass::Script::Value::Color) hsl($hue, $saturation, $lightness)
756 757 758 759 760 761 762 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 756
def hsl(hue, saturation, lightness)
if special_number?(hue) || special_number?(saturation) || special_number?(lightness)
unquoted_string("hsl(#{hue}, #{saturation}, #{lightness})")
else
hsla(hue, saturation, lightness, number(1))
end
end |
- (Sass::Script::Value::Color) hsla($hue, $saturation, $lightness, $alpha)
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 784
def hsla(hue, saturation, lightness, alpha)
if special_number?(hue) || special_number?(saturation) ||
special_number?(lightness) || special_number?(alpha)
return unquoted_string("hsla(#{hue}, #{saturation}, #{lightness}, #{alpha})")
end
assert_type hue, :Number, :hue
assert_type saturation, :Number, :saturation
assert_type lightness, :Number, :lightness
assert_type alpha, :Number, :alpha
check_alpha_unit alpha, 'hsla'
h = hue.value
s = saturation.value
l = lightness.value
# Don't store the string representation for function-created colors, both
# because it's not very useful and because some functions aren't supported
# on older browsers.
Sass::Script::Value::Color.new(
:hue => h, :saturation => s, :lightness => l, :alpha => alpha.value)
end |
- (Sass::Script::Value::Number) hue($color)
Returns the hue component of a color. See the CSS3 HSL specification. Calculated from RGB where necessary via this algorithm.
867 868 869 870 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 867
def hue(color)
assert_type color, :Color, :color
number(color.hue, "deg")
end |
- (Sass::Script::Value::String) ie_hex_str($color)
Converts a color into the format understood by IE filters.
1107 1108 1109 1110 1111 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1107
def ie_hex_str(color)
assert_type color, :Color, :color
alpha = Sass::Util.round(color.alpha * 255).to_s(16).rjust(2, '0')
identifier("##{alpha}#{color.send(:hex_str)[1..-1]}".upcase)
end |
- (Sass::Script::Value::Base) if($condition, $if-true, $if-false)
Returns one of two values, depending on whether or not $condition is true. Just like in @if, all values other than false and null are considered to be true.
2331 2332 2333 2334 2335 2336 2337 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2331
def if(condition, if_true, if_false)
if condition.to_bool
perform(if_true)
else
perform(if_false)
end
end |
- (Sass::Script::Value::Number, Sass::Script::Value::Null) index($list, $value)
Returns the position of a value within a list. If the value isn't found, returns null instead.
Note that unlike some languages, the first item in a Sass list is number 1, the second number 2, and so forth.
This can return the position of a pair in a map as well.
2150 2151 2152 2153 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2150
def index(list, value)
index = list.to_a.index {|e| e.eq(value).to_bool}
index ? number(index + 1) : null
end |
- (Sass::Script::Value::String) inspect($value)
Return a string containing the value as its Sass representation.
2542 2543 2544 2545 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2542
def inspect(value)
value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String)
unquoted_string(value.to_sass)
end |
- (Sass::Script::Value::Color) invert($color) - (Sass::Script::Value::Color) invert($color, $weight:100%)
Returns the inverse (negative) of a color. The red, green, and blue values are inverted, while the opacity is left alone.
1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1415
def invert(color, weight = number(100))
if color.is_a?(Sass::Script::Value::Number)
return identifier("invert(#{color})")
end
assert_type color, :Color, :color
inv = color.with(
:red => (255 - color.red),
:green => (255 - color.green),
:blue => (255 - color.blue))
mix(inv, color, weight)
end |
- (Sass::Script::Value::Bool) is_bracketed($list)
Returns whether a list uses square brackets.
2179 2180 2181 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2179
def is_bracketed(list)
bool(list.bracketed)
end |
- (Sass::Script::Value::Bool) is_superselector($super, $sub)
Returns whether $super is a superselector of $sub. This means that $super matches all the elements that $sub matches, as well as possibly additional elements. In general, simpler selectors tend to be superselectors of more complex oned.
2840 2841 2842 2843 2844 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2840
def is_superselector(sup, sub)
sup = parse_selector(sup, :super)
sub = parse_selector(sub, :sub)
bool(sup.superselector?(sub))
end |
- (Sass::Script::Value::List) join($list1, $list2, $separator:auto, $bracketed:auto)
Joins together two lists into one.
Unless $separator is passed, if one list is comma-separated and one is space-separated, the first parameter's separator is used for the resulting list. If both lists have fewer than two items, spaces are used for the resulting list.
Unless $bracketed is passed, the resulting list is bracketed if the first parameter is.
Like all list functions, join() returns a new list rather than modifying its arguments in place.
2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2012
def join(list1, list2,
separator = identifier("auto"), bracketed = identifier("auto"),
kwargs = nil, *rest)
# rubocop:enable ParameterLists
if separator.is_a?(Hash)
kwargs = separator
separator = identifier("auto")
elsif bracketed.is_a?(Hash)
kwargs = bracketed
bracketed = identifier("auto")
elsif rest.last.is_a?(Hash)
rest.unshift kwargs
kwargs = rest.pop
end
unless rest.empty?
# Add 4 to rest.length because we don't want to count the kwargs hash,
# which is always passed.
raise ArgumentError.new("wrong number of arguments (#{rest.length + 4} for 2..4)")
end
if kwargs
separator = kwargs.delete("separator") || separator
bracketed = kwargs.delete("bracketed") || bracketed
unless kwargs.empty?
name, val = kwargs.to_a.first
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
end
end
assert_type separator, :String, :separator
unless %w(auto space comma).include?(separator.value)
raise ArgumentError.new("Separator name must be space, comma, or auto")
end
list(list1.to_a + list2.to_a,
separator:
if separator.value == 'auto'
list1.separator || list2.separator || :space
else
separator.value.to_sym
end,
bracketed:
if bracketed.is_a?(Sass::Script::Value::String) && bracketed.value == 'auto'
list1.bracketed
else
bracketed.to_bool
end)
end |
- (Sass::Script::Value::Map) keywords($args)
Returns the map of named arguments passed to a function or mixin that takes a variable argument list. The argument names are strings, and they do not contain the leading $.
2312 2313 2314 2315 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2312
def keywords(args)
assert_type args, :ArgList, :args
map(Sass::Util.map_keys(args.keywords.as_stored) {|k| Sass::Script::Value::String.new(k)})
end |
- (Sass::Script::Value::Number) length($list)
Return the length of a list.
This can return the number of pairs in a map as well.
1915 1916 1917 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1915
def length(list)
number(list.to_a.size)
end |
- (Sass::Script::Value::Color) lighten($color, $amount)
Makes a color lighter. Takes a color and a number between 0% and 100%, and returns a color with the lightness increased by that amount.
1009 1010 1011 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1009
def lighten(color, amount)
_adjust(color, amount, :lightness, 0..100, :+, "%")
end |
- (Sass::Script::Value::Number) lightness($color)
Returns the lightness component of a color. See the CSS3 HSL specification. Calculated from RGB where necessary via this algorithm.
903 904 905 906 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 903
def lightness(color)
assert_type color, :Color, :color
number(color.lightness, "%")
end |
- (Sass::Script::Value::String) list_separator($list)
Returns the separator of a list. If the list doesn't have a separator due to having fewer than two elements, returns space.
2166 2167 2168 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2166
def list_separator(list)
identifier((list.separator || :space).to_s)
end |
- (Sass::Script::Value::Base) map_get($map, $key)
Returns the value in a map associated with the given key. If the map doesn't have such a key, returns null.
2197 2198 2199 2200 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2197
def map_get(map, key)
assert_type map, :Map, :map
map.to_h[key] || null
end |
- (Sass::Script::Value::Bool) map_has_key($map, $key)
Returns whether a map has a value associated with a given key.
2292 2293 2294 2295 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2292
def map_has_key(map, key)
assert_type map, :Map, :map
bool(map.to_h.has_key?(key))
end |
- (List) map_keys($map)
Returns a list of all keys in a map.
2260 2261 2262 2263 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2260
def map_keys(map)
assert_type map, :Map, :map
list(map.to_h.keys, :comma)
end |
- (Sass::Script::Value::Map) map_merge($map1, $map2)
Merges two maps together into a new map. Keys in $map2 will take precedence over keys in $map1.
This is the best way to add new values to a map.
All keys in the returned map that also appear in $map1 will have the same order as in $map1. New keys from $map2 will be placed at the end of the map.
Like all map functions, map-merge() returns a new map rather than modifying its arguments in place.
2223 2224 2225 2226 2227 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2223
def map_merge(map1, map2)
assert_type map1, :Map, :map1
assert_type map2, :Map, :map2
map(map1.to_h.merge(map2.to_h))
end |
- (Sass::Script::Value::Map) map_remove($map, $keys...)
Returns a new map with keys removed.
Like all map functions, map-merge() returns a new map rather than modifying its arguments in place.
2244 2245 2246 2247 2248 2249 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2244
def map_remove(map, *keys)
assert_type map, :Map, :map
hash = map.to_h.dup
hash.delete_if {|key, _| keys.include?(key)}
map(hash)
end |
- (List) map_values($map)
Returns a list of all values in a map. This list may include duplicate values, if multiple keys have the same value.
2276 2277 2278 2279 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2276
def map_values(map)
assert_type map, :Map, :map
list(map.to_h.values, :comma)
end |
- (Sass::Script::Value::Number) max($numbers...)
Finds the maximum of several numbers. This function takes any number of arguments.
1898 1899 1900 1901 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1898
def max(*values)
values.each {|v| assert_type v, :Number}
values.inject {|max, val| max.gt(val).to_bool ? max : val}
end |
- (Sass::Script::Value::Number) min($numbers...)
Finds the minimum of several numbers. This function takes any number of arguments.
1881 1882 1883 1884 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1881
def min(*numbers)
numbers.each {|n| assert_type n, :Number}
numbers.inject {|min, num| min.lt(num).to_bool ? min : num}
end |
- (Sass::Script::Value::Color) mix($color1, $color2, $weight:50%)
Mixes two colors together. Specifically, takes the average of each of the RGB components, optionally weighted by the given percentage. The opacity of the colors is also considered when weighting the components.
The weight specifies the amount of the first color that should be included in the returned color. The default, 50%, means that half the first color and half the second color should be used. 25% means that a quarter of the first color and three quarters of the second color should be used.
1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1334
def mix(color1, color2, weight = number(50))
assert_type color1, :Color, :color1
assert_type color2, :Color, :color2
assert_type weight, :Number, :weight
Sass::Util.check_range("Weight", 0..100, weight, '%')
# This algorithm factors in both the user-provided weight (w) and the
# difference between the alpha values of the two colors (a) to decide how
# to perform the weighted average of the two RGB values.
#
# It works by first normalizing both parameters to be within [-1, 1],
# where 1 indicates "only use color1", -1 indicates "only use color2", and
# all values in between indicated a proportionately weighted average.
#
# Once we have the normalized variables w and a, we apply the formula
# (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color1.
# This formula has two especially nice properties:
#
# * When either w or a are -1 or 1, the combined weight is also that number
# (cases where w * a == -1 are undefined, and handled as a special case).
#
# * When a is 0, the combined weight is w, and vice versa.
#
# Finally, the weight of color1 is renormalized to be within [0, 1]
# and the weight of color2 is given by 1 minus the weight of color1.
p = (weight.value / 100.0).to_f
w = p * 2 - 1
a = color1.alpha - color2.alpha
w1 = ((w * a == -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0
w2 = 1 - w1
rgba = color1.rgb.zip(color2.rgb).map {|v1, v2| v1 * w1 + v2 * w2}
rgba << color1.alpha * p + color2.alpha * (1 - p)
rgb_color(*rgba)
end |
- (Sass::Script::Value::Bool) mixin_exists($name)
Check whether a mixin with the given name exists.
2505 2506 2507 2508 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2505
def mixin_exists(name)
assert_type name, :String, :name
bool(environment.mixin(name.value))
end |
- (Sass::Script::Value::Base) nth($list, $n)
Gets the nth item in a list.
Note that unlike some languages, the first item in a Sass list is number 1, the second number 2, and so forth.
This can return the nth pair in a map as well.
Negative index values address elements in reverse order, starting with the last element in the list.
1971 1972 1973 1974 1975 1976 1977 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1971
def nth(list, n)
assert_type n, :Number, :n
Sass::Script::Value::List.assert_valid_index(list, n)
index = n.to_i > 0 ? n.to_i - 1 : n.to_i
list.to_a[index]
end |
- (Sass::Script::Value::Color) opacify($color, $amount) Also known as: fade_in
Makes a color more opaque. Takes a color and a number between 0 and 1, and returns a color with the opacity increased by that amount.
965 966 967 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 965
def opacify(color, amount)
_adjust(color, amount, :alpha, 0..1, :+)
end |
- (Sass::Script::Value::Number) opacity($color)
Returns the alpha component (opacity) of a color. This is 1 unless otherwise specified.
942 943 944 945 946 947 948 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 942
def opacity(color)
if color.is_a?(Sass::Script::Value::Number)
return identifier("opacity(#{color})")
end
assert_type color, :Color, :color
number(color.alpha)
end |
- (Sass::Script::Value::Number) percentage($number)
Converts a unitless number to a percentage.
1806 1807 1808 1809 1810 1811 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1806
def percentage(number)
unless number.is_a?(Sass::Script::Value::Number) && number.unitless?
raise ArgumentError.new("$number: #{number.inspect} is not a unitless number")
end
number(number.value * 100, '%')
end |
- (Sass::Script::Value::String) quote($string)
Add quotes to a string if the string isn't quoted, or returns the same string if it is.
1478 1479 1480 1481 1482 1483 1484 1485 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1478
def quote(string)
assert_type string, :String, :string
if string.type != :string
quoted_string(string.value)
else
string
end
end |
- (Sass::Script::Value::Number) random - (Sass::Script::Value::Number) random($limit)
2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2557
def random(limit = nil)
generator = Sass::Script::Functions.random_number_generator
if limit
assert_integer limit, "limit"
if limit.to_i < 1
raise ArgumentError.new("$limit #{limit} must be greater than or equal to 1")
end
number(1 + generator.rand(limit.to_i))
else
number(generator.rand)
end
end |
- (Sass::Script::Value::Number) red($color)
Gets the red component of a color. Calculated from HSL where necessary via this algorithm.
817 818 819 820 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 817
def red(color)
assert_type color, :Color, :color
number(color.red)
end |
- (Sass::Script::Value::Color) rgb($red, $green, $blue)
Creates a Color object from red, green, and blue values.
656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 656
def rgb(red, green, blue)
if special_number?(red) || special_number?(green) || special_number?(blue)
return unquoted_string("rgb(#{red}, #{green}, #{blue})")
end
assert_type red, :Number, :red
assert_type green, :Number, :green
assert_type blue, :Number, :blue
color_attrs = [red, green, blue].map do |c|
if c.is_unit?("%")
c.value * 255 / 100.0
elsif c.unitless?
c.value
else
raise ArgumentError.new("Expected #{c} to be unitless or have a unit of % but got #{c}")
end
end
# Don't store the string representation for function-created colors, both
# because it's not very useful and because some functions aren't supported
# on older browsers.
Sass::Script::Value::Color.new(color_attrs)
end |
- (Sass::Script::Value::Color) rgba($red, $green, $blue, $alpha) - (Sass::Script::Value::Color) rgba($color, $alpha)
Creates a Color from red, green, blue, and alpha values.
712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 712
def rgba(*args)
case args.size
when 2
color, alpha = args
assert_type color, :Color, :color
if special_number?(alpha)
unquoted_string("rgba(#{color.red}, #{color.green}, #{color.blue}, #{alpha})")
else
assert_type alpha, :Number, :alpha
check_alpha_unit alpha, 'rgba'
color.with(:alpha => alpha.value)
end
when 4
red, green, blue, alpha = args
if special_number?(red) || special_number?(green) ||
special_number?(blue) || special_number?(alpha)
unquoted_string("rgba(#{red}, #{green}, #{blue}, #{alpha})")
else
rgba(rgb(red, green, blue), alpha)
end
else
raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)")
end
end |
- (Sass::Script::Value::Number) round($number)
Rounds a number to the nearest whole number.
1823 1824 1825 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1823
def round(number)
numeric_transformation(number) {|n| Sass::Util.round(n)}
end |
- (Sass::Script::Value::Color) saturate($color, $amount)
Makes a color more saturated. Takes a color and a number between 0% and 100%, and returns a color with the saturation increased by that amount.
1047 1048 1049 1050 1051 1052 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1047
def saturate(color, amount = nil)
# Support the filter effects definition of saturate.
# https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html
return identifier("saturate(#{color})") if amount.nil?
_adjust(color, amount, :saturation, 0..100, :+, "%")
end |
- (Sass::Script::Value::Number) saturation($color)
Returns the saturation component of a color. See the CSS3 HSL specification. Calculated from RGB where necessary via this algorithm.
885 886 887 888 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 885
def saturation(color)
assert_type color, :Color, :color
number(color.saturation, "%")
end |
- (Sass::Script::Value::Color) scale_color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha])
Fluidly scales one or more properties of a color. Unlike adjust-color, which changes a color's properties by fixed amounts, scale-color fluidly changes them based on how high or low they already are. That means that lightening an already-light color with scale-color won't change the lightness much, but lightening a dark color by the same amount will change it more dramatically. This has the benefit of making scale-color($color, ...) have a similar effect regardless of what $color is.
For example, the lightness of a color can be anywhere between 0% and 100%. If scale-color($color, $lightness: 40%) is called, the resulting color's lightness will be 40% of the way between its original lightness and 100. If scale-color($color, $lightness: -40%) is called instead, the lightness will be 40% of the way between the original and 0.
This can change the red, green, blue, saturation, value, and alpha properties. The properties are specified as keyword arguments. All arguments should be percentages between 0% and 100%.
All properties are optional. You can't specify both RGB properties ($red, $green, $blue) and HSL properties ($saturation, $value) at the same time.
1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1215
def scale_color(color, kwargs)
assert_type color, :Color, :color
with = Sass::Util.map_hash(
"red" => 255,
"green" => 255,
"blue" => 255,
"saturation" => 100,
"lightness" => 100,
"alpha" => 1
) do |name, max|
val = kwargs.delete(name)
next unless val
assert_type val, :Number, name
assert_unit val, '%', name
Sass::Util.check_range("$#{name}: Amount", -100..100, val, '%')
current = color.send(name)
scale = val.value / 100.0
diff = scale > 0 ? max - current : current
[name.to_sym, current + diff * scale]
end
unless kwargs.empty?
name, val = kwargs.to_a.first
raise ArgumentError.new("Unknown argument $#{name} (#{val})")
end
color.with(with)
end |
- (Sass::Script::Value::List) selector_append($selectors...)
Return a new selector with all selectors in $selectors appended one another as though they had been nested in the stylesheet as $selector1 { &$selector2 { ... } }.
2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2641
def selector_append(*selectors)
if selectors.empty?
raise ArgumentError.new("$selectors: At least one selector must be passed")
end
selectors.map {|sel| parse_selector(sel, :selectors)}.inject do |parent, child|
child.members.each do |seq|
sseq = seq.members.first
unless sseq.is_a?(Sass::Selector::SimpleSequence)
raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"")
end
base = sseq.base
case base
when Sass::Selector::Universal
raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"")
when Sass::Selector::Element
unless base.namespace.nil?
raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"")
end
sseq.members[0] = Sass::Selector::Parent.new(base.name)
else
sseq.members.unshift Sass::Selector::Parent.new
end
end
child.resolve_parent_refs(parent)
end.to_sass_script
end |
- (Sass::Script::Value::List) selector_extend($selector, $extendee, $extender)
Returns a new version of $selector with $extendee extended with $extender. This works just like the result of
$selector { ... }
$extender { @extend $extendee }
2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2698
def selector_extend(selector, extendee, extender)
selector = parse_selector(selector, :selector)
extendee = parse_selector(extendee, :extendee)
extender = parse_selector(extender, :extender)
extends = Sass::Util::SubsetMap.new
begin
extender.populate_extends(extends, extendee, nil, [], true)
selector.do_extend(extends).to_sass_script
rescue Sass::SyntaxError => e
raise ArgumentError.new(e.to_s)
end
end |
- (Sass::Script::Value::List) selector_nest($selectors...)
Return a new selector with all selectors in $selectors nested beneath one another as though they had been nested in the stylesheet as $selector1 { $selector2 { ... } }.
Unlike most selector functions, selector-nest allows the parent selector & to be used in any selector but the first.
2611 2612 2613 2614 2615 2616 2617 2618 2619 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2611
def selector_nest(*selectors)
if selectors.empty?
raise ArgumentError.new("$selectors: At least one selector must be passed")
end
parsed = [parse_selector(selectors.first, :selectors)]
parsed += selectors[1..-1].map {|sel| parse_selector(sel, :selectors, true)}
parsed.inject {|result, child| child.resolve_parent_refs(result)}.to_sass_script
end |
- (Sass::Script::Value::List) selector_parse($selector)
Parses a user-provided selector into a list of lists of strings as returned by &.
2585 2586 2587 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2585
def selector_parse(selector)
parse_selector(selector, :selector).to_sass_script
end |
- (Sass::Script::Value::List) selector_replace($selector, $original, $replacement)
Replaces all instances of $original with $replacement in $selector
This works by using @extend and throwing away the original selector. This means that it can be used to do very advanced replacements; see the examples below.
2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2741
def selector_replace(selector, original, replacement)
selector = parse_selector(selector, :selector)
original = parse_selector(original, :original)
replacement = parse_selector(replacement, :replacement)
extends = Sass::Util::SubsetMap.new
begin
replacement.populate_extends(extends, original, nil, [], true)
selector.do_extend(extends, [], true).to_sass_script
rescue Sass::SyntaxError => e
raise ArgumentError.new(e.to_s)
end
end |
- (Sass::Script::Value::List, Sass::Script::Value::Null) selector_unify($selector1, $selector2)
Unifies two selectors into a single selector that matches only elements matched by both input selectors. Returns null if there is no such selector.
Like the selector unification done for @extend, this doesn't guarantee that the output selector will match all elements matched by both input selectors. For example, if .a .b is unified with .x .y, .a .x .b.y, .x .a .b.y will be returned, but .a.x .b.y will not. This avoids exponential output size while matching all elements that are likely to exist in practice.
2787 2788 2789 2790 2791 2792 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2787
def selector_unify(selector1, selector2)
selector1 = parse_selector(selector1, :selector1)
selector2 = parse_selector(selector2, :selector2)
return null unless (unified = selector1.unify(selector2))
unified.to_sass_script
end |
- (Sass::Script::Value::List) set
Return a new list, based on the list provided, but with the nth element changed to the value given.
Note that unlike some languages, the first item in a Sass list is number 1, the second number 2, and so forth.
Negative index values address elements in reverse order, starting with the last element in the list.
1940 1941 1942 1943 1944 1945 1946 1947 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1940
def set_nth(list, n, value)
assert_type n, :Number, :n
Sass::Script::Value::List.assert_valid_index(list, n)
index = n.to_i > 0 ? n.to_i - 1 : n.to_i
new_list = list.to_a.dup
new_list[index] = value
list.with_contents(new_list)
end |
- (Sass::Script::Value::List) simple_selectors($selector)
Returns the simple selectors that comprise the compound selector $selector.
Note that $selector must be a compound selector. That means it cannot contain commas or spaces. It also means that unlike other selector functions, this takes only strings, not lists.
2814 2815 2816 2817 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2814
def simple_selectors(selector)
selector = parse_compound_selector(selector, :selector)
list(selector.members.map {|simple| unquoted_string(simple.to_s)}, :comma)
end |
- (Sass::Script::Value::Number, Sass::Script::Value::Null) str_index($string, $substring)
Returns the index of the first occurrence of $substring in $string. If there is no such occurrence, returns null.
Note that unlike some languages, the first character in a Sass string is number 1, the second number 2, and so forth.
1554 1555 1556 1557 1558 1559 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1554
def str_index(string, substring)
assert_type string, :String, :string
assert_type substring, :String, :substring
index = string.value.index(substring.value)
index ? number(index + 1) : null
end |
- (Sass::Script::Value::String) str_insert($string, $insert, $index)
Inserts $insert into $string at $index.
Note that unlike some languages, the first character in a Sass string is number 1, the second number 2, and so forth.
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1522
def str_insert(original, insert, index)
assert_type original, :String, :string
assert_type insert, :String, :insert
assert_integer index, :index
assert_unit index, nil, :index
insertion_point = if index.to_i > 0
[index.to_i - 1, original.value.size].min
else
[index.to_i, -original.value.size - 1].max
end
result = original.value.dup.insert(insertion_point, insert.value)
Sass::Script::Value::String.new(result, original.type)
end |
- (Sass::Script::Value::Number) str_length($string)
Returns the number of characters in a string.
1496 1497 1498 1499 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1496
def str_length(string)
assert_type string, :String, :string
number(string.value.size)
end |
- (Sass::Script::Value::String) str_slice($string, $start-at, $end-at:-1)
Extracts a substring from $string. The substring will begin at index $start-at and ends at index $end-at.
Note that unlike some languages, the first character in a Sass string is number 1, the second number 2, and so forth.
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1584
def str_slice(string, start_at, end_at = nil)
assert_type string, :String, :string
assert_unit start_at, nil, "start-at"
end_at = number(-1) if end_at.nil?
assert_unit end_at, nil, "end-at"
return Sass::Script::Value::String.new("", string.type) if end_at.value == 0
s = start_at.value > 0 ? start_at.value - 1 : start_at.value
e = end_at.value > 0 ? end_at.value - 1 : end_at.value
s = string.value.length + s if s < 0
s = 0 if s < 0
e = string.value.length + e if e < 0
return Sass::Script::Value::String.new("", string.type) if e < 0
extracted = string.value.slice(s..e)
Sass::Script::Value::String.new(extracted || "", string.type)
end |
- (Sass::Script::Value::String) to_lower_case($string)
Convert a string to lower case,
1628 1629 1630 1631 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1628
def to_lower_case(string)
assert_type string, :String, :string
Sass::Script::Value::String.new(Sass::Util.downcase(string.value), string.type)
end |
- (Sass::Script::Value::String) to_upper_case($string)
Converts a string to upper case.
1613 1614 1615 1616 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1613
def to_upper_case(string)
assert_type string, :String, :string
Sass::Script::Value::String.new(Sass::Util.upcase(string.value), string.type)
end |
- (Sass::Script::Value::Color) transparentize($color, $amount) Also known as: fade_out
Makes a color more transparent. Takes a color and a number between 0 and 1, and returns a color with the opacity decreased by that amount.
987 988 989 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 987
def transparentize(color, amount)
_adjust(color, amount, :alpha, 0..1, :-)
end |
- (Sass::Script::Value::String) type_of($value)
Returns the type of a value.
1652 1653 1654 1655 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1652
def type_of(value)
value.check_deprecated_interp if value.is_a?(Sass::Script::Value::String)
identifier(value.class.name.gsub(/Sass::Script::Value::/, '').downcase)
end |
- (Sass::Script::Value::String) unique_id
Returns a unique CSS identifier. The identifier is returned as an unquoted string. The identifier returned is only guaranteed to be unique within the scope of a single Sass run.
2346 2347 2348 2349 2350 2351 2352 2353 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2346
def unique_id
generator = Sass::Script::Functions.random_number_generator
Thread.current[:sass_last_unique_id] ||= generator.rand(36**8)
# avoid the temptation of trying to guess the next unique value.
value = (Thread.current[:sass_last_unique_id] += (generator.rand(10) + 1))
# the u makes this a legal identifier if it would otherwise start with a number.
identifier("u" + value.to_s(36).rjust(8, '0'))
end |
- (Sass::Script::Value::String) unit($number)
Returns the unit(s) associated with a number. Complex units are sorted in alphabetical order by numerator and denominator.
1758 1759 1760 1761 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1758
def unit(number)
assert_type number, :Number, :number
quoted_string(number.unit_str)
end |
- (Sass::Script::Value::Bool) unitless($number)
Returns whether a number has units.
1773 1774 1775 1776 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1773
def unitless(number)
assert_type number, :Number, :number
bool(number.unitless?)
end |
- (Sass::Script::Value::String) unquote($string)
Removes quotes from a string. If the string is already unquoted, this will return it unmodified.
1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 1442
def unquote(string)
unless string.is_a?(Sass::Script::Value::String)
# Don't warn multiple times for the same source line.
# rubocop:disable GlobalVars
$_sass_warned_for_unquote ||= Set.new
frame = environment.stack.frames.last
key = [frame.filename, frame.line] if frame
return string if frame && $_sass_warned_for_unquote.include?(key)
$_sass_warned_for_unquote << key if frame
# rubocop:enable GlobalVars
Sass::Util.sass_warn(<<MESSAGE.strip)
DEPRECATION WARNING: Passing #{string.to_sass}, a non-string value, to unquote()
will be an error in future versions of Sass.
#{environment.stack.to_s.gsub(/^/, ' ' * 8)}
MESSAGE
return string
end
string.check_deprecated_interp
return string if string.type == :identifier
identifier(string.value)
end |
- (Sass::Script::Value::Bool) variable_exists($name)
Check whether a variable with the given name exists in the current scope or in the global scope.
2443 2444 2445 2446 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2443
def variable_exists(name)
assert_type name, :String, :name
bool(environment.caller.var(name.value))
end |
- (Sass::Script::Value::List) zip($lists...)
Combines several lists into a single multidimensional list. The nth value of the resulting list is a space separated list of the source lists' nth values.
The length of the resulting list is the length of the shortest list.
2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 | # File '/home/nweiz/code/sass-site/.sass/lib/sass/script/functions.rb', line 2117
def zip(*lists)
length = nil
values = []
lists.each do |list|
array = list.to_a
values << array.dup
length = length.nil? ? array.length : [length, array.length].min
end
values.each do |value|
value.slice!(length)
end
new_list_value = values.first.zip(*values[1..-1])
list(new_list_value.map {|list| list(list, :space)}, :comma)
end |