Created
November 18, 2015 17:57
-
-
Save Debilski/590c724c14a7a826666c to your computer and use it in GitHub Desktop.
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
/* | |
Requires | |
libraryDependencies += "com.helger" % "ph-css" % "4.0.0" | |
Use in boot.scala: | |
(new CSSFixer).fixCSS("css" :: "styles" :: Nil, Full("/newRoot")) | |
*/ | |
package code.lib | |
import java.io.StringWriter | |
import com.helger.css.ECSSVersion | |
import com.helger.css.decl.visit.{AbstractModifyingCSSUrlVisitor, CSSVisitor} | |
import com.helger.css.reader.CSSReader | |
import com.helger.css.writer.CSSWriter | |
import net.liftweb.common.{Full, Box} | |
import net.liftweb.http._ | |
class CSSFixer { | |
def convertRoot(root: String, css: String): String = { | |
val cssDef = CSSReader.readFromString(css, ECSSVersion.CSS30) | |
CSSVisitor.visitCSSUrl(cssDef, new CSSURLFixer(root)) | |
val s = new StringWriter | |
val cssWriter = new CSSWriter(ECSSVersion.CSS30) | |
cssWriter.writeCSS(cssDef, s) | |
s.toString | |
} | |
def fixCSS(path: List[String], prefix: Box[String]) { | |
val liftReq: LiftRules.LiftRequestPF = new LiftRules.LiftRequestPF { | |
def functionName = "PH-CSS URL Fixer" | |
def isDefinedAt(r: Req): Boolean = { | |
r.path.partPath == path | |
} | |
def apply(r: Req): Boolean = { | |
r.path.partPath == path | |
} | |
} | |
val cssFixer: LiftRules.DispatchPF = new LiftRules.DispatchPF { | |
def functionName = "default css fixer" | |
def isDefinedAt(r: Req): Boolean = { | |
r.path.partPath == path | |
} | |
def apply(r: Req): () => Box[LiftResponse] = { | |
val cssPath = path.mkString("/", "/", ".css") | |
() => { | |
LiftRules.loadResourceAsString(cssPath) map { (css: String) => | |
CSSResponse(convertRoot(prefix openOr (S.contextPath), css)) | |
} | |
} | |
} | |
} | |
LiftRules.dispatch.prepend(cssFixer) | |
LiftRules.liftRequest.append(liftReq) | |
} | |
} | |
class CSSURLFixer(root: String) extends AbstractModifyingCSSUrlVisitor { | |
def getModifiedURI(s: String) = if (s.startsWith("/")) root + s else s | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment