Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/custom colors in interactions #420

Open
wants to merge 21 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 19 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,15 @@ class FileComponentLoader(paths: Seq[String], showNonReleased: Boolean)
}

private def loadCss(root: String): Option[String] = {
val maybeFiles = Seq("styles.less.min.css", "styles.less.css", "styles.css")
val maybeFiles = Seq("styles.css")

maybeFiles
.map(filename => readMaybeFile(new File(s"${if (root.endsWith("/")) root else s"$root/"}$filename")))
.find(!_.isEmpty).flatten
}

private def loadLess(root: String): Option[String] = {
val maybeFiles = Seq("styles.less")

maybeFiles
.map(filename => readMaybeFile(new File(s"${if (root.endsWith("/")) root else s"$root/"}$filename")))
Expand All @@ -108,6 +116,7 @@ class FileComponentLoader(paths: Seq[String], showNonReleased: Boolean)
loadLibrarySources(compRoot.getPath, "client", createClientName(compRoot.getName)),
loadLibrarySources(compRoot.getPath, "server", createServerName),
loadCss(s"${compRoot.getPath}/src/client"),
loadLess(s"${compRoot.getPath}/src/client"),
loadLibraries(packageJson)))
}

Expand All @@ -121,6 +130,7 @@ class FileComponentLoader(paths: Seq[String], showNonReleased: Boolean)
released = false,
client = loadLibrarySources(compRoot.getPath, "client", createClientName(compRoot.getPath)),
css = loadCss(s"${compRoot.getPath}/src/client"),
less = loadLess(s"${compRoot.getPath}/src/client"),
packageInfo = packageJson))
}

Expand Down Expand Up @@ -251,7 +261,8 @@ class FileComponentLoader(paths: Seq[String], showNonReleased: Boolean)
val renderJs = getJsFromFile(client.getPath + "/render")
val configureJs = getJsFromFile(client.getPath + "/configure")
val styleCss = loadCss(client.getPath)
Client(renderJs, configureJs, styleCss, renderLibs, configureLibs)
val styleLess = loadLess(client.getPath)
Client(renderJs, configureJs, styleCss, styleLess, renderLibs, configureLibs)
}

