Last active
December 29, 2020 07:07
-
-
Save disco0/d4236516728ac3711a0772392017cffe to your computer and use it in GitHub Desktop.
Stylus - CSS Calc function wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Builds css calc function expression literal for css property value. | |
* Gives ability to drop in variables at the cost of escaping operators, or | |
* get both with format string | |
*/ | |
calc() | |
unless length(arguments) > 0 | |
error('Calc wrapper requires at least one syntax element in `arguments`.') | |
if length(arguments) == 1 and arguments[0] is a 'string' | |
return 'calc( %s )' % unquote(arguments[0]) | |
unless length(arguments) > 1 | |
error('Calc expression passed as idents must have more than 1 elements.') | |
$first = arguments[0] | |
$rest = slice(arguments, 1) | |
if $first is a 'string' | |
if length($rest) < 1 | |
return 'calc( %s )' % ( unquote($first) ) | |
else | |
return 'calc( %s )' % ( $first % ( $rest ) ) | |
$out = 'calc( ' + $first | |
for $arg in $rest | |
p('Current: %s', $arg) | |
$out = $out + ' ' + $arg | |
$out += ' )' | |
return unquote($out) | |
// Usage | |
// $CalcUsage = 1 | |
if $CalcUsage is defined | |
div | |
content: calc(50% \/ 200px) | |
// =>content: calc( 50% / 200px ); | |
content: calc(50% \/ 200px \+ calc(10vw \- 50%)) | |
// => content: calc( 50% / 200px + calc( 10vw - 50% ) ); | |
$var = 200px | |
content: calc(50% \/ $var \+ calc(10vw \- 50%)) | |
// => content: calc( 50% / 200px + calc( 10vw - 50% ) ); | |
// With calc expression tokens as rest args | |
content: calc(50%, \/, $var) | |
// => content: calc( 50% / 200px ); | |
content: calc('50% / 200px'); | |
// => content: calc( 50% / 200px ); | |
content: calc('%s / %s', 50%, 200px); | |
// => content: calc( 50% / 200px ); | |
// With format string expansions as rest args | |
content: calc('50% / 200px + %s', calc(10vw \- 50%)) | |
// => content: calc( 50% / 200px + calc( 10vw - 50% ) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment