com-lihaoyi / scalatags Goto Github PK
View Code? Open in Web Editor NEWScalaTags is a small XML/HTML construction library for Scala.
Home Page: https://com-lihaoyi.github.io/scalatags/
License: MIT License
ScalaTags is a small XML/HTML construction library for Scala.
Home Page: https://com-lihaoyi.github.io/scalatags/
License: MIT License
Hi,
is the svg tags work ?
This:
import SvgTags.svg
import SvgStyles.stroke
svg(stroke:="blue")
returns
not found: value svg(
not found: value stroke := "blue"
Is the imports not correct ?
Thanks
Hi,
First off really cool stuff :)
But, if you change the TodoMVC example you have in another repo, to include two input fields.
The submit function won't be called.
form(
inputOne,
inputTwo,
onsubmit <~ {
println("Submit")
}
)
I have the following scalatags fragment :
html(
head(
meta(charset := "utf-8"),
meta(name := "viewport", content := "initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"),
htitle("some title"),
link(href := "lib/ionic/css/ionic.css", rel := "stylesheet"),
link(href := "css/style.css", rel := "stylesheet"),
// ionic/angularjs is included in the bundled jsdeps created by scala-js.
//See the webjar dependencies in the build.sbt to add more javascript dependencies
script(src := "js/scala-js-ionic-starter-application-tabs-jsdeps.js"),
// cordova script (this will be a 404 during development)
script(src := "cordova.js"),
// your app's js
script(src := "js/scala-js-ionic-starter-application-tabs" + jsOptNameSuffix),
script(`type` := "text/javascript")("com.olivergg.ristorantewatcher.RistoranteWatcherApp().main();")
),
body(ngApp := "starter", animation := "slide-left-right-ios7")(
ionNavBar(cls := "bar-stable bar-positive nav-title-slide-ios7")(ionNavBackButton(cls := "button-icon icon ion-ios7-arrow-back")("Back")),
/**
* The views will be rendered in the <ion-nav-view> directive below
* Templates are in the /templates folder (but you could also
* have templates inline in this html file if you'd like).
*/
ionNavView()
)
That generates the following output :
<html>
<head>
<meta charset="utf-8"/>
<meta content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width" name="viewport"/>
<title>some title</title>
<link rel="stylesheet" href="lib/ionic/css/ionic.css"/>
<link rel="stylesheet" href="css/style.css"/>
<script src="js/scala-js-ionic-starter-application-tabs-jsdeps.js"/>
<script src="cordova.js"/>
<script src="js/scala-js-ionic-starter-application-tabs-fastopt.js"/>
<script type="text/javascript">com.olivergg.ristorantewatcher.RistoranteWatcherApp().main();</script>
</head>
<body animation="slide-left-right-ios7" ng-app="starter">
<ion-nav-bar class="bar-stable bar-positive nav-title-slide-ios7">
<ion-nav-back-button class="button-icon icon ion-ios7-arrow-back">Back</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view/>
</body>
</html>
Unfortunately, the script tag does not work properly when not close with an explicit closing tag.
How would you make scalatags generate :
<script src="js/scala-js-ionic-starter-application-tabs-jsdeps.js"></script>
instead of
<script src="js/scala-js-ionic-starter-application-tabs-jsdeps.js"/>
Thansk ;)
To ensure that scalatags users benefit from scala-js/scala-js#1506 (and avoid symptoms seen in scala-js/scala-js#1514), scalatags needs to be republished for scalajs-0.6.1.
Hi,
Have you decided on a licence for scalatags? I see you've not yet added a LICENSE file in the repo root.
Please, publish ScalaTags 0.4.3 (that uses dom 0.7.1). Update of libs are blocked because of it (want to update with dom 0.7.1 first and only then - move to 0.8.0)
It would be nice to put in a URL or some other class that has an appropriate toString method without having to convert explicitly. (In my case, I do a reverse lookup in Play, and get back a Call object instead of a String. Works fine in src(...), but not in javascript(...).)
https://github.com/lihaoyi/scalatags#use-cases
When I try this example, I am getting ambiguous implicit errors
The imports for the example aren't listed, so I am assuming that its full form is:
import scalatags.JsDom._
import scalatags.JsDom.all._
val labelElem = label("Default").render
val inputElem = input(
`type`:="text",
onfocus := { () => labelElem.textContent = ""}
).render
val box = div(
inputElem,
labelElem
).render
println(labelElem.textContent) // "Default"
inputElem.onfocus(null)
println(labelElem.textContent) // ""
Which gives me the following error:
[error] /home/bjackman/cgta/orange/viz-sjs/src/main/scala/cgta/viz/pepper/PepperGrid.scala:33: type mismatch;
[error] found : org.scalajs.dom.HTMLInputElement
[error] required: scalatags.JsDom.Node
[error] (which expands to) scalatags.generic.Node[org.scalajs.dom.Element]
[error] Note that implicit conversions are not applicable because they are ambiguous:
[error] both method bindElement in trait LowPriorityImplicits of type (e: org.scalajs.dom.Element)scalatags.generic.Node[org.scalajs.dom.Element]
[error] and method NumericNode in object JsDom of type [T](u: T)(implicit evidence$1: Numeric[T])scalatags.JsDom.StringNode
[error] are possible conversion functions from org.scalajs.dom.HTMLInputElement to scalatags.JsDom.Node
[error] inputElem,
[error] ^
[error] /home/bjackman/cgta/orange/viz-sjs/src/main/scala/cgta/viz/pepper/PepperGrid.scala:34: type mismatch;
[error] found : org.scalajs.dom.HTMLLabelElement
[error] required: scalatags.JsDom.Node
[error] (which expands to) scalatags.generic.Node[org.scalajs.dom.Element]
[error] Note that implicit conversions are not applicable because they are ambiguous:
[error] both method bindElement in trait LowPriorityImplicits of type (e: org.scalajs.dom.Element)scalatags.generic.Node[org.scalajs.dom.Element]
[error] and method NumericNode in object JsDom of type [T](u: T)(implicit evidence$1: Numeric[T])scalatags.JsDom.StringNode
[error] are possible conversion functions from org.scalajs.dom.HTMLLabelElement to scalatags.JsDom.Node
[error] labelElem
[error] ^
[error] two errors found
It turns out that the entire list of every CSS declaration in existence is... pretty short:
It would be cool to define a CSS DSL to complement the HTML. This would comprise several parts:
This would be a lot of work, but would more-or-less replace the ad-hoc inline-css-as-methods system that exists now with something that can cover the whole CSS pipeline of definition to usage, which would be quite nice.
i want to achieve something like this
val dangerouslySetInnerHTML = "dangerouslySetInnerHTML".attr
val htmlObj : js.Object = js.Dynamic.literal("__html"" -> text)
div(dangerouslySetInnerHTML := htmlObj )
scala-js/scala-js#1149 I am not sure if it is scalajs issue or something is wrong with scalatags publishing
Re: https://groups.google.com/d/msg/play-framework/nhjp4wIx7jo/SfynW3Zsz44J
Hi, I came across your repository yesterday after hearing about scala.js announcement. Needless to say, ScalaTags is very impressive and only lags twirl in the form functionality.
I quickly hacked together https://gist.github.com/SRGOM/9a711b56d37d0ae60dc5 to replicate that functionality. It's most code copying. It works fine for the cases I tried. Before I think about making it production ready* I wanted to check with you if you will be accepting pull request.
Disclaimer: I might be completely wrong about a lot of things because my experience with scalatags is 20 lines + this code. Wanted to mention this because I don't want to waste your time.
*production ready =>
Please let me know if this plan makes sense. Thanks.
This doesn't work
import scalatags.Text.all._
val thing: Tag = div
It should.
Is it possible to avoid fusing style-related attributes into one combined style
attribute short of using .attr
for each?
scala> import scalatags.Text.all._
import scalatags.Text.all._
scala> img(src := "foo", width := 10, height := 10)
res0: scalatags.Text.TypedTag[Nothing] = <img src="foo" style="width: 10;height: 10;" />
scala> img(src := "foo", "width".attr := 10, "height".attr := 10)
res1: scalatags.Text.TypedTag[Nothing] = <img src="foo" width="10" height="10" />
Is there a way to influence scalatags so that I can get res1
with code like img(src := "foo", width := 10, height := 10)
, perhaps by configuring the bundles?
FYI:
https://github.com/sbt/sbt.github.com/blob/gen-master/src/jekyll/using_sonatype.md
I would like to use ScalaTags in Xitrum:
http://ngocdaothanh.github.io/xitrum/
When using source maps with scalatags, it produces sources which are local to the computer where it has been compiled.
I first opened an issue in scala-js, thinking it was a compiler's issue. The available fix is explained in there: scala-js/scala-js#993
Very nice project!
For using it with other open source projects I would like to know what its license is. I hope it's something compatible with the Apache (MIT, etc., see http://www.apache.org/legal/3party.html)
Thanks!
scala.xml.PrettyPrinter does not generate validate W3 html markup language, and alters the orginal placements of tags.
For example
script(src:=""/assets/jquery.min.js"")
generates
< script src="/assets/jquery.min.js"></script>
and is converted to
< script src="/assets/jquery.min.js"/>
When in development it is useful to see the structure of the HTML, however by using scala.xml.PrettyPrinter as described in the readme.md the output is changed and becomes invalid.
Would it be possible to create a basic pretty-print within scalatags itself, I don't think you would need to wrap long lines of text, but showing the correct indentation would be enough.
The link to the ScalaTags Google Group has been removed from the readme. Maybe is better to add it back?
https://groups.google.com/forum/#!forum/scalatags
which probably means default to "px" for those attributes that this matters. We already have a good model of what attributes can take, so this shouldn't be hard
According to the docs, import bundle.short._
"imports the contents of Tags
and DataConverters
, but aliases Attrs
and Styles
as *
"
That's blatantly not the case; no tags are imported. This could be construed as a bug in the documentation, but I'm led to believe that it's a bug in the implementation, because further down in the docs, an example is given with tags like div
and p
being used after importing short._
.
You can import tags from elsewhere, eg. import tags._
, but you get compile errors for expressions like div(List(p,p))
. More generally, if you import underscore from any two subclasses of scalatags.JsDom.Cap, then implicitly[List[Modifier] => Modifier]
fails to compile.
div(div.render, List(*.width:=300.px, p))
to compile is to:
import scalatags.JsDom.short.{*,bindJsAny,bindJsAnyLike,bindNode}
import scalatags.JsDom.tags._
import scalatags.JsDom.implicits._
import scalatags.DataConverters._
or import all._;
, which kinda kills the point of importing the *
.
In short, it's useless to import short._
, which I don't believe was the intention.
More context here: http://stackoverflow.com/questions/29126824/using-title-with-scalatags
import scalatags.Text.all._
title("My Awesome Website")
But
import scalatags.Text.tags2.title
works
Hello.
I've modified the project to support Scala.js. The main problem found was that Scala.js doesn't support Symbols, so Tags.scala gives unsupported exceptions. I've redefined Tags.scala to use strings instead of symbols and it works on Scala.js. I've not tested it fully, but at least works within my project. It's great to have such html engine running directly in the browser!!
The repo with the changes is at https://github.com/Peluko/scalatags
I've created an alternate sbt project into folder scalatags-js
which builds with Scala.js, omits the original Tags.scala file and includes the modified one. Cab be used from other Scala.js projects just creating the dependency to the alternate sbt project.
Hello,
I'm trying to define a tag which extends
How could that be achieved, please?
object dijit { val select = "select".tag[Select] class Select extends dom.HTMLDivElement { //TODO: need to add custom attributes, such as: `data-dojo-type`:="dijit/form/Select" //TODO: implicit def ArrayModifier[A <% Modifier](xs: Array[A]) = new SeqModifier[A](xs.toSeq) } }
Hi there, first of all: Very nice libraries! Thanks for these contributions to ScalaJS!
When reading through the readme, I noticed your first code example in the CSS&Styles section is not demonstration the Style & Styles classes as the text says. It is just the same as the following example which is setting the styles as plain old strings.
In particular, scalatags.math
shadowing all of scala.math
is extremely annoying when you consider the the HTML <math>
tag has been used about 5 times since its inception in 1995, mostly by mistake.
It used to be up at github.io/scalatags. Will it now be at another url?
If you import scalatags._
, title
refers to the Attr
title, not the more commonly used <title>Page Title</title>
that goes in the <head>
tag.
Hi,
I'm developping a scala-js based mobile application (with some ionic/angular bindings) (see https://github.com/olivergg/scalajs-ionic-starttabs), and I would like to automate the generation of both the index.html and index-dev.html (which only differs from the name of the javascript file emitted by fastOptJS and fullOptJS). To do so I was thinking of the following :
write an index.scala file in src/main/html (for example)
write an SBT task to parse the file and output the corresponding HTML String to a file
copy this file to a custom directory (the same way it is done with the .js files)
& 3) are quite easy to do. For 2), I'm thinking of :
// index.scala file
object index {
def output(someParam:String):String = {
html(
head(
script(src:="..."),
script(
"alert('Hello World')"
)
),
body(
div(
h1(id:="title", "This is a title"),
p("This is a big paragraph of text")
)
)
)
}
someParam
could either be equals to "fastOpt" or "fullOpt"). The intepreted code would then contain a defined function that could be called to write the output string to a file.Let me know what you think ;)
Thanks.
When I try to replicate the example under the Layouts section of the readme , I get the following error when I try to define the page
method in sbt console
:
error: No implicit view available from scalatags.Text.all.Modifier => scalatags.Text.Frag.
head(scripts),
I've imported scalatags using import scalatags.Text.all._
.
I'm completely new to scalatags, and fairly new to Scala, so I apologize if this is user error/ignorance--
Versions:
scalatags: 0.4.2
scala: 2.10.4
sbt: 0.13.5
Hi,
Scalatags looks very interesting, I've been doing something similar but yours is much better!
I would like to use your DSL, for creating tags, but have it render to a NodeSeq.
Is that possible right now? If not, would it be possible to support it?
Many thanks,
Paul
That is a typo, right?
Basically, could taking pre-existing HTML ('.html') artifacts and generating valid ScalaTags classes be of any use at all? This isn't a problem per se, just an idea.
To explain further:
What I'm proposing is something like an SBT Plugin(?). When pointed at an HTML-containing directory (or appropriately named HTML files), the plugin would emit valid Scalatags-based Scala classes. The generated classes could then be imported into the codebase and edited within the project, as normal.
To do this conversion, I suggest a library such as TreeHugger, for Scala class file ('.scala') generation and any of a multitude of HTML parsers available for the JVM.
This Stackoverflow post, 'parsing html file to dom tree for extract java' demonstrates the use Neko HTML parser (Java) to correct the HTML input to well-formed HTML (XHTML). The resulting document is then parsed into an XML DOM tree, which could then be used, along with TreeHugger, to generate valid Scalatags code.
I'd be interested to hear any thoughts you might have on this.
Cheers
Attributes in scalatags are all lowercase (eg. onsubmit
, onchange
) which is incompatible ReactJS. To get ReactJS to work I have to specify onChange
instead of onchange
.
Do you think the existing attributes in Scalatags should be changed? What are your thoughts?
I really like your work, and I am going to use scalatags in future projects. So far it's working out brilliantly! Thanks for making your work open source for the world to enjoy :)
In order to migrate existing html pages to scalatags, I am writing an html-to-scalatag converter. In a utility function, I want to print a HtmlTag
as follows:
def print(htag: HtmlTag): String =
htag.tag + "(" + htag.children.map(print(_)).mkString(",") + ")"
The problem is, htag.children is a Seq[STag]
. I cannot print the children, because STags do not have the property tag
. I am trying to find a clean fix for this problem.
And let me know when I start getting annoying. :-)
Hey Haoyi,
I noticed that your projects have this structure of shared folder :
shared / main / scala
Instead of the recommended one :
shared / src / main / scala
I always have a hard time to set up project structure correctly in Intellij Idea, because both "gen-idea" and Intellij Idea scala plugin ignore the sources from this folder because it doesn't follow the maven/sbt dir structure convention. The Scala plugin has 1240 open issues so I guess people get overwhelmed with these problems on daily basis.
Is it by design or by mistake ?
Hi,
Another tag (after data-), not found in the API: _aria-_. The implementation is detailed here:
http://www.w3.org/WAI/PF/aria-implementation/
A first solution would be to implement a ariaWith(suffix: String) method but is not fully typed, or to add all the aria-xxx methods (around 30) in the API. I can do it and pull a PR if you agree with this proposal.
Mathieu
A grep of the course doesn't find the "rowspan" attribute for td tags. See http://www.w3.org/TR/html401/struct/tables.html#h-11.2.6.1
I was looking to do something like:
span("itemscope".attr, "itemtype".attr := "http://data-vocabulary.org/Breadcrumb")
go generate:
<span itemscope itemtype="http://data-vocabulary.org/Breadcrumb">
Reference to usage: https://support.google.com/webmasters/answer/185417?hl=en
Is this possible somehow?
Hey Haoyi,
Trying to throw together a visualization using scalatags and was trying to use the
"content".cls style of classes as seen here: https://github.com/lihaoyi/scalatags#layouts
Here is the my block of code:
import scalatags.JsDom._
import scalatags.JsDom.all._
val lvl = item.s
var e = div(cls := "elscope-item", lvl.qtyIncs.toString)
e = if (lvl.isMd) {
if (lvl.mdSide.isBid)
e("bid".cls)
else
e("ask".cls)
} else {
e("trade".cls)
}
e.render
...anyhow I am getting cls is not a member of String
I searched through the scalatags repo and couldn't find a "def cls" or "val cls" which would be needed in the implicit extension class anywhere (except in the readme).
a. What import do i need?
(a2 I think the code snippets should always have the imports listed at the top, the code snippets should work in isolation, i know the imports are a bit ugly but they really help to have them in each code block so that each one stands on it's own)
b. How can I make an string => class without using the implicit .cls?
c. I am assuming that this will append the class to the list of classes for the element rather than replacing all of them, am I right in this assumption?
Hello, when using script tag, without any inline script, e.g.:
script( src := "/addr.js" )
the tag that gets generated is <script src = "/addr.js"/>
and not <script src = "/addr.js"></script>
as one would want. What could I be doing wrong? Thanks
What would be the proper way to generate a before the html tag ?
For now, I just prepend the string before calling toString on a scalatags fragment.
Thanks.
How hard would it be to implement Virtual DOM (like Facebook React, render the tree, diff trees, update) in terms of scalatags? In combination with Signals/Observable types it would be nice to use pure functions to re-render each time when "something" occurs. With Virtual DOM it should only update the parts which have been changed, so the experience stays smooth and performant. Elm does this aswell: http://elm-lang.org/blog/Blazing-Fast-Html.elm. More about this: https://github.com/evancz/elm-architecture-tutorial
Adding the following to scalatags.BasicTests causes a compile-time error that just seems wrong:
"OptionString" - {
val rd:Option[String] = Some("rd")
val s = rd.getOrElse("")
assert(s.isInstanceOf[String])
val frag = p( rd.getOrElse("") )
assert(frag.toString == """<td>rd</td>""")
}
The error is
test-only scalatags.BasicTests
[info] Compiling 1 Scala source to /Users/bwbecker/temp/scalaTags/target/scala-2.10/test-classes...
[error] /Users/bwbecker/temp/scalaTags/shared/test/scala/scalatags/BasicTests.scala:134: type mismatch;
[error] found : java.io.Serializable
[error] required: scalatags.Modifier
[error] val frag = p( rd.getOrElse("") )
[error] ^
[error] one error found
error Compilation failed
[error] Total time: 1 s, completed 24-Feb-2014 8:28:08 AM
>
Substituting s for rd.getOrElse("") compiles just fine.
The tag doesn't seem to make a difference: it fails on p(...), td(...), and li(...) with the same error.
I spent a bunch of time last night looking at the source code Play creates for templates and trying to figure out what I'd have to do to use ScalaTags instead, but didn't get very far. Now, granted, it was very late and I was tired, but I just wanted to see if you had any examples of how to use ScalaTags as a replacement for a Play template before I tried to reinvent the wheel.
There are these nice, typesafe constants for the predefined CSS colors, but they're only available for the color
property. It seems like these could be factored into a trait that all compatible properties could extend to also take advantage. I don't mind doing this and make a PR if this is a direction you'd be interested in this.
There could also be support for transparent
, currentColor
, and color constants above Level 1 (see https://developer.mozilla.org/en-US/docs/Web/CSS/color_value). I guess it's a question of what level of completeness you're interested in shooting for.
Also, I was wondering if there's any idea of supporting multi-value syntax in the DSL. For example, by using tuples: margin := (10.px, 10.px)
to get margin: 10px 10px;
, perhaps specified dynamically by being able to map from tuple arity to the properties aggregated, to allow for the typesafe shorthands to be used somehow.
Hi Li,
First of all congrats on the amazing job with this library! It's very useful. :)
Quick question: is it possible to define the colSpan
attribute in td
elements? If not, is there any extensibility mechanism that would allow me to do this?
Cheers,
Sérgio
otherwise we have to "selected".attr = ""
(which isn't entirely true because it doesn't need a value, I'm just not sure how to do that).
Hi,
for some reason, the tags from Tags2 does not seem to work properly. For instance the ":=" method does not work fine. The following code in js-fiddle does not work for the nav tag (but works for "p" and "label"):
import scalatags.JsDom.all._
import scalatags.Text.tags2._
object ScalaJSExample extends js.JSApp{
def main() = {
println(p(color := "red")("Red Text"))
println(label(color := "green")("Green Label"))
println(nav(color := "red"))
}
}
produces the error:
Main.scala:20: error: type mismatch;
found : scalatags.generic.StylePair[org.scalajs.dom.Element,String]
required: scalatags.Text.Modifier
(which expands to) scalatags.generic.Modifier[scalatags.text.Builder]
println(nav(color := "red"))
^
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.