private def loadServer(server: File): Server = if (!server.exists()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background-color: red;
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ class FileComponentLoaderTest extends Specification {
lib.server.map(_.name).contains("corespring.my-lib.server") === true
lib.server.map(_.name).contains("corespring.my-lib.server.other") === true
lib.css.get.startsWith("body") mustEqual true
lib.less.get.startsWith("body") mustEqual true
}

"an interaction can specify a library" in {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ case class Library(
client: Seq[LibrarySource] = Seq.empty,
server: Seq[LibrarySource] = Seq.empty,
css: Option[String],
less: Option[String],
libraries: Seq[Id])
extends Component(Id(org, name), packageInfo)

Expand Down Expand Up @@ -75,12 +76,14 @@ case class LayoutComponent(org: String,
name: String,
client: Seq[LibrarySource],
css: Option[String],
less: Option[String],
released: Boolean,
override val packageInfo: JsValue) extends Component(Id(org, name), packageInfo)

case class Client(render: String,
configure: String,
css: Option[String],
less: Option[String],
renderLibs: Seq[LibrarySource] = Seq.empty,
configureLibs: Seq[LibrarySource] = Seq.empty)

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ trait ComponentMaker {
title = title,
titleGroup = titleGroup,
released = released,
client = Client("", "", None),
client = Client("", "", None, None),
server = Server(""),
packageInfo = Json.obj("name" -> name, "org" -> org),
defaultData = Json.obj(),
Expand All @@ -24,16 +24,16 @@ trait ComponentMaker {
}

def widget(name: String, libs: Seq[Id] = Seq.empty, title: Option[String] = None, titleGroup: Option[String] = None, org: String = defaultOrg) = {
Widget(org, name, title, titleGroup, Client("", "", None), true, Json.obj("name" -> name, "org" -> org),
Widget(org, name, title, titleGroup, Client("", "", None, None), true, Json.obj("name" -> name, "org" -> org),
Json.obj(), None, Map(), libs)
}

def lib(name: String, libraries: Seq[Id] = Seq.empty, org: String = defaultOrg): Library = {
Library(org, name, Json.obj("name" -> name), Seq.empty, Seq.empty, None, libraries)
Library(org, name, Json.obj("name" -> name), Seq.empty, Seq.empty, None, None, libraries)
}

def id(name: String, scope: Option[String] = None, org: String = defaultOrg) = Id(org, name, scope)

def layout(name: String, org: String = defaultOrg) = LayoutComponent(org, name, Seq.empty, None, true, Json.obj("name" -> name, "org" -> org))
def layout(name: String, org: String = defaultOrg) = LayoutComponent(org, name, Seq.empty, None, None, true, Json.obj("name" -> name, "org" -> org))

}
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package org.corespring.container.client

import javax.xml.bind.DatatypeConverter

import org.corespring.container.client.controllers.DefaultComponentSets
import org.corespring.container.client.processing.{ CssMinifier, Gzipper, JsMinifier }
import org.corespring.container.logging.ContainerLogger
import play.api.Configuration
import play.api.http.ContentTypes
import play.api.libs.json.{ JsObject, Json }
import play.api.mvc.{ Action, EssentialAction, RequestHeader, Result }

trait CompressedAndMinifiedComponentSets extends DefaultComponentSets
Expand Down Expand Up @@ -43,13 +46,32 @@ trait CompressedAndMinifiedComponentSets extends DefaultComponentSets
}
}

private def tokenToJson(token: String): JsObject = {
val decodedColorString = DatatypeConverter.parseBase64Binary(token).map(_.toChar).mkString
try {
Json.parse(decodedColorString).as[JsObject]
} catch {
case _ => Json.obj()
}
}

override def singleResource[A >: EssentialAction](context: String, componentType: String, suffix: String): A = Action { implicit request =>
val (body, ct) = generate(context, allComponents.find(_.matchesType(componentType)).toSeq, suffix)
val resourceToken = request.queryString.get("resourceToken")
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

duplication w/ line 69?

val paramsJson = resourceToken match {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

duplication? line 65?

case Some(token) if (token.length > 0) => tokenToJson(token(0))
case _ => Json.obj()
}
val (body, ct) = generate(context, allComponents.find(_.matchesType(componentType)).toSeq, suffix, paramsJson)
process(body, ct)
}

override def resource[A >: EssentialAction](context: String, directive: String, suffix: String) = Action { implicit request =>
val (body, ct) = generateBodyAndContentType(context, directive, suffix)
val resourceToken = request.queryString.get("resourceToken")
val paramsJson = resourceToken match {
case Some(token) if (token.length > 0) => tokenToJson(token(0))
case _ => Json.obj()
}
val (body, ct) = generateBodyAndContentType(context, directive, suffix, paramsJson)
process(body, ct)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import play.api.mvc.Controller

trait ComponentUrls {
def jsUrl(context: String, components: Seq[Component], separatePaths: Boolean): Seq[String]
def lessUrl(context: String, components: Seq[Component], separatePaths: Boolean, encodedCustomColors: Option[String]): Seq[String]
def cssUrl(context: String, components: Seq[Component], separatePaths: Boolean): Seq[String]
}

Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import org.corespring.container.client.views.txt.js.{ ComponentServerWrapper, Co
import org.corespring.container.components.model._
import org.corespring.container.components.model.dependencies.ComponentTypeFilter
import org.corespring.container.components.model.packaging.ClientSideDependency
import play.api.libs.json.JsObject
import play.api.libs.json.{ Json, JsValue, JsObject }
import org.apache.commons.io.IOUtils

object SourceGenerator {
object Keys {
Expand All @@ -26,6 +27,8 @@ trait SourceGenerator

def css(components: Seq[Component]): String

def less(components: Seq[Component], customColors: JsObject = Json.obj()): String

protected def wrapComponent(moduleName: String, directiveName: String, src: String) = {
ComponentWrapper(moduleName, directiveName, src).toString
}
Expand Down Expand Up @@ -119,6 +122,30 @@ abstract class BaseGenerator
""".stripMargin
}

override def less(components: Seq[Component], customColors: JsObject = Json.obj()): String = {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it alot of this is static content - try and isolate it and generate it once

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what do you mean?

val inputStream = this.getClass().getResourceAsStream("/public/components-common.less")
val commonLessSource = IOUtils.toString(inputStream)
inputStream.close
val commonLess = commonLessSource.mkString
val (libraries, uiComps, layoutComps, widgets) = splitComponents(components)
val uiLess = uiComps.map(_.client.less.getOrElse("")).mkString("\n")
val widgetLess = widgets.map(_.client.less.getOrElse("")).mkString("\n")
val layoutLess = layoutComps.map(_.less.getOrElse("")).mkString("\n")
val libraryLess = libraries.map(_.less.getOrElse("")).mkString("\n")
val dynamicColors = customColors.asOpt[Map[String, String]] match {
case Some(cols) => cols.map { case (a, b) => s"@$a: $b;" }.mkString("\n")
case _ => ""
}
s"""
|$commonLess
|$dynamicColors
|$uiLess
|$widgetLess
|$layoutLess
|$libraryLess
""".stripMargin
}

override def js(components: Seq[Component]): String = {
val (libs, uiComps, layoutComps, widgets) = splitComponents(components)
val uiJs = uiComps.map(interactionToJs).mkString("\n")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,15 @@ import org.corespring.container.components.model.dependencies.DependencyResolver
import org.corespring.container.logging.ContainerLogger
import play.api.http.ContentTypes
import play.api.mvc._
import org.lesscss.LessCompiler
import play.api.libs.json.{ JsObject, Json }

trait ComponentSets extends Controller with ComponentUrls {

private lazy val logger = ContainerLogger.getLogger("ComponentSets")

private val lessCompiler = new LessCompiler()

def allComponents: Seq[Component]

def playerGenerator: SourceGenerator
Expand All @@ -27,11 +31,14 @@ trait ComponentSets extends Controller with ComponentUrls {

def singleResource[A >: EssentialAction](context: String, componentType: String, suffix: String): A

protected final def generate(context: String, resolvedComponents: Seq[Component], suffix: String): (String, String) = {
protected final def generate(context: String, resolvedComponents: Seq[Component], suffix: String, parameters: JsObject = Json.obj()): (String, String) = {

def gen(generator: SourceGenerator): String = suffix match {
case "js" => generator.js(resolvedComponents)
case "css" => generator.css(resolvedComponents)
case "less" =>
val res = generator.less(resolvedComponents, (parameters \ "colors").asOpt[JsObject].getOrElse(Json.obj()))
lessCompiler.compile(res)
case _ => ""
}

Expand All @@ -46,43 +53,51 @@ trait ComponentSets extends Controller with ComponentUrls {
val contentType = suffix match {
case "js" => ContentTypes.JAVASCRIPT
case "css" => ContentTypes.CSS
case "less" => ContentTypes.CSS
case _ => throw new RuntimeException(s"Unknown suffix: $suffix")
}

(out, contentType)
}

protected final def generateBodyAndContentType(context: String, directive: String, suffix: String): (String, String) = {
protected final def generateBodyAndContentType(context: String, directive: String, suffix: String, parameters: JsObject = Json.obj()): (String, String) = {
val types: Seq[String] = ComponentUrlDirective(directive, allComponents)
val usedComponents = types.map { t => allComponents.find(_.componentType == t) }.flatten
val components = dependencyResolver.resolveComponents(usedComponents.map(_.id), Some(context))
logger.trace(s"context: $context, comps: ${components.map(_.componentType).mkString(",")}")
generate(context, components, suffix)
generate(context, components, suffix, parameters)
}

override def cssUrl(context: String, components: Seq[Component], separatePaths: Boolean): Seq[String] = url(context, components, "css", separatePaths)

override def jsUrl(context: String, components: Seq[Component], separatePaths: Boolean): Seq[String] = url(context, components, "js", separatePaths)
override def lessUrl(context: String, components: Seq[Component], separatePaths: Boolean, encodedCustomColors: Option[String]): Seq[String] = url(context, components, "less", separatePaths, encodedCustomColors)

private def url(context: String, components: Seq[Component], suffix: String, separatePaths: Boolean): Seq[String] = {
override def jsUrl(context: String, components: Seq[Component], separatePaths: Boolean): Seq[String] = url(context, components, "js", separatePaths)

private def url(context: String, components: Seq[Component], suffix: String, separatePaths: Boolean, resourceToken: Option[String] = None): Seq[String] = {
require(allComponents.length > 0, "Can't load components")

if (separatePaths) {
val resolvedComponents = dependencyResolver.resolveComponents(components.map(_.id), Some(context))
resolvedComponents.map { c => routes.ComponentSets.singleResource(context, c.componentType, suffix).url }
resolvedComponents.map { c =>
routes.ComponentSets.singleResource(context, c.componentType, suffix).url + (resourceToken match {
case Some(token) => s"?resourceToken=$token"
case None => ""
})
}
} else {
components match {
case Nil => Seq.empty
case _ => {
ComponentUrlDirective.unapply(components.map(_.componentType), allComponents).map { path =>
routes.ComponentSets.resource(context, path, suffix).url
routes.ComponentSets.resource(context, path, suffix).url + (resourceToken match {
case Some(token) => s"?resourceToken=$token"
case None => ""
})
}.toSeq
}
}

}

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import org.corespring.container.logging.ContainerLogger

import scala.concurrent._

case class ComponentScriptInfo(jsUrl: Seq[String], cssUrl: Seq[String], ngDependencies: Seq[String])
case class ComponentScriptInfo(jsUrl: Seq[String], cssUrl: Seq[String], lessUrl: Seq[String], ngDependencies: Seq[String])

trait HasLogger {
def logger: Logger
Expand Down Expand Up @@ -99,12 +99,17 @@ trait App[T]
js.distinct.map(resolvePath)
}

protected def buildCss(scriptInfo: ComponentScriptInfo)(implicit rh: RequestHeader) = {
val css = paths(cssSrc) ++ cssSrc.otherLibs ++ scriptInfo.cssUrl.toSeq
protected def buildLess(scriptInfo: ComponentScriptInfo)(implicit rh: RequestHeader) = {
val less = scriptInfo.lessUrl
less.map(resolvePath)
}

protected def buildCss(scriptInfo: ComponentScriptInfo, withComponents: Boolean = false)(implicit rh: RequestHeader) = {
val css = paths(cssSrc) ++ cssSrc.otherLibs ++ (if (withComponents) scriptInfo.cssUrl else Seq())
css.map(resolvePath)
}

protected def componentScriptInfo(components: Seq[String], separatePaths: Boolean): ComponentScriptInfo = {
protected def componentScriptInfo(components: Seq[String], separatePaths: Boolean, customColorsEncoded: Option[String] = None): ComponentScriptInfo = {

val typeIds = components.map {
t =>
Expand All @@ -116,9 +121,10 @@ trait App[T]
val resolvedComponents = resolveComponents(typeIds, Some(context))
val jsUrl = urls.jsUrl(context, resolvedComponents, separatePaths)
val cssUrl = urls.cssUrl(context, resolvedComponents, separatePaths)
val lessUrl = urls.lessUrl(context, resolvedComponents, separatePaths, customColorsEncoded)
val clientSideDependencies = getClientSideDependencies(resolvedComponents)
val dependencies = ngModules.createAngularModules(resolvedComponents, clientSideDependencies)
ComponentScriptInfo(jsUrl, cssUrl, dependencies)
ComponentScriptInfo(jsUrl, cssUrl, lessUrl, dependencies)
}

/** Allow external domains to be configured */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package org.corespring.container.client.controllers.apps

import org.corespring.container.client.component.AllItemTypesReader
import org.corespring.container.client.controllers.GetAsset
import org.corespring.container.client.controllers.helpers.QueryHelper
import org.corespring.container.client.controllers.jade.Jade
import org.corespring.container.client.hooks.{ LoadHook, CatalogHooks }
import org.corespring.container.client.hooks.Hooks.StatusMessage
Expand All @@ -15,7 +16,8 @@ trait Catalog
extends AllItemTypesReader
with App[CatalogHooks]
with Jade
with GetAsset[CatalogHooks] {
with GetAsset[CatalogHooks]
with QueryHelper {

override def context: String = "catalog"

Expand Down Expand Up @@ -47,10 +49,11 @@ trait Catalog

def ifEmpty = {
logger.trace(s"[showCatalog]: $id")

val serviceParams = queryParams(mapToJson)
val colors = (serviceParams \ "colors").asOpt[String].getOrElse("default")
val scriptInfo = componentScriptInfo(componentTypes(Json.obj()), jsMode == "dev")
val domainResolvedJs = buildJs(scriptInfo)
val domainResolvedCss = buildCss(scriptInfo)
val domainResolvedCss = buildCss(scriptInfo) ++ buildLess(scriptInfo)
Ok(
renderJade(
CatalogTemplateParams(
Expand Down
Loading