Skip to content

Commit

Permalink
code 'color_to_rgb' filter
Browse files Browse the repository at this point in the history
  • Loading branch information
edadma committed May 6, 2018
1 parent 198edd1 commit a79952e
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 8 deletions.
2 changes: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ libraryDependencies ++= Seq(
"xyz.hyperreal" %% "lia" % "0.22.2",
"xyz.hyperreal" %% "json" % "0.7",
"xyz.hyperreal" %% "args" % "0.1",
"xyz.hyperreal" %% "hsl" % "0.2"
"xyz.hyperreal" %% "hsl" % "0.3.1"
)

coverageExcludedPackages := ".*Main;.*nil;.*package;.*Tag;.*Filter"
Expand Down
25 changes: 18 additions & 7 deletions src/main/scala/ExtraColorFilters.scala
Original file line number Diff line number Diff line change
@@ -1,25 +1,36 @@
//@
package xyz.hyperreal.liquescent

import xyz.hyperreal.hsl.HSL

object ExtraColorFilters {

val hslRegex = """hsl\(\s*(\d+)\s*,\s*(\d+)\s*%\s*,\s*(\d+)\s*%\s*\)"""r
val hslaRegex = """hsl\(\s*(\d+)\s*,\s*(\d+)\s*%\s*,\s*(\d+)\s*%\s*,\s*(\d+(?:\.\d*)?)\s*\)"""r
object ExtraColorFilters {

val map =
List(

new Filter( "color_to_rgb" ) {
val colorRegex = "#[0-9a-fA-F]{6}".r.pattern
val hslRegex = """hsl\(\s*(\d+)\s*,\s*(\d+)\s*%\s*,\s*(\d+)\s*%\s*\)"""r
val hslaRegex = """hsla\(\s*(\d+)\s*,\s*(\d+)\s*%\s*,\s*(\d+)\s*%\s*,\s*(\d+(?:\.\d*)?)\s*\)"""r
val colorRegex = "#([0-9a-fA-F]{6})".r

override def parameters = List( List(StringType) )

override def apply( interp: Interpreter, settings: Map[Symbol, Any], args: List[Any], named: Map[String, Any], locals: Map[String, Any] ) =
args match {
case List( s: String ) =>
if (colorRegex.matcher( s ).matches)
s drop 1 grouped 2 map (Integer.parseInt(_, 16)) mkString ("rgb(", ", ", ")")
case List( c: String ) =>
c match {
case hslRegex( h, s, l ) =>
val (r, g, b) = HSL( h.toDouble/360, s.toDouble/100, l.toDouble/100 ).toRGB

s"rgb($r, $g, $b)"
case hslaRegex( h, s, l, a ) =>
val (r, g, b) = HSL( h.toDouble/360, s.toDouble/100, l.toDouble/100 ).toRGB

s"rgba($r, $g, $b, $a)"
case colorRegex( h ) => h grouped 2 map (Integer.parseInt(_, 16)) mkString ("rgb(", ", ", ")")
case _ => sys.error( s"color doesn't match known format: $c" )
}
}
}

Expand Down
15 changes: 15 additions & 0 deletions src/test/scala/ExtraColorFilterTests.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//@
package xyz.hyperreal.liquescent

import org.scalatest._
import prop.PropertyChecks


class ExtraColorFilterTests extends FreeSpec with PropertyChecks with Matchers with Testing {

"color_to_rgb" in {
test( "{{ '#7ab55c' | color_to_rgb }}", true ) shouldBe "rgb(122, 181, 92)"
test( "{{ 'hsla(100, 38%, 54%, 0.5)' | color_to_rgb }}", true ) shouldBe "rgba(123, 182, 93, 0.5)"
}

}

0 comments on commit a79952e

Please sign in to comment.