Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save TheAppleFreak/888372c9b40b9a3c969b to your computer and use it in GitHub Desktop.
Save TheAppleFreak/888372c9b40b9a3c969b to your computer and use it in GitHub Desktop.
// Functions
// ===============================================================================
//
// There's some stuff that I need fine-grained control over. These
// functions give it to me in spades.
//
// The following are all third-party functions.
// color-contrast() and related courtesy of Lu Nelson
// http://codepen.io/lunelson/pen/jENxwB
// LINEAR to LOGARITHMIC and vice-versa
@function lin2log($n) {
@if $n <= 0.00313 {
@return $n * 12.92;
}
@else {
@return 1.055 * pow($n, 1 / 2.4) - 0.055;
}
}
@function log2lin($n) {
@if $n <= 0.04045 {
@return $n / 12.92;
}
@else {
@return pow(($n + 0.055) / 1.055, 2.4);
}
}
// sRGB BT-709 BRIGHTNESS
@function brightness($c) {
$rlin: log2lin(red($c) / 255);
$glin: log2lin(green($c) / 255);
$blin: log2lin(blue($c) / 255);
@return lin2log(0.2126 * $rlin + 0.7152 * $glin + 0.0722 * $blin) * 100;
}
// Compares contrast of a given color to the light/dark arguments and returns
// whichever is most "contrasty"
@function color-contrast($color,
$dark: $PLACEHOLDER-BLACK,
$light: $PLACEHOLDER-WHITE) {
@if $color == null {
@return null;
}
@else {
$color-brightness: brightness($color);
$text-light-brightness: brightness($light);
$text-dark-brightness: brightness($dark);
@return if(abs($color-brightness - $text-light-brightness) >
abs($color-brightness - $text-dark-brightness), $light, $dark);
}
}
// Function to retrieve value in nested map without a trillion map-gets
// Takes map as first arg, arglist as the second and beyond
@function map-get-nested($map, $keys...) {
@each $key in $keys {
$map: map-get($map, $key);
}
@return $map;
}
// Function to check if nested key exists.
// Takes map as first arg, arglist as the second and beyond
@function map-has-nested-key($map, $keys...) {
@each $key in $keys {
@if not map-has-key($map, $key) {
@return false;
}
$map: map-get($map, $key);
}
@return true;
}
// Courtesy of http://hugogiraudel.com/2013/08/08/advanced-sass-list-functions/
@function remove($list, $value, $recursive: false) {
$result: ();
@for $i from 1 through length($list) {
@if type-of(nth($list, $i)) == list and $recursive {
$result: append($result, remove(nth($list, $i), $value, $recursive));
}
@else if nth($list, $i) != $value {
$result: append($result, nth($list, $i));
}
}
@return $result;
}
@function map-set($map, $key, $value) {
$new: ($key: $value);
@return map-merge($map, $new);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment