Skip to content

Instantly share code, notes, and snippets.

@bookwyrm
Last active August 29, 2015 14:21
Show Gist options
  • Save bookwyrm/2b60270c2fbc00e4b21a to your computer and use it in GitHub Desktop.
Save bookwyrm/2b60270c2fbc00e4b21a to your computer and use it in GitHub Desktop.
Thoughts on “Useful Sass Snippets”
$color-stack:
(group: orange, id: normal, color: #e67835),
(group: orange, id: pale, color: #f8a878),
(group: orange, id: dark, color: #ad490c),
(group: blue, id: normal, color: #426682);
$color-stack:
(group: orange, shade: normal, color: #e67835),
(group: orange, shade: pale, color: #f8a878),
(group: orange, shade: dark, color: #ad490c),
(group: blue, shade: normal, color: #426682);
// Color Function
@function color($group, $shade:normal, $transparency:1, $color:null){
$_return: null;
$_color: null;
@each $c-color in $color-stack {
@if (type-of($c-color) == map) {
$c-group: map-get($c-color, group);
$c-shade: map-get($c-color, shade);
@if ($group == map-get($c-color, group) and $shade == map-get($c-color, shade) and $_color == null) {
$_color: map-get($c-color, color);
}
}
}
// If color was passed in
@if ($color != null) {
// If color was found
@if ($_color != null) {
// If colors don't match
@if ($_color != $color) {
@error "Found different color (#{$_color}) than color passed in (#{$color}) for given group (#{$group}) and shade (#{$shade})";
}
}
// No color was found
@else {
// See if color is defined but for different group and shade
$c-color: _color_stack_entry($color);
@if ($c-color != null) {
@error "Found color (#{$color}) already defined for different group (#{map-get($c-color, group)}) and shade (#{map-get($c-color, shade)}) than passed in group (#{$group}) and shade (#{$shade})";
}
// Add the new color
$c-color: (group: $group, shade: $shade, color: $color);
$color-stack: append($color-stack, $c-color, comma) !global;
$_color: $color;
}
}
@if ($_color == null) {
@error "No color found for given group (#{$group}) and shade (#{$shade})";
}
@return rgba($_color, $transparency);
}
// See if a color is already defined in our color stack
@function _color_stack_entry($color) {
$_return: null;
@each $cse in $color-stack {
@if ($_return == null) {
@if ($color == map-get($cse, color)) {
$_return: (group: map-get($cse, group), shade: map-get($cse, shade), color: $color);
}
}
}
@return $_return;
}
// https://github.com/ericam/true
@import "true";
@include test-module('Utilities') {
@include test('Color Stack Entry [function]') {
$test: _color_stack_entry(#fff);
$expect: null;
@include assert-equal($test, $expect, 'Unfound color returns null');
$test: _color_stack_entry(#ad490c);
$expect: (group: orange, shade: dark, color: #ad490c);
@include assert_equal($test, $expect, 'Found color return color stack entry');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment