summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLi Haoyi <haoyi@dropbox.com>2014-10-29 23:07:55 -0700
committerLi Haoyi <haoyi@dropbox.com>2014-10-29 23:07:55 -0700
commite8b38f242876f99966c3d13cefae2f5863c5bb9e (patch)
tree01989c3899a57cbbc37c5479a7489aa6ac8c753f
parent42394b5fa4bc0a76585d77f587a79b11c1b7c32f (diff)
downloadhands-on-scala-js-e8b38f242876f99966c3d13cefae2f5863c5bb9e.tar.gz
hands-on-scala-js-e8b38f242876f99966c3d13cefae2f5863c5bb9e.tar.bz2
hands-on-scala-js-e8b38f242876f99966c3d13cefae2f5863c5bb9e.zip
lots of refactoring
-rw-r--r--book/canvas-app.tw212
-rw-r--r--book/getting-started.tw324
-rw-r--r--book/index.tw4
-rw-r--r--book/intro.tw3
-rw-r--r--book/src/main/resources/css/grids-responsive-min.css7
-rw-r--r--book/src/main/resources/images/Dropdown.pngbin0 -> 331377 bytes
-rw-r--r--book/src/main/resources/images/Hello World Console.pngbin0 -> 345956 bytes
-rw-r--r--book/src/main/resources/images/Hello World White.pngbin0 -> 245770 bytes
-rw-r--r--book/src/main/resources/images/Hello World.pngbin0 -> 265509 bytes
-rw-r--r--book/src/main/resources/images/IntelliJ Hello.pngbin0 -> 338093 bytes
-rw-r--r--book/src/main/resources/images/Scalatags Downloads.pngbin0 -> 89779 bytes
-rw-r--r--book/src/main/scala/book/Book.scala50
-rw-r--r--examples/src/main/scala/Clock.scala48
-rw-r--r--examples/src/main/scala/FlappyLine.scala105
-rw-r--r--examples/src/main/scala/ScratchPad.scala38
-rw-r--r--examples/src/main/scala/Splash.scala (renamed from examples/src/main/scala/Example.scala)3
16 files changed, 760 insertions, 34 deletions
diff --git a/book/canvas-app.tw b/book/canvas-app.tw
new file mode 100644
index 0000000..ba440e4
--- /dev/null
+++ b/book/canvas-app.tw
@@ -0,0 +1,212 @@
+@p
+ By this point, you've already cloned and got your hands dirty fiddling around with the toy @a("workbench-example-app", href:="https://github.com/lihaoyi/workbench-example-app"). You have your editor set up, SBT installed, and have published the example application in a way you can host online for other people to see. Maybe you've even made some changes to the application to see what happens. Hopefully you're curious, and want to learn more.
+
+@p
+ In this section of the book, we will walk through making a small canvas application. This will expose you to important concepts like:
+
+@ul
+ @li
+ Taking input with Javascript event handlers
+ @li
+ Writing your application logic in Scala
+ @li
+ Using a timer to drive periodic actions
+
+@p
+ In general, while the previous chapter was mostly set-up and exploring the Scala.js project, this chapter will walk you through actually writing a non-trivial, self-contained Scala.js application. Throughout this chapter, we will only be making modifications to @code{ScalaJSExample.scala}; the rest of the project will remain unchanged.
+
+@sect{Making a Sketchpad using Mouse Input}
+
+ @p
+ To begin with, lets remove all the existing stuff in our @code{.scala} file and leave only the @hli.scala{object} and the @hli.scala{main} method. Let's start off with some necessary boilerplate:
+
+ @hl.ref("examples/src/main/scala/ScratchPad.scala", "/*setup*/", end = "/*code*/")
+
+ @p
+ As described earlier, this code uses the @hli.javascript{document.getElementById} function to fish out the @code{canvas} element that we interested in from the DOM. It then gets a rendering context from that @code{canvas}, and sets the height and width of the canvas to completely fill its containing element. Lastly, it fills out the canvas light-gray, so that we can see it on the page.
+
+ @p
+ Next, let's set some event handlers on the canvas:
+
+ @div(cls:="pure-g")
+ @div(cls:="pure-u-1 pure-u-md-13-24")
+ @hl.ref("examples/src/main/scala/ScratchPad.scala", "/*code*/")
+
+ @div(cls:="pure-u-1 pure-u-md-11-24")
+ @canvas(id:="canvas2", display:="block")
+ @script("ScratchPad().main(document.getElementById('canvas2'))")
+
+ @p
+ This code sets up the @code{mousedown} and @code{mouseup} events to keep track of whether or not the mouse has currently been clicked. It then draws black squares any time you move the mouse while the button is down. This lets you basically click-and-drag to draw pictures on the canvas. Try it out!
+
+ @p
+ In general, you have access to all the DOM APIs through the @hli.scala{dom} package as well as through Javascript objects such as the @hli.scala{dom.HTMLCanvasElement}. Setting the @code{onmouseXXX} callbacks is just one way of interacting with the DOM. With Scala.js, you also get a very handy autocomplete in the editor, which you can use to browse the various other APIs that are available for use:
+
+ @img(src:="images/Dropdown.png", maxWidth:="100%")
+
+ @p
+ Apart from mouse events, keyboard events, scroll events, input events, etc. are all usable from Scala.js as you'd expect
+
+@sect{Making a Clock using setInterval}
+
+ @p
+ You've already seen this in the previous example, but @hli.scala{dom.setInterval} can be used to schedule recurring, periodic events in your program. Common use cases include running the event loop for a game, making smooth animations, and other tasks of that sort which require some work to happen over a period of time.
+
+ @p
+ Again, we need roughly the same boilerplate as just now to set up the canvas:
+
+ @hl.ref("examples/src/main/scala/Clock.scala", "/*setup*/", "/*code*/")
+
+ @p
+ The only thing unusual here is that I'm going to create a @hli.scala{linearGradient} in order to make the stopwatch look pretty. This is by no means necessary, and you could simply make the @hli.scala{fillStyle} @hli.scala{"black"} if you want to keep things simple.
+
+ @p
+ Once that's done, it's only a few lines of code to set up a nice, live clock:
+
+ @div(cls:="pure-g")
+ @div(cls:="pure-u-1 pure-u-md-13-24")
+ @hl.ref("examples/src/main/scala/Clock.scala", "/*code*/")
+
+ @div(cls:="pure-u-1 pure-u-md-11-24")
+ @canvas(id:="canvas3", display:="block")
+ @script("Clock().main(document.getElementById('canvas3'))")
+
+ @p
+ As you can see, we're using more @a("Canvas APIs", href:="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D"), in this case dealing with rendering text on the canvas. Another thing we're using is the Javascript @a("Date", href:="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date") class, in Scala.js under the fully name @hli.scala{scala.scalajs.js.Date}, here imported as @hli.scala{js.Date}.
+
+@sect{Tying it together: Flappy Box}
+
+ @p
+ You've just seen two examples of how to use Scala.js, together with the Javascript DOM APIs, to make simple applications. However, we've only used the "Scala" in Scala.js in the most rudimentary fashion: setting a few primitives here and there, defining some methods, mainly just gluing together a few Javascript APIs
+
+ @p
+ In this example we will make a spiritual clone of the popular @a("Flappy Bird", href:="http://en.wikipedia.org/wiki/Flappy_Bird") video game. This game involves a few simple rules
+
+ @ul
+ @li
+ Your character starts in the middle of the screen
+ @li
+ Gravity pulls your character down
+ @li
+ Clicking/tapping the screen makes your character jump up
+ @li
+ There are obstacles that approach your character from the right side of the screen, and you have to make sure you go through the hole in each obstacle to avoid hitting it
+ @li
+ Don't go out of bounds!
+
+ @p
+ It's a relatively simple game, but there should be enough "business logic" in here that we won't be simply gluing together APIs. Let's start!
+
+ @sect{Setting Up the Canvas}
+ @hl.ref("examples/src/main/scala/FlappyLine.scala", "/*setup*/", end="/*variables*/")
+
+ @p
+ This section of the code is peripherally necessary, but not core to the implementation or logic of Flappy Box. We see the same @hli.scala{canvas}/@hli.scala{renderer} logic we've seen in all our examples, along with some logic to make the canvas a reasonable size, and some configuration of how we will render text to the canvas.
+
+ @p
+ In general, code like this will usually end up being necessary in a Scala.js program: the Javascript APIs that the browser provides to do things often ends up being somewhat roundabout and verbose. It's somewhat annoying to have to do for a small program such as this one, but in a larger application, the cost is both spread out over thousands of lines of code and also typically hidden away in some helpers, so you don't have to mess with this stuff unless you really want to.
+
+ @sect{Defining our State}
+ @hl.ref("examples/src/main/scala/FlappyLine.scala", "/*variables*/", end="def runDead")
+
+ @p
+ This is where we start defining things that are relevant to Flappy Box. There are roughly two groups of values here: immutable constants in the top group, and mutable variables in the bottom. The rough meaning of each variable is documented in the comments, and we'll see exactly how we use them later.
+
+ @p
+ One notable thing is that we're using a @hli.scala{collection.mutable.Queue} to store the list of obstacles. This is defined in the Scala standard library; in general, all the collections in the Scala standard library can be used without issue in Scala.js.
+
+ @sect{Game Logic}
+ @hl.ref("examples/src/main/scala/FlappyLine.scala", "def runLive", "def runDead")
+
+ @p
+ The @hli.scala{runLive} function is the meat of Flappy Box. In it, we
+
+ @ul
+ @li
+ Clear the canvas
+ @li
+ Generate new obstacles
+ @li
+ Apply velocity and acceleration to the player
+ @li
+ Check for collisions or out-of-bounds, killing the player if it happens
+ @li
+ Rendering everything, including the player as the namesake box
+
+ @p
+ This function basically contains all the game logic, from motion, to collision-detection, to rendering, so it's pretty large. Not that large though! And entirely understandable, even if it takes a few moments to read through.
+
+ @hl.ref("examples/src/main/scala/FlappyLine.scala", "def runDead", end="def run")
+
+ @p
+ This is the function that handles what happens when you're dead. Essentially, we reset all the mutable variables to their initial state, and just count down the @hli.scala{dead} counter until it reaches zero and we're considered alive again.
+
+ @sect{A Working Product}
+ @hl.ref("examples/src/main/scala/FlappyLine.scala", "def run")
+
+ @p
+ And finally, this is the code that kicks everything off: we define the @hli.scala{run} function to swap between @hli.scala{runLive} and @hli.scala{runDead}, register an @hli.scala{canvas.onclick} handler to make the player jump by tweaking his velocity, and we call @code{setInterval} to run the @hli.scala{run} function every 20 milliseconds.
+
+ @p
+ At almost 100 lines of code, this is quite a meaty example! Nonetheless, when all is said and done, you will find that the example actually works! Try it out!
+
+ @div
+ @canvas(id:="canvas4", display:="block")
+ @script("FlappyLine().main(document.getElementById('canvas4'))")
+
+@sect{Canvas Recap}
+ @p
+ We've now gone through the workings of building a handful of toy applications using Scala.js. What have we learnt in the process?
+
+ @sect{Development Speed}
+ @p
+ We've by now written a good chunk of Scala.js code, and perhaps debugged some mysterious errors, and tried some new things. One thing you've probably noticed is the efficiency of the process: you make a change in your editor, the browser reloads itself, and life goes on. There is a compile cycle, but after a few runs the compiler warms up and the compilation cycle drops to less than a second.
+ @p
+ Apart from the compilation/reload speed, you've probably noticed the benefit of tooling around Scala.js. Unlike Javascript editors, your existin Scala IDEs like IntelliJ or Eclipse can give very useful help when you're working with Scala.js. Autocomplete, error-highlighting, jump-to-definition, and a myriad other modern conveniences that are missing when working in dynamically-typed languages are present when working in Scala.js. This makes the code much less mysterious: you're no longer trying to guess what methods a value has, or what a method returns: it's all laid out in front of you in plain sight.
+
+ @sect{Full Scala}
+ @p
+ All of the examples so far have been very self-contained: they do not touch the HTML DOM, they do not make Ajax calls, or try to access web services. They don't push the limits of the browser's API.
+
+ @p
+ Nevertheless, these examples have exercised a good amount of the Scala language. List comprehensions, collections, the math library, and more. In general, most of the Scala standard library works under Scala.js, as well as a large number of third-party libraries. Unlike many other compile-to-Javascript languages out there, this isn't a language-that-looks-like-Scala: it is Scala through and through, with a tiny number of semantic differences.
+
+ @sect{Seamless Javascript Interop}
+ @p
+ Even if we take some time to read through the code we've written, it is not immediately obvious which bits of code are Scala and which bits are Javascript! It all kind of meshes together, for example if we take the Flappy Box source code:
+
+ @ul
+ @li
+ @hli.scala{obstacles} is a Scala @hli.scala{mutable.Queue}, as we defined it earlier, and all the methods on it are Scala method calls
+ @li
+ @hli.scala{renderer} is a Javascript @hli.javascript{CanvasRenderingContext2D}, and all the methods on it are Javascript method calls directly on the Javascript object
+ @li
+ @hli.scala{frame} is a Scala @hli.scala{Int}, and obeys Scala semantics, though it is implemented as a Javascript @hli.javascript{Number} under the hood.
+ @li
+ @hli.scala{playerY} and @hli.scala{playerV} are Scala @hli.scala{Double}s, implemented directly as Javascript @hli.javascript{Number}s
+
+ @p
+ This reveals something pretty interesting about Scala.js: even though Scala at-first-glance is a very different language from Javascript, the interoperation with Javascript is so seamless that you can't even tell from the code which values/methods are defined in Scala and which values/methods come from Javascript!
+ @p
+ These two classes of values/methods are treated very differently by the compiler when it comes to emitting the executable Javascript blob, but the compiler does not need extra syntax telling it which things belong to Scala and which to Javascript: the types are sufficient. @hli.scala{renderer}, for example is of type @hli.scala{dom.CanvasRenderContext2D} which is a subtype of @hli.scala{scalajs.js.Object}, indicating to the compiler that it needs special treatment. Primitives like @hli.scala{Double}s and @hli.scala{Int}s have similar treatment
+
+ @p
+ Overall, this seamless mix of Scala and Javascript values/methods/functions is a common theme in Scala.js applications, so you should expect to see more of it in later chapters of the book.
+
+ @hr
+
+ @p
+ You've now had some experience building small canvas applications in Scala.js. Why not try exercising your new-found skills? Here are some possibilities:
+
+ @ul
+ @li
+ Make more video games! I have a set of @a("retro-games ported to Scala.js", href:="http://lihaoyi.github.io/scala-js-games/"). Maybe re-make one of them without looking at the source, or maybe port some other game you're familiar with and enjoy playing. Even just drawing things on canvas, games can get @a("pretty elaborate", href:="http://lihaoyi.github.io/roll/").
+
+ @li
+ Explore the APIs! We've touched on a small number of Javascript APIs here, mainly for dealign with the canvas, but modern browsers offer a whole @a("zoo of functionality", href:="https://developer.mozilla.org/en-US/docs/Web/API"). Try making an application that uses @a("localStorage", href:="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage") to save state even when you close the tab, or an application that works with the HTML DOM.
+
+ @li
+ Draw something pretty! We have a working canvas, a nice programming language, and a way to easily publish the results online. @a("Various", href:="http://www.scala-js-fiddle.com/gist/77a3840678d154257ca1/KochSnowflake.scala") @a("fractals", href:="http://www.scala-js-fiddle.com/gist/77a3840678d154257ca1/KochCurve.scala"), or @a("colorful visualizations", href:="http://www.scala-js-fiddle.com/gist/9443f8e0ecc68d1058ad/RayTracer.scala") are all possibilities.
+
+ @p
+ By this point you've some experience building stand-alone, single-canvas Scala.js applications, which has hopefully given you a feel for how Scala.js works. The problem is that few web applications satisfy the criteria of being stand-alone single-page canvas applications! Most web applications need to deal with the DOM of the HTML page, need to fetch data from web services, and generally need to do a lot of other messy things. We'll go into that in the next chapter
diff --git a/book/getting-started.tw b/book/getting-started.tw
new file mode 100644
index 0000000..9b6b9c7
--- /dev/null
+++ b/book/getting-started.tw
@@ -0,0 +1,324 @@
+
+@p
+ To get started with Scala.js, you will need to prepare a few things:
+
+@ul
+ @li
+ @a("sbt", href:="http://www.scala-sbt.org/"): SBT is the most common build-tool in the Scala community, and is what we will use for building our Scala.js application. Their home page has a link to download and install it.
+ @li
+ An editor for Scala: @a("IntelliJ Scala", href:="http://blog.jetbrains.com/scala/") and @a("Eclipse ScalaIDE", href:="http://scala-ide.org/") are the most popular choices and work on all platforms, though there are others.
+ @li
+ @a("Git", href:="http://git-scm.com/"): This is a version-control system that we will use to download and manage our Scala.js projects.
+ @li
+ A terminal: on OSX you have @a("Terminal.app", href:="http://guides.macrumors.com/Terminal") already installed, in Linux you have @a("Terminal", href:="https://help.ubuntu.com/community/UsingTheTerminal"), and on Windows you have @a("PowerShell", href:="http://en.wikipedia.org/wiki/Windows_PowerShell").
+ @li
+ Your favorite web browser: @a("Chrome", href:="https://www.google.com/chrome") and @a("Firefox", href:="https://www.mozilla.org/en-US/firefox") are the most popular.
+
+@p
+ If you've worked with Scala before, you probably already have most of these installed. Otherwise, take a moment to download them before we get to work.
+
+@p
+ The quickest way to get started with Scala.js is to @code{git clone} @a("workbench-example-app", href:="https://github.com/lihaoyi/workbench-example-app"), go into the repository root, and run @code{~fastOptJS}
+
+@hl.bash
+ git clone https://github.com/lihaoyi/workbench-example-app
+ cd workbench-example-app
+ sbt ~fastOptJS
+
+@p
+ This should result in a bunch of spam to the console, and may take a few minutes the first time as SBT resolves and downloads all necessary dependencies. A successful run looks like this
+
+@pre
+ haoyi-mbp:Workspace haoyi$ git clone https://github.com/lihaoyi/workbench-example-app
+ Cloning into 'workbench-example-app'...
+ remote: Counting objects: 876, done.
+ remote: Total 876 (delta 0), reused 0 (delta 0)
+ Receiving objects: 100% (876/876), 676.59 KiB | 317.00 KiB/s, done.
+ Resolving deltas: 100% (308/308), done.
+ Checking connectivity... done.
+ haoyi-mbp:Workspace haoyi$ cd workbench-example-app/
+ haoyi-mbp:workbench-example-app haoyi$ sbt ~fastOptJS
+ [info] Loading global plugins from /Users/haoyi/.sbt/0.13/plugins
+ [info] Updating {file:/Users/haoyi/.sbt/0.13/plugins/}global-plugins...
+ [info] Resolving org.fusesource.jansi#jansi;1.4 ...
+ [info] Done updating.
+ [info] Loading project definition from /Users/haoyi/Dropbox (Personal)/Workspace/workbench-example-app/project
+ [info] Updating {file:/Users/haoyi/Dropbox%20(Personal)/Workspace/workbench-example-app/project/}workbench-example-app-build...
+ [info] Resolving org.fusesource.jansi#jansi;1.4 ...
+ [info] Done updating.
+ [info] Set current project to Example (in build file:/Users/haoyi/Dropbox%20(Personal)/Workspace/workbench-example-app/)
+ [INFO] [10/26/2014 15:42:09.791] [SystemLol-akka.actor.default-dispatcher-2] [akka://SystemLol/user/IO-HTTP/listener-0] Bound to localhost/127.0.0.1:12345
+ [info] Updating {file:/Users/haoyi/Dropbox%20(Personal)/Workspace/workbench-example-app/}workbench-example-app...
+ [info] Resolving jline#jline;2.12 ...
+ [info] Done updating.
+ [info] Compiling 1 Scala source to /Users/haoyi/Dropbox (Personal)/Workspace/workbench-example-app/target/scala-2.11/classes...
+ [info] Fast optimizing /Users/haoyi/Dropbox (Personal)/Workspace/workbench-example-app/target/scala-2.11/example-fastopt.js
+ [info] workbench: Checking example-fastopt.js
+ [info] workbench: Refreshing http://localhost:12345/target/scala-2.11/example-fastopt.js
+ [success] Total time: 11 s, completed Oct 26, 2014 3:42:21 PM
+ 1. Waiting for source changes... (press enter to interrupt)
+
+@p
+ The line @code{Waiting for source changes...} is telling you that your Scala.js program is ready! Now, when you go to the web URL @code{http://localhost:12345/target/scala-2.11/classes/index-dev.html} in your browser, you should see the following:
+
+ @img(src:="images/Hello World.png", maxWidth:="100%")
+
+@p
+ Congratulations, you just built and ran your first Scala.js application! If something here does not happen as expected, it means that one of the steps did not complete successfully. Make sure you can get this working before you proceed onward.
+
+@sect{Opening up the Project}
+
+ @p
+ The next thing to do once you have the project built and running in your browser is to load it into your editor. Both IntelliJ and Eclipse should let you import the Scala.js project without any hassle. Opening it and navigating to @code{ScalaJSExample.scala} would look like this:
+
+ @img(src:="images/IntelliJ Hello.png", maxWidth:="100%")
+
+ @p
+ Let's try changing one line to change the background fill from black to white:
+
+ @hl.diff
+ - ctx.fillStyle = "black"
+ + ctx.fillStyle = "white"
+
+ @p
+ Because we started ran @code{sbt ~fastOptJS} with the @code{~} prefix earlier, it should pick up the change and automatically recompile. The example project is set up to automatically refresh the page when recompilation is complete.
+
+ @img(src:="images/Hello World White.png", maxWidth:="100%")
+
+ @p
+ If you open up your browser's developer console, you'll see that the SBT log output is being mirrored there:
+
+ @img(src:="images/Hello World Console.png", maxWidth:="100%")
+
+ @p
+ Apart from the SBT log output (which is handled by Workbench) any @hli.scala{println}s in your Scala.js code will also end up in the browser console (the @code{main} you see in the console is printed inside the Scala.js application, see if you can find it!) and so will the stack traces for any thrown exceptions.
+
+@sect{The Application Code}
+
+ @p
+ We've downloaded, compiled, ran, and made changes to our first Scala.js application. Let's now take a closer look at the code that we just ran:
+
+ @hl.ref("output/temp/src/main/scala/example/ScalaJSExample.scala")
+
+ @p
+ It's a good chunk of code, though not a huge amount. To someone who didn't know about Scala.js, they would just think it's normal Scala, albeit with this unusual @hli.scala{dom} library and a few weird annotations. Let's pick it apart starting from the top:
+
+ @hl.ref("output/temp/src/main/scala/example/ScalaJSExample.scala", "case class Point", "@JSExport")
+
+ @p
+ Here we are defining a @hli.scala{Point} case class which represents a X/Y position, with some basic operators defined on it. This is done mostly for convenience later on, when we want to manipulate these two-dimensional points. Scala.js is Scala, and supports the entirety of the Scala language. @hli.scala{Point} here behaves identically as it would if you had run Scala on the JVM.
+
+ @hl.ref("output/temp/src/main/scala/example/ScalaJSExample.scala", "@JSExport", "val ctx")
+
+ @p
+ This @hli.scala("@JSExport") annotation is used to tell Scala.js that you want this method to be visible and callable from Javascript. By default, Scala.js does dead code elimination and removes any methods or classes which are not used. This is done to keep the compiled executables a reasonable size, since most projects use only a small fraction of e.g. the standard library. @hli.scala("@JSExport") is used to tell Scala.js that the @hli.scala{ScalaJSExample} object and its @hli.scala{def main} method are entry points to the program. Even if they aren't called anywhere internally, they are called externally by Javascript that the Scala.js compiler is not aware of, and should not be removed.
+
+ @p
+ Apart from this annotation, @hli.scala{ScalaJSExample} is just a normal Scala @hli.scala{object}, and behaves like one in every way. Note that the main-method in this case takes a @hli.scala{dom.HTMLCanvasElement}: your exported methods can have any signature, with arbitrary arity or types for parameters or the return value. This is in contrast to the main method on the JVM which always takes an @hli.scala{Array[String]} and returns @hli.scala{Unit}. In fact, there's nothing special about this method at all! It's like any other exported method, we just happen to attribute it the "main" entry point.
+
+ @hl.ref("output/temp/src/main/scala/example/ScalaJSExample.scala", "val ctx", "var count")
+
+ @p
+ Here we are retrieving a handle to the canvas we will draw on using @hli.scala{document.getElementById}, and from it we can get a @hli.scala{dom.CanvasRenderingContext2D} which we actually use to draw on it.
+
+ @p
+ @hli.scala{document.getElementById} is the exact same API that's used in normal Javascript, as documented @a("here", href:="https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById"). In fact, the entire @hli.scala{org.scalajs.dom} namespace (imported at the top of the file) comprises statically typed facades for the javascript APIs provided by the browser.
+
+ @p
+ We need to perform the @hli.scala{asInstanceOf} call because depending on what you pass to @hli.scala{getElementById} and @hli.scala{getContext}, you could be returned elements and contexts of different types. Hence we need to tell the compiler explicitly that we're expecting a @hli.scala{dom.HTMLCanvasElement} and @hli.scala{dom.CanvasRenderingContext2D} back from these methods for the strings we passed in.
+
+ @hl.ref("output/temp/src/main/scala/example/ScalaJSExample.scala", "def run", "dom.setInterval")
+
+ @p
+ This is the part of the Scala.js program which does the real work. It runs 10 iterations of a @a("small algorithm", href:="http://en.wikipedia.org/wiki/Sierpinski_triangle#Chaos_game") that generates a Sierpinski Triangle point-by-point. The steps, as described by the linked article, are roughly:
+
+ @ul
+ @li
+ Pick a random corner of the large-triangle
+ @li
+ Move your current-position @hli.scala{p} halfway between its current location and that corner
+ @li
+ Draw a dot
+ @li
+ Repeat
+
+ @p
+ In this example, the triangle is hard-coded to be 255 pixels high by 255 pixels wide, and some math is done to pick a color for each dot which will give the triangle a pretty gradient.
+
+ @hl.ref("output/temp/src/main/scala/example/ScalaJSExample.scala", "dom.setInterval")
+
+ @p
+ Now this is the call that actually does the useful work. All this method does is call @hli.scala{dom.setInterval}, which tells the browser to run the @hli.scala{run} method every 50 milliseconds. As mentioned earlier, the @hli.scala{dom.*} methods are simply facades to their native Javascript equivalents, and @hli.scala{dom.setInterval} is @a("no different", href:="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval"). Note how you can pass a Scala lambda to @hli.scala{setInterval} to have it called by the browser, where in Javascript you'd need to pass a Javascript @hli.javascript{function(){...}}
+
+@sect{The Project Code}
+
+ @p
+ We've already taken a look at the application code for a simple, self-contained Scala.js application, but this application is not @i{entirely} self contained. It's wrapped in a small SBT project that sets up the necessary dependencies and infrastructure for this application to work.
+
+ @sect{project/build.sbt}
+ @hl.ref("output/temp/project/build.sbt")
+
+ @p
+ This is the list of SBT plugins used by this small example application. There are two of them: the Scala.js plugin (which contains the Scala.js compiler and other things, e.g. tasks such as @code{fastOptJS}) and the @a("Workbench", href:="https://github.com/lihaoyi/workbench") plugin, which is used to provide the auto-reload-on-change behavior and the forwarding of SBT logspam to the browser console.
+
+ @p
+ Of the two, only the Scala.js plugin is really necessary. The Workbench plugin is a convenience that makes development easier. Without it you'd need to keep a terminal open to view the SBT logspam, and manually refresh the page when compilation finished. Not the end of the world.
+
+
+ @sect{build.sbt}
+ @hl.ref("output/temp/build.sbt")
+
+ @p
+ The @code{build.sbt} project file for this application is similarly unremarkable: It includes the settings for the two SBT plugins we saw earlier, as well as boilerplate @hli.scala{name}/@hli.scala{version}/@hli.scala{scalaVersion} values common to all projects.
+
+ @p
+ Of interest is the @hli.scala{libraryDependencies}. In Scala-JVM, this key is used to declare dependencies on libraries from Maven Central, so you can use them in your Scala-JVM projects. In Scala.js, the same key is used to declare dependencies on libraries so you can use them in your Scala.js projects! Re-usable libraries can be built and published with Scala.js just as you do on Scala-JVM, and here we make use of one which provides the typed facades with which we used to access the DOM in the application code.
+
+ @p
+ Lastly, we have two Workbench related settings: @hli.scala{bootSnippet} basically tells Workbench how to restart your application when a new compilation run finishes, and @hli.scala{updateBrowsers} actually tells it to perform this application-restarting.
+
+ @sect{src/main/resources/index-dev.html}
+ @hl.ref("output/temp/src/main/resources/index-dev.html")
+
+ @p
+ This is the HTML page which our toy app lives in, and the same page that we have so far been using to view the app in the browser. To anyone who has used HTML, most of it is probably familiar. Things of note are the Script tags: @hli.scala{"../example-fastopt.js"} Is the executable blob spat out by the compiler, which we need to include in the HTML page for anything to happen. This is where the results of your compiled Scala code appear. @hli.scala{"workbench.js"} is the client for the Workbench plugin that connects to SBT, reloads the browser and forwards logspam to the browser console.
+
+ @p
+ The @hli.scala{ScalaJSExample().main()} call is what kicks off the Scala.js application and starts its execution. Scala.js follows Scala semantics in that @hli.scala{object}s are evaluated lazily, with no top-level code allowed. This is in contrast to Javascript, where you can include top-level statements and object-literals in your code which execute immediately. In Scala.js, nothing happens when @code{../example-fastopt.js} is imported! We have to call the main-method first.
+
+ @p
+ Lastly, only @hli.scala("@JSExport")ed objects and methods can be called from Javascript. Also, although this example only exports the @hli.scala{main} method which is called once, there is nothing stopping you from exporting any number of objects and methods and calling them whenever you need to. In this way, you can easily make a Scala.js "library" which is available to external Javascript as an API.
+
+@sect{Publishing}
+ @p
+ The last thing that we'll do with our toy application is to publish it. If you look in the @code{target/scala2.11} folder, you'll see the output of everything we've done so far:
+
+ @hl.bash
+ target/scala-2.11
+ ├── classes
+ │   ├── JS_DEPENDENCIES
+ │   ├── example
+ │   │   ├── Point$.class
+ │   │   ├── Point$.sjsir
+ │   │   ├── Point.class
+ │   │   ├── Point.sjsir
+ │   │   ├── ScalaJSExample$$anonfun$main$1.class
+ │   │   ├── ScalaJSExample$$anonfun$run$1.class
+ │   │   ├── ScalaJSExample$.class
+ │   │   ├── ScalaJSExample$.sjsir
+ │   │   └── ScalaJSExample.class
+ │   ├── index-dev.html
+ │   └── index-opt.html
+ ├── example-fastopt.js
+ └── example-fastopt.js.map
+
+ @p
+ All the @code{.class} and @code{.sjsir} files are the direct output of the Scala.js compiler, and aren't necessary to actually run the application. The only two files necessary are @code{index-dev.html} and @code{example-fastopt.js}. You may recognize @code{index-dev.html} as the file that we were navigating to in the browser earlier.
+
+ @p
+ These two files can be extracted and published as-is: you can put them on @a("Github-Pages", href:="https://pages.github.com/"), @a("Amazon Web Services", href:="http://docs.aws.amazon.com/gettingstarted/latest/swh/website-hosting-intro.html"), or a hundred other places. However, one thing of note is the fact that the generated Javascript file is quite large:
+
+ @hl.bash
+ haoyi-mbp:temp haoyi$ du -h target/scala-2.11/example-fastopt.js
+ 856K target/scala-2.11/example-fastopt.js
+
+ @p
+ 856 Kilobytes for a hello world app! That is clearly too large. If you examine the contents of the file, you'll see that your code has been translated into something like this:
+
+ @hl.javascript
+ var i$2 = i;
+ if (((ScalaJS.m.Lexample_ScalaJSExample().count$1 % 30000) === 0)) {
+ ScalaJS.m.Lexample_ScalaJSExample().clear__V()
+ };
+ ScalaJS.m.Lexample_ScalaJSExample().count$1 = ((ScalaJS.m.Lexample_ScalaJSExample().count$1 + 1) | 0);
+ var jsx$3 = ScalaJS.m.Lexample_ScalaJSExample();
+ var jsx$2 = ScalaJS.m.Lexample_ScalaJSExample().p$1;
+ var jsx$1 = ScalaJS.m.Lexample_ScalaJSExample().corners$1;
+ var this$5 = ScalaJS.m.s_util_Random();
+ jsx$3.p$1 = jsx$2.$$plus__Lexample_Point__Lexample_Point(ScalaJS.as.Lexample_Point(jsx$1.apply__I__O(this$5.self$1.nextInt__I__I(3)))).$$div__I__Lexample_Point(2);
+ var height = (512.0 / ((255 + ScalaJS.m.Lexample_ScalaJSExample().p$1.y$1) | 0));
+ var r = ((ScalaJS.m.Lexample_ScalaJSExample().p$1.x$1 * height) | 0);
+ var g = ((((255 - ScalaJS.m.Lexample_ScalaJSExample().p$1.x$1) | 0) * height) | 0);
+
+ @p
+ As you can see, this code is still very verbose, with lots of unnecessarily long identifiers such as @hli.javascript{Lexample_ScalaJSExample} in it. This is because we've only performed the @i{fast optimization} on this file, to try and keep the time taken to edit -> compile while developing reasonably short.
+
+ @sect{Full Optimization}
+ @p
+ If we're planning on publishing the app for real, we can run the @i{full optimization}. This takes several seconds longer than the @i{fast optimization}, but results in a significantly smaller and leaner output file @code{example-opt.js}.
+
+ @hl.bash
+ haoyi-mbp:temp haoyi$ du -h target/scala-2.11/example-opt.js
+ 144K target/scala-2.11/example-opt.js
+
+ @p
+ 144 Kilobytes! Better. Not great, though! In general, Scala.js does not produce tiny executables, although the output size of the compiled executables is dropping all the time. If you look inside that file, you'll see all of the long identifiers have been replaced by short ones by the Google Closure Compiler.
+
+ @hl.javascript("""
+ Rb(P(),N(r(L(Ea),["rgb(",", ",", ",")"])))),Sb(P(),r(L(K),[n,s,C])));fe().te.fillRect(fe().Oc.jc,fe().Oc.kc,1,1);e=e+1|0;c=c+k|0}},50))}ae.prototype.Zf=function(){this.te.fillStyle="black";this.te.fillRect(0,0,255,255)};ae.prototype.main=function(){return ee(),void 0};ae.prototype.a=new I({lj:0},!1,"example.ScalaJSExample$",K,{lj:1,b:1});var be=void 0;function fe(){be||(be=(new ae).c());return be}ba.ScalaJSExample=fe;function le(){}le.prototype=new J;function me(){}me.prototype=le.prototype;
+ """)
+
+ @p
+ These files are basically unreadable, but nonetheless behave the same as the @code{-fastopt} versions. Try it out by opening the @code{index-opt.html} file in the @code{target/scala-2.11/classes} directory with your browser: you should see the thing as when opening @code{index-dev}, except it will be pulling in the fully-optmized version of your application.
+
+ @p
+ This means you can develop and debug using @code{fastOptJS}, and only spend the extra time (and increased debugging-difficulty) on the @code{fullOptJS} version just as you're going to publish it, with the assurance that although the code is much more compact, its behavior will not change.
+
+ @sect{Blob Size}
+ @p
+ Even the fully-optimized version of our toy Scala.js app are pretty large. There are some factors that mitigate the large size of these executables:
+
+ @ul
+ @li
+ A large portion of this 144k is the Scala standard library, and so the size of the compiled blob does not grow that fast as your program grows. For example, while this ~50 line application is 144k, a much larger ~2000 line application is only 288k.
+ @li
+ This size is pre-@a("gzip", href:="http://en.wikipedia.org/wiki/Gzip"), and most webservers serve their contents compressed via gzip to reduce the download size. Gzip cuts the actual download size down to 43k, which is more acceptable.
+
+ @p
+ And there is ongoing work to shrink the size of these executables. If you want to read more about this, check out the section on the Scala.js File Encoding and the Optimization Pipeline.
+
+ @hr
+
+ @p
+ In general, all the output of the Scala.js compiler is bundled up into the @code{example-fastopt.js} and @code{example-opt.js} files. As a first approximation, these files can be included directly on a HTML page (as we have here, with @code{index-dev.html} and @code{index-opt.html}) and published together as a working web app. Even zipping them up and emailing them to a friend is sufficient to give someone a working, live version of your hard work!
+
+ @p
+ More advanced users would want to integrate them into their build process or serve them from a web server, all of which is entirely possible. You just need to run the Scala.js compiler and place the output @code{.js} file somewhere your web server can pick it up, e.g. in some static-resource folder. We cover an example setup of this with a Scala webserver in our Client Server Integration chapter.
+
+@sect{Recap}
+
+ @p
+ If you've made it this far, you've downloaded, made modifications to, and published a toy Scala.js application. At the same time, we've gone over many of the key concepts in the Scala.js development process:
+
+ @ul
+ @li
+ Getting a Scala.js application
+ @li
+ Building it and seeing it work in the browser
+ @li
+ Made modifications to it to see it update
+ @li
+ Examined the source code to try and understand what it's doing
+ @li
+ Examined the output code, at two levels of optimization, to see how the Scala.js compiler works
+ @li
+ Packaged the application in a form that can be easily published online
+
+ @p
+ Hopefully this gives a good sense of the workflow involved in developing a Scala.js application end-to-end, as well as a feel for the magic involved in the compilation process. Nevertheless, we have barely written any Scala.js code itself!
+
+ @p
+ Since you have a working development environment set up, you should take this time to poke around what you can do with our small Sierpinski-Triangle drawing app. Possible exercises include:
+
+ @ul
+ @li
+ Javascript includes APIs for @a("getting the size of the window", href:="http://stackoverflow.com/questions/1248081/get-the-browser-viewport-dimensions-with-javascript") and @a("changing the size of a canvas", href:="http://stackoverflow.com/questions/9251480/set-canvas-size-using-javascript"). These Javascript APIs are available in Scala.js, and we've already used some of them in the course of this example. Try making the Canvas full-screen, and re-positioning the corners of the triangle to match.
+ @li
+ The @hli.scala{dom.CanvasRenderingContext2D} has a bunch of methods on it that can be used to draw things. Here we only draw 1x1 rectangles to put points on the canvas; try modifying the code to make it draw something else.
+ @li
+ We've look at the @code{master} branch of @code{workbench-example-app}, but this project also has several other branches showing off different facets of Scala.js: @a("dodge-the-dots", href:="https://github.com/lihaoyi/workbench-example-app/tree/dodge-the-dots") and @a("space-invaders", href:="https://github.com/lihaoyi/workbench-example-app/tree/space-invaders") are both interesting branches worth playing with as a beginner. Check them out!
+ @li
+ Try publishing the output code somewhere. You only need @code{example-opt.js} and @code{index-opt.html}; try putting them somewhere online where the world can see it.
+
+ @p
+ When you're done poking around our toy web application, read on to the next chapter, where we will explore making something more meaty using the Scala.js toolchain!
diff --git a/book/index.tw b/book/index.tw
index 4dcea2d..3cf8df3 100644
--- a/book/index.tw
+++ b/book/index.tw
@@ -2,11 +2,11 @@
@sect("Hands-on Scala.js")
@div(cls:="pure-g")
@div(cls:="pure-u-1 pure-u-md-13-24")
- @hl.ref("examples/src/main/scala/Example.scala", "/*example*/", indented=false)
+ @hl.ref("examples/src/main/scala/Splash.scala", "var x")
@div(cls:="pure-u-1 pure-u-md-11-24")
@canvas(id:="canvas1", display:="block")
- @script("Example().main(document.getElementById('canvas1'))")
+ @script("Splash().main(document.getElementById('canvas1'))")
@p
@a("Scala.js", href:="http://www.scala-js.org/") is a compiler that compiles Scala source code to equivalent Javascript code. That lets you write Scala code that you can run in a web browser, or other environments (Chrome plugins, Node.js, etc.) where Javascript is supported.
diff --git a/book/intro.tw b/book/intro.tw
index 7c31fbc..f00a53a 100644
--- a/book/intro.tw
+++ b/book/intro.tw
@@ -23,6 +23,9 @@
});
@p
+ As you can see, both of the above programs do identical things: it's just that the one on the left is written in Scala and the one on the right is in Javascript.
+
+@p
Traditionally, Scala has been a language which runs on the JVM. This eliminates it from consideration in many cases, e.g. when you need to build interactive web apps, you need to fall back to Javascript to run your client-side code, at a great loss in terms of toolability and maintainability. Scala.js lets you to develop web applications with the safety and toolability that comes with a statically typed language:
@ul
diff --git a/book/src/main/resources/css/grids-responsive-min.css b/book/src/main/resources/css/grids-responsive-min.css
new file mode 100644
index 0000000..7bcfd32
--- /dev/null
+++ b/book/src/main/resources/css/grids-responsive-min.css
@@ -0,0 +1,7 @@
+/*!
+Pure v0.5.0
+Copyright 2014 Yahoo! Inc. All rights reserved.
+Licensed under the BSD License.
+https://github.com/yui/pure/blob/master/LICENSE.md
+*/
+@media screen and (min-width:35.5em){.pure-u-sm-1,.pure-u-sm-1-1,.pure-u-sm-1-2,.pure-u-sm-1-3,.pure-u-sm-2-3,.pure-u-sm-1-4,.pure-u-sm-3-4,.pure-u-sm-1-5,.pure-u-sm-2-5,.pure-u-sm-3-5,.pure-u-sm-4-5,.pure-u-sm-5-5,.pure-u-sm-1-6,.pure-u-sm-5-6,.pure-u-sm-1-8,.pure-u-sm-3-8,.pure-u-sm-5-8,.pure-u-sm-7-8,.pure-u-sm-1-12,.pure-u-sm-5-12,.pure-u-sm-7-12,.pure-u-sm-11-12,.pure-u-sm-1-24,.pure-u-sm-2-24,.pure-u-sm-3-24,.pure-u-sm-4-24,.pure-u-sm-5-24,.pure-u-sm-6-24,.pure-u-sm-7-24,.pure-u-sm-8-24,.pure-u-sm-9-24,.pure-u-sm-10-24,.pure-u-sm-11-24,.pure-u-sm-12-24,.pure-u-sm-13-24,.pure-u-sm-14-24,.pure-u-sm-15-24,.pure-u-sm-16-24,.pure-u-sm-17-24,.pure-u-sm-18-24,.pure-u-sm-19-24,.pure-u-sm-20-24,.pure-u-sm-21-24,.pure-u-sm-22-24,.pure-u-sm-23-24,.pure-u-sm-24-24{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-u-sm-1-24{width:4.1667%;*width:4.1357%}.pure-u-sm-1-12,.pure-u-sm-2-24{width:8.3333%;*width:8.3023%}.pure-u-sm-1-8,.pure-u-sm-3-24{width:12.5%;*width:12.469%}.pure-u-sm-1-6,.pure-u-sm-4-24{width:16.6667%;*width:16.6357%}.pure-u-sm-1-5{width:20%;*width:19.969%}.pure-u-sm-5-24{width:20.8333%;*width:20.8023%}.pure-u-sm-1-4,.pure-u-sm-6-24{width:25%;*width:24.969%}.pure-u-sm-7-24{width:29.1667%;*width:29.1357%}.pure-u-sm-1-3,.pure-u-sm-8-24{width:33.3333%;*width:33.3023%}.pure-u-sm-3-8,.pure-u-sm-9-24{width:37.5%;*width:37.469%}.pure-u-sm-2-5{width:40%;*width:39.969%}.pure-u-sm-5-12,.pure-u-sm-10-24{width:41.6667%;*width:41.6357%}.pure-u-sm-11-24{width:45.8333%;*width:45.8023%}.pure-u-sm-1-2,.pure-u-sm-12-24{width:50%;*width:49.969%}.pure-u-sm-13-24{width:54.1667%;*width:54.1357%}.pure-u-sm-7-12,.pure-u-sm-14-24{width:58.3333%;*width:58.3023%}.pure-u-sm-3-5{width:60%;*width:59.969%}.pure-u-sm-5-8,.pure-u-sm-15-24{width:62.5%;*width:62.469%}.pure-u-sm-2-3,.pure-u-sm-16-24{width:66.6667%;*width:66.6357%}.pure-u-sm-17-24{width:70.8333%;*width:70.8023%}.pure-u-sm-3-4,.pure-u-sm-18-24{width:75%;*width:74.969%}.pure-u-sm-19-24{width:79.1667%;*width:79.1357%}.pure-u-sm-4-5{width:80%;*width:79.969%}.pure-u-sm-5-6,.pure-u-sm-20-24{width:83.3333%;*width:83.3023%}.pure-u-sm-7-8,.pure-u-sm-21-24{width:87.5%;*width:87.469%}.pure-u-sm-11-12,.pure-u-sm-22-24{width:91.6667%;*width:91.6357%}.pure-u-sm-23-24{width:95.8333%;*width:95.8023%}.pure-u-sm-1,.pure-u-sm-1-1,.pure-u-sm-5-5,.pure-u-sm-24-24{width:100%}}@media screen and (min-width:48em){.pure-u-md-1,.pure-u-md-1-1,.pure-u-md-1-2,.pure-u-md-1-3,.pure-u-md-2-3,.pure-u-md-1-4,.pure-u-md-3-4,.pure-u-md-1-5,.pure-u-md-2-5,.pure-u-md-3-5,.pure-u-md-4-5,.pure-u-md-5-5,.pure-u-md-1-6,.pure-u-md-5-6,.pure-u-md-1-8,.pure-u-md-3-8,.pure-u-md-5-8,.pure-u-md-7-8,.pure-u-md-1-12,.pure-u-md-5-12,.pure-u-md-7-12,.pure-u-md-11-12,.pure-u-md-1-24,.pure-u-md-2-24,.pure-u-md-3-24,.pure-u-md-4-24,.pure-u-md-5-24,.pure-u-md-6-24,.pure-u-md-7-24,.pure-u-md-8-24,.pure-u-md-9-24,.pure-u-md-10-24,.pure-u-md-11-24,.pure-u-md-12-24,.pure-u-md-13-24,.pure-u-md-14-24,.pure-u-md-15-24,.pure-u-md-16-24,.pure-u-md-17-24,.pure-u-md-18-24,.pure-u-md-19-24,.pure-u-md-20-24,.pure-u-md-21-24,.pure-u-md-22-24,.pure-u-md-23-24,.pure-u-md-24-24{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-u-md-1-24{width:4.1667%;*width:4.1357%}.pure-u-md-1-12,.pure-u-md-2-24{width:8.3333%;*width:8.3023%}.pure-u-md-1-8,.pure-u-md-3-24{width:12.5%;*width:12.469%}.pure-u-md-1-6,.pure-u-md-4-24{width:16.6667%;*width:16.6357%}.pure-u-md-1-5{width:20%;*width:19.969%}.pure-u-md-5-24{width:20.8333%;*width:20.8023%}.pure-u-md-1-4,.pure-u-md-6-24{width:25%;*width:24.969%}.pure-u-md-7-24{width:29.1667%;*width:29.1357%}.pure-u-md-1-3,.pure-u-md-8-24{width:33.3333%;*width:33.3023%}.pure-u-md-3-8,.pure-u-md-9-24{width:37.5%;*width:37.469%}.pure-u-md-2-5{width:40%;*width:39.969%}.pure-u-md-5-12,.pure-u-md-10-24{width:41.6667%;*width:41.6357%}.pure-u-md-11-24{width:45.8333%;*width:45.8023%}.pure-u-md-1-2,.pure-u-md-12-24{width:50%;*width:49.969%}.pure-u-md-13-24{width:54.1667%;*width:54.1357%}.pure-u-md-7-12,.pure-u-md-14-24{width:58.3333%;*width:58.3023%}.pure-u-md-3-5{width:60%;*width:59.969%}.pure-u-md-5-8,.pure-u-md-15-24{width:62.5%;*width:62.469%}.pure-u-md-2-3,.pure-u-md-16-24{width:66.6667%;*width:66.6357%}.pure-u-md-17-24{width:70.8333%;*width:70.8023%}.pure-u-md-3-4,.pure-u-md-18-24{width:75%;*width:74.969%}.pure-u-md-19-24{width:79.1667%;*width:79.1357%}.pure-u-md-4-5{width:80%;*width:79.969%}.pure-u-md-5-6,.pure-u-md-20-24{width:83.3333%;*width:83.3023%}.pure-u-md-7-8,.pure-u-md-21-24{width:87.5%;*width:87.469%}.pure-u-md-11-12,.pure-u-md-22-24{width:91.6667%;*width:91.6357%}.pure-u-md-23-24{width:95.8333%;*width:95.8023%}.pure-u-md-1,.pure-u-md-1-1,.pure-u-md-5-5,.pure-u-md-24-24{width:100%}}@media screen and (min-width:64em){.pure-u-lg-1,.pure-u-lg-1-1,.pure-u-lg-1-2,.pure-u-lg-1-3,.pure-u-lg-2-3,.pure-u-lg-1-4,.pure-u-lg-3-4,.pure-u-lg-1-5,.pure-u-lg-2-5,.pure-u-lg-3-5,.pure-u-lg-4-5,.pure-u-lg-5-5,.pure-u-lg-1-6,.pure-u-lg-5-6,.pure-u-lg-1-8,.pure-u-lg-3-8,.pure-u-lg-5-8,.pure-u-lg-7-8,.pure-u-lg-1-12,.pure-u-lg-5-12,.pure-u-lg-7-12,.pure-u-lg-11-12,.pure-u-lg-1-24,.pure-u-lg-2-24,.pure-u-lg-3-24,.pure-u-lg-4-24,.pure-u-lg-5-24,.pure-u-lg-6-24,.pure-u-lg-7-24,.pure-u-lg-8-24,.pure-u-lg-9-24,.pure-u-lg-10-24,.pure-u-lg-11-24,.pure-u-lg-12-24,.pure-u-lg-13-24,.pure-u-lg-14-24,.pure-u-lg-15-24,.pure-u-lg-16-24,.pure-u-lg-17-24,.pure-u-lg-18-24,.pure-u-lg-19-24,.pure-u-lg-20-24,.pure-u-lg-21-24,.pure-u-lg-22-24,.pure-u-lg-23-24,.pure-u-lg-24-24{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-u-lg-1-24{width:4.1667%;*width:4.1357%}.pure-u-lg-1-12,.pure-u-lg-2-24{width:8.3333%;*width:8.3023%}.pure-u-lg-1-8,.pure-u-lg-3-24{width:12.5%;*width:12.469%}.pure-u-lg-1-6,.pure-u-lg-4-24{width:16.6667%;*width:16.6357%}.pure-u-lg-1-5{width:20%;*width:19.969%}.pure-u-lg-5-24{width:20.8333%;*width:20.8023%}.pure-u-lg-1-4,.pure-u-lg-6-24{width:25%;*width:24.969%}.pure-u-lg-7-24{width:29.1667%;*width:29.1357%}.pure-u-lg-1-3,.pure-u-lg-8-24{width:33.3333%;*width:33.3023%}.pure-u-lg-3-8,.pure-u-lg-9-24{width:37.5%;*width:37.469%}.pure-u-lg-2-5{width:40%;*width:39.969%}.pure-u-lg-5-12,.pure-u-lg-10-24{width:41.6667%;*width:41.6357%}.pure-u-lg-11-24{width:45.8333%;*width:45.8023%}.pure-u-lg-1-2,.pure-u-lg-12-24{width:50%;*width:49.969%}.pure-u-lg-13-24{width:54.1667%;*width:54.1357%}.pure-u-lg-7-12,.pure-u-lg-14-24{width:58.3333%;*width:58.3023%}.pure-u-lg-3-5{width:60%;*width:59.969%}.pure-u-lg-5-8,.pure-u-lg-15-24{width:62.5%;*width:62.469%}.pure-u-lg-2-3,.pure-u-lg-16-24{width:66.6667%;*width:66.6357%}.pure-u-lg-17-24{width:70.8333%;*width:70.8023%}.pure-u-lg-3-4,.pure-u-lg-18-24{width:75%;*width:74.969%}.pure-u-lg-19-24{width:79.1667%;*width:79.1357%}.pure-u-lg-4-5{width:80%;*width:79.969%}.pure-u-lg-5-6,.pure-u-lg-20-24{width:83.3333%;*width:83.3023%}.pure-u-lg-7-8,.pure-u-lg-21-24{width:87.5%;*width:87.469%}.pure-u-lg-11-12,.pure-u-lg-22-24{width:91.6667%;*width:91.6357%}.pure-u-lg-23-24{width:95.8333%;*width:95.8023%}.pure-u-lg-1,.pure-u-lg-1-1,.pure-u-lg-5-5,.pure-u-lg-24-24{width:100%}}@media screen and (min-width:80em){.pure-u-xl-1,.pure-u-xl-1-1,.pure-u-xl-1-2,.pure-u-xl-1-3,.pure-u-xl-2-3,.pure-u-xl-1-4,.pure-u-xl-3-4,.pure-u-xl-1-5,.pure-u-xl-2-5,.pure-u-xl-3-5,.pure-u-xl-4-5,.pure-u-xl-5-5,.pure-u-xl-1-6,.pure-u-xl-5-6,.pure-u-xl-1-8,.pure-u-xl-3-8,.pure-u-xl-5-8,.pure-u-xl-7-8,.pure-u-xl-1-12,.pure-u-xl-5-12,.pure-u-xl-7-12,.pure-u-xl-11-12,.pure-u-xl-1-24,.pure-u-xl-2-24,.pure-u-xl-3-24,.pure-u-xl-4-24,.pure-u-xl-5-24,.pure-u-xl-6-24,.pure-u-xl-7-24,.pure-u-xl-8-24,.pure-u-xl-9-24,.pure-u-xl-10-24,.pure-u-xl-11-24,.pure-u-xl-12-24,.pure-u-xl-13-24,.pure-u-xl-14-24,.pure-u-xl-15-24,.pure-u-xl-16-24,.pure-u-xl-17-24,.pure-u-xl-18-24,.pure-u-xl-19-24,.pure-u-xl-20-24,.pure-u-xl-21-24,.pure-u-xl-22-24,.pure-u-xl-23-24,.pure-u-xl-24-24{display:inline-block;*display:inline;zoom:1;letter-spacing:normal;word-spacing:normal;vertical-align:top;text-rendering:auto}.pure-u-xl-1-24{width:4.1667%;*width:4.1357%}.pure-u-xl-1-12,.pure-u-xl-2-24{width:8.3333%;*width:8.3023%}.pure-u-xl-1-8,.pure-u-xl-3-24{width:12.5%;*width:12.469%}.pure-u-xl-1-6,.pure-u-xl-4-24{width:16.6667%;*width:16.6357%}.pure-u-xl-1-5{width:20%;*width:19.969%}.pure-u-xl-5-24{width:20.8333%;*width:20.8023%}.pure-u-xl-1-4,.pure-u-xl-6-24{width:25%;*width:24.969%}.pure-u-xl-7-24{width:29.1667%;*width:29.1357%}.pure-u-xl-1-3,.pure-u-xl-8-24{width:33.3333%;*width:33.3023%}.pure-u-xl-3-8,.pure-u-xl-9-24{width:37.5%;*width:37.469%}.pure-u-xl-2-5{width:40%;*width:39.969%}.pure-u-xl-5-12,.pure-u-xl-10-24{width:41.6667%;*width:41.6357%}.pure-u-xl-11-24{width:45.8333%;*width:45.8023%}.pure-u-xl-1-2,.pure-u-xl-12-24{width:50%;*width:49.969%}.pure-u-xl-13-24{width:54.1667%;*width:54.1357%}.pure-u-xl-7-12,.pure-u-xl-14-24{width:58.3333%;*width:58.3023%}.pure-u-xl-3-5{width:60%;*width:59.969%}.pure-u-xl-5-8,.pure-u-xl-15-24{width:62.5%;*width:62.469%}.pure-u-xl-2-3,.pure-u-xl-16-24{width:66.6667%;*width:66.6357%}.pure-u-xl-17-24{width:70.8333%;*width:70.8023%}.pure-u-xl-3-4,.pure-u-xl-18-24{width:75%;*width:74.969%}.pure-u-xl-19-24{width:79.1667%;*width:79.1357%}.pure-u-xl-4-5{width:80%;*width:79.969%}.pure-u-xl-5-6,.pure-u-xl-20-24{width:83.3333%;*width:83.3023%}.pure-u-xl-7-8,.pure-u-xl-21-24{width:87.5%;*width:87.469%}.pure-u-xl-11-12,.pure-u-xl-22-24{width:91.6667%;*width:91.6357%}.pure-u-xl-23-24{width:95.8333%;*width:95.8023%}.pure-u-xl-1,.pure-u-xl-1-1,.pure-u-xl-5-5,.pure-u-xl-24-24{width:100%}} \ No newline at end of file
diff --git a/book/src/main/resources/images/Dropdown.png b/book/src/main/resources/images/Dropdown.png
new file mode 100644
index 0000000..c28a60d
--- /dev/null
+++ b/book/src/main/resources/images/Dropdown.png
Binary files differ
diff --git a/book/src/main/resources/images/Hello World Console.png b/book/src/main/resources/images/Hello World Console.png
new file mode 100644
index 0000000..3b83de3
--- /dev/null
+++ b/book/src/main/resources/images/Hello World Console.png
Binary files differ
diff --git a/book/src/main/resources/images/Hello World White.png b/book/src/main/resources/images/Hello World White.png
new file mode 100644
index 0000000..f4d3774
--- /dev/null
+++ b/book/src/main/resources/images/Hello World White.png
Binary files differ
diff --git a/book/src/main/resources/images/Hello World.png b/book/src/main/resources/images/Hello World.png
new file mode 100644
index 0000000..d333b5f
--- /dev/null
+++ b/book/src/main/resources/images/Hello World.png
Binary files differ
diff --git a/book/src/main/resources/images/IntelliJ Hello.png b/book/src/main/resources/images/IntelliJ Hello.png
new file mode 100644
index 0000000..766df74
--- /dev/null
+++ b/book/src/main/resources/images/IntelliJ Hello.png
Binary files differ
diff --git a/book/src/main/resources/images/Scalatags Downloads.png b/book/src/main/resources/images/Scalatags Downloads.png
new file mode 100644
index 0000000..4ff118c
--- /dev/null
+++ b/book/src/main/resources/images/Scalatags Downloads.png
Binary files differ
diff --git a/book/src/main/scala/book/Book.scala b/book/src/main/scala/book/Book.scala
index 909c46e..c41ab15 100644
--- a/book/src/main/scala/book/Book.scala
+++ b/book/src/main/scala/book/Book.scala
@@ -123,9 +123,9 @@ object Book {
* }
*/
- def ref(filepath: String, identifier: String = "", end: String = "", indented: Boolean = true) = {
+ def ref(filepath: String, start: String = "", end: String = "\n") = {
- val lang = filepath.split('.').last match{
+ val lang = filepath.split('.').last match {
case "js" => "javascript"
case "scala" => "scala"
case "sbt" => "scala"
@@ -138,35 +138,25 @@ object Book {
val lines = io.Source.fromFile(filepath).getLines().toVector
- val blob = if (identifier == ""){
- lines.mkString("\n")
- }else {
- val firstLine = lines.indexWhere(_.contains(identifier))
- val whitespace = lines(firstLine).indexWhere(!_.isWhitespace)
- val things =
- lines.drop(firstLine + 1)
- .takeWhile{ x =>
- if (end == "") {
- val firstCharIndex = x.indexWhere(!_.isWhitespace)
- firstCharIndex == -1 || firstCharIndex >= whitespace + (if (indented) 1 else 0)
- }else{
- !x.contains(end)
- }
- }
-
- val stuff =
- if (!indented) {
- things
- } else {
- val last = lines(firstLine + things.length + 1)
- if (last.trim.toSet subsetOf "}])".toSet) {
- lines(firstLine) +: things :+ last
- } else {
- lines(firstLine) +: things
- }
- }
- stuff.map(_.drop(whitespace)).mkString("\n")
+ def indent(line: String) = line.takeWhile(_.isWhitespace).length
+ println(lines)
+ println(start)
+
+ val startLine = lines.indexWhere(_.contains(start))
+ if (startLine == -1){
+ throw new Exception("Can't find marker: " + start)
}
+ val whitespace = indent(lines(startLine))
+ val endLine = lines.indexWhere(
+ line => line.contains(end) || (indent(line) < whitespace && line.trim != ""),
+ startLine
+ )
+ val sliced =
+ if (endLine == -1) lines.drop(startLine)
+ else lines.slice(startLine, endLine)
+ val blob = sliced.map(_.drop(whitespace)).mkString("\n")
+
+
pre(code(cls:=lang + " highlight-me", blob))
}
}
diff --git a/examples/src/main/scala/Clock.scala b/examples/src/main/scala/Clock.scala
new file mode 100644
index 0000000..1db7c23
--- /dev/null
+++ b/examples/src/main/scala/Clock.scala
@@ -0,0 +1,48 @@
+
+import org.scalajs.dom
+import scala.scalajs.js.annotation.JSExport
+import scalajs.js
+@JSExport
+object Clock extends{
+ @JSExport
+ def main(canvas: dom.HTMLCanvasElement) = {
+ /*setup*/
+ val renderer = canvas.getContext("2d")
+ .asInstanceOf[dom.CanvasRenderingContext2D]
+
+ canvas.width = canvas.parentElement.clientWidth
+ canvas.height = canvas.parentElement.clientHeight
+
+ val gradient = renderer.createLinearGradient(
+ canvas.width / 2 - 100, 0, canvas.width/ 2 + 100, 0
+ )
+ gradient.addColorStop(0,"red")
+ gradient.addColorStop(0.5,"green")
+ gradient.addColorStop(1,"blue")
+ renderer.fillStyle = gradient
+ //renderer.fillStyle = "black"
+
+ renderer.textAlign = "center"
+ renderer.textBaseline = "middle"
+
+ /*code*/
+ def render() = {
+ val date = new js.Date()
+ renderer.clearRect(
+ 0, 0, canvas.width, canvas.height
+ )
+
+ renderer.font = "75px sans-serif"
+ renderer.fillText(
+ Seq(
+ date.getHours(),
+ date.getMinutes(),
+ date.getSeconds()
+ ).mkString(":"),
+ canvas.width / 2,
+ canvas.height / 2
+ )
+ }
+ dom.setInterval(render _, 1000)
+ }
+} \ No newline at end of file
diff --git a/examples/src/main/scala/FlappyLine.scala b/examples/src/main/scala/FlappyLine.scala
new file mode 100644
index 0000000..92583b5
--- /dev/null
+++ b/examples/src/main/scala/FlappyLine.scala
@@ -0,0 +1,105 @@
+
+import org.scalajs.dom
+import scala.scalajs.js.annotation.JSExport
+import scala.util.Random
+import scalajs.js
+
+@JSExport
+object FlappyLine extends{
+ @JSExport
+ def main(canvas: dom.HTMLCanvasElement) = {
+ /*setup*/
+
+ val renderer = canvas.getContext("2d")
+ .asInstanceOf[dom.CanvasRenderingContext2D]
+
+ canvas.width = canvas.parentElement.clientWidth
+ canvas.height = 400
+
+ renderer.font = "50px sans-serif"
+ renderer.textAlign = "center"
+ renderer.textBaseline = "middle"
+
+ /*variables*/
+ val obstacleGap = 200 // Gap between the approaching obstacles
+ val holeSize = 50 // Size of the hole in each obstacle you must go through
+ val gravity = 0.1 // Y acceleration of the player
+
+ var playerY = canvas.height / 2.0 // Y position of the player; X is fixed
+ var playerV = 0.0 // Y velocity of the player
+ // Whether the player is dead or not;
+ // 0 means alive, >0 is number of frames before respawning
+ var dead = 0
+ // What frame this is; used to keep track
+ // of where the obstacles should be positioned
+ var frame = -50
+ // List of each obstacle, storing only the Y position of the hole.
+ // The X position of the obstacle is calculated by its position in the
+ // queue and in the current frame.
+ val obstacles = collection.mutable.Queue.empty[Int]
+
+
+ def runLive() = {
+ frame += 2
+
+ // Create new obstacles, or kill old ones as necessary
+ if (frame >= 0 && frame % obstacleGap == 0)
+ obstacles.enqueue(Random.nextInt(canvas.height - 2 * holeSize) + holeSize)
+ if (obstacles.length > 7){
+ obstacles.dequeue()
+ frame -= obstacleGap
+ }
+
+ // Apply physics
+ playerY = playerY + playerV
+ playerV = playerV + gravity
+
+
+ // Render obstacles, and check for collision
+ renderer.fillStyle = "darkblue"
+ for((holeY, i) <- obstacles.zipWithIndex){
+ val holeX = i * obstacleGap - frame + canvas.width
+ renderer.fillRect(holeX, 0, 5, holeY - holeSize)
+ renderer.fillRect(
+ holeX, holeY + holeSize, 5, canvas.height - holeY - holeSize
+ )
+ if (math.abs(holeX - canvas.width/2) < 5 &&
+ math.abs(holeY - playerY) > holeSize){
+ dead = 50
+ }
+ }
+
+ // Render player
+ renderer.fillStyle = "darkgreen"
+ renderer.fillRect(canvas.width / 2 - 5, playerY - 5, 10, 10)
+
+ // Check for out-of-bounds player
+ if (playerY < 0 || playerY > canvas.height){
+ dead = 50
+ }
+ }
+
+
+ def runDead() = {
+ playerY = canvas.height / 2
+ playerV = 0
+ frame = -50
+ obstacles.clear()
+ dead -= 1
+ renderer.fillStyle = "darkred"
+ renderer.fillText("You Died", canvas.width / 2, canvas.height / 2)
+ }
+
+ def run() = {
+ renderer.clearRect(0, 0, canvas.width, canvas.height)
+ if (dead > 0) runDead()
+ else runLive()
+ }
+
+ dom.setInterval(run _, 20)
+
+ canvas.onclick = (e: dom.MouseEvent) => {
+ playerV -= 5
+ }
+ }
+} \ No newline at end of file
diff --git a/examples/src/main/scala/ScratchPad.scala b/examples/src/main/scala/ScratchPad.scala
new file mode 100644
index 0000000..225e567
--- /dev/null
+++ b/examples/src/main/scala/ScratchPad.scala
@@ -0,0 +1,38 @@
+
+import org.scalajs.dom
+
+import scala.scalajs.js.annotation.JSExport
+
+@JSExport
+object ScratchPad extends{
+ @JSExport
+ def main(canvas: dom.HTMLCanvasElement) = {
+ /*setup*/
+ val renderer = canvas.getContext("2d")
+ .asInstanceOf[dom.CanvasRenderingContext2D]
+
+ canvas.width = canvas.parentElement.clientWidth
+ canvas.height = canvas.parentElement.clientHeight
+
+ renderer.fillStyle = "#f8f8f8"
+ renderer.fillRect(0, 0, canvas.width, canvas.height)
+
+ /*code*/
+ renderer.fillStyle = "black"
+ var down = false
+ canvas.onmousedown = (e: dom.MouseEvent)=>{
+ down = true
+ }
+ canvas.onmouseup = (e: dom.MouseEvent)=>{
+ down = false
+ }
+ canvas.onmousemove = (e: dom.MouseEvent)=>{
+ val rect = canvas.getBoundingClientRect()
+ if (down) renderer.fillRect(
+ e.clientX - rect.left,
+ e.clientY - rect.top,
+ 10, 10
+ )
+ }
+ }
+} \ No newline at end of file
diff --git a/examples/src/main/scala/Example.scala b/examples/src/main/scala/Splash.scala
index 3eba6fa..1dcc528 100644
--- a/examples/src/main/scala/Example.scala
+++ b/examples/src/main/scala/Splash.scala
@@ -4,7 +4,7 @@ import org.scalajs.dom
import scala.scalajs.js.annotation.JSExport
@JSExport
-object Example extends{
+object Splash extends{
@JSExport
def main(canvas: dom.HTMLCanvasElement) = {
@@ -21,7 +21,6 @@ object Example extends{
def h = canvas.height
def w = canvas.width
- /*example*/
var x = 0.0
type Graph = (String, Double => Double)
val graphs = Seq[Graph](