-
Notifications
You must be signed in to change notification settings - Fork 0
/
to-infinity-and-beyond.html
1026 lines (918 loc) · 32.4 KB
/
to-infinity-and-beyond.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>Javascripting, With Style</title>
<meta name="author" content="(Jack Viers)"/>
<link rel="stylesheet" href="http://localhost:8000/css/reveal.min.css"/>
<link rel="stylesheet" href="http://localhost:8000/css/theme/moon.css" id="theme"/>
<link rel="stylesheet" href="../lib/css/zenburn.css"/>
<!-- If the query includes 'print-pdf', include the PDF print sheet -->
<script>
if( window.location.search.match( /print-pdf/gi ) ) {
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = 'http://localhost:8000/css/print/pdf.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
}
</script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
<meta name="description" content="Elasticsearch Introduction.">
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<h1>Javascripting, With Style</h1>
<h2>Jack Viers</h2>
<h2><a href="mailto:jack.viers@banno.com">jack.viers@banno.com</a>, <a href="mailto:@jackviers">@jackviers</a></h2>
<h2></h2></section>
<section>
<h2>Table of Contents</h2><ul>
<li>
<a href="#sec-1">Life in a post-js world</a>
</li>
<li>
<a href="#sec-2">Why ALT-JS</a>
</li>
<li>
<a href="#sec-3">Levels of Alt</a>
</li>
<li>
<a href="#sec-4">Javascript Can run Anything</a>
</li>
</ul>
</section>
<section id="sec-1" >
<h2>Life in a post-js world</h2>
<img src="http://whyirundisney.files.wordpress.com/2012/09/to-infinity-and-beyond.jpg?w=605"/>
<p style="font-size: .5em"><span >Image Credit: - http://whyirundisney.files.wordpress.com/2012/09/to-infinity-and-beyond.jpg?w=605</p>
<aside class="notes">
<p>
Javascript is the runtime of the web. Interesting stuff exists. We're devs, we live in the future.
</p>
</aside>
</section>
<section id="sec-2" >
<h2>Why ALT-JS</h2>
<center><blockquote class="twitter-tweet" lang="en"><p>"Tests = ∃x. Types = ∀x." -- <a href="https://twitter.com/psnively">@psnively</a> and <a href="https://twitter.com/pandamonial">@pandamonial</a></p>— Jack Viers (@jackviers) <a href="https://twitter.com/jackviers/statuses/367102573460729856">August 13, 2013</a></blockquote><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script></center>
<ul><li><a href="http://worrydream.com/LadderOfAbstraction/" target="_blank"> Up and Down the Ladder of Abstraction - Bret Victor</a></li>
<li><a href="http://coffeescript.org/#overview" target="_blank">Type less do more - Coffescript</a></li>
<li><a href="http://opalang.org/#code" target="_blank">DSLs - Opa</a></li>
<li><a href="https://www.destroyallsoftware.com/talks/wat" target="_blank">WAT</a></li>
<li>And much more!</li></ul>
<aside class="notes">
<p>
Everybody that knows me knows I am heavy into js. So why all this fuss about js being the runtime implementation language of the web?
There are idiosyncrasies that don't make sense. No typechecking means errors show up at runtime. DSLs provide layers of abstraction.
Lots of boilerplate. Functional style. OO style. And much more.
</p>
</aside>
</section>
<section id="sec-3" >
<h2>Levels of Alt</h2>
<ul class="org-ul">
<li>Industrial Strength
</li>
<li>DSLs
</li>
<li>Experiments
</li>
</ul>
<aside class="notes">
<p>
There are really three different levels of Alt-js languages.
The first are industrial-strength, ready for production use languages.
The second are also production ready Domain Specific Languages.
The third level is experimental languages where anything, and I mean anything, goes.
</p>
</aside>
</section>
<section>
<section id="sec-3-1" >
<h3>Industrial Strength Languages</h3>
<ul class="org-ul">
<li>Coffeescript
</li>
<li>Dart
</li>
<li>Typescript
</li>
<li>Clojurescript
</li>
</ul>
</section>
<section id="sec-3-1-1" >
<h4>Coffeescript</h4>
<ul class="org-ul">
<li><a href="http://coffeescript.org">http://coffeescript.org</a>
</li>
<li>Macro language for js
</li>
<li>Dynamic, functional/OO hybrid
</li>
<li>Makes js a little nicer by eliminating boilerplate
</li>
<li>Seamless js interop
</li>
<li>Compiled
</li>
</ul>
<aside class="notes">
<p>
Coffeescript is really a macro-language for js.
It is js with different syntax that helps you avoid gotchas and type less.
Interaction with js in CS is seamless, you just call a function.
It is a little "prettier" and looks more functional.
</p>
</aside>
<pre><code data-trim class="coffeescript">
arr = [
1
2
3
4
5
6
]
count = (num) -> "#{num}! #{num} wonderful stars! Ah, ah, ah."
(count stars for stars in arr when star % 2 is 0).join ""
</code></pre>
</section>
<section id="sec-3-1-2" >
<h4>Dart</h4>
<ul class="org-ul">
<li><a href="https://www.dartlang.org/">https://www.dartlang.org/</a>
</li>
<li>Optionally typed
</li>
<li>Java/JS syntax hybrid
</li>
<li>Modular
</li>
<li>HOFs and Collections
</li>
<li>Annotations
</li>
<li>Interpreted and Compiled
</li>
</ul>
<aside class="notes">
<p>
Dart is an optionally typed js superset
Syntax is a mix of Java and Js
Designed for development scalability
Supports annotations (for custom html extensions and what not)
It can be both interpreted in browsers supporting it and compiled.
</p>
</aside>
<pre><code data-trim class="dart">
import 'dart:math' show Random; // Import a class from a library.
void main() { // The app starts executing here.
print(new Die(n: 12).roll()); // Print a new object's value. Chain method calls.
}
class Die { // Define a class.
static Random shaker = new Random(); // Define a class variable.
int sides, value; // Define instance variables.
String toString() => '$value'; // Define a method using shorthand syntax.
Die({int n: 6}) { // Define a constructor.
if (4 <= n && n <= 20) {
sides = n;
} else {
throw new ArgumentError(/* */); // Support for errors and exceptions.
}
}
int roll() { // Define an instance method.
return value = shaker.nextInt(sides); // Get a random number.
}
}</code></pre>
</section>
<section id="sec-3-1-3" >
<h4>Typescript</h4>
<ul class="org-ul">
<li><a href="http://www.typescriptlang.org/">http://www.typescriptlang.org/</a>
</li>
<li>Optionally typed
</li>
<li>Compiled
</li>
<li>JS superset
</li>
<li>JS Interop (with Definitely typed) <a href="https://github.com/borisyankov/DefinitelyTyped">https://github.com/borisyankov/DefinitelyTyped</a>
</li>
</ul>
<aside class="notes">
<p>
Typescript is an optionally typed js language by Microsoft
Basically MS answer to dart.
REALLY nice.
</p>
</aside>
<pre><code data-trim class="typescript">
export class Greeter
{
element: HTMLElement;
span: HTMLElement;
timerToken: number;
constructor (element: HTMLElement)
{
this.element = element;
this.element.innerText += "The time is: ";
this.span = document.createElement('span');
this.element.appendChild(this.span);
this.span.innerText = new Date().toUTCString();
}
start()
{
this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
}
stop()
{
clearTimeout(this.timerToken);
}
}
</code></pre>
</section>
<section id="sec-3-1-4" >
<h4>Clojurescript</h4>
<ul class="org-ul">
<li>Lisp variant
</li>
<li>JS Interop
</li>
<li>Based on Clojure - <a href="http://clojure.org/">http://clojure.org/</a>
</li>
<li>Functional
</li>
<li>Nice async libraries
</li>
<li>Optimizing compiler
</li>
<li>Compiled
</li>
</ul>
<aside class="notes">
<p>
Here's where we start to go wider afield
Clojurescript is a js run variant of clojure, which is a jvm lisp
It is a functional language, with custom integrations for js interop.
It has nice asynchronous (event, out of order execution) libraries.
It is compiled and optimized using the Google Closure compiler.
Very powerful, lifts the level of abstraction over the previous three.
</p>
</aside>
<pre><code data-trim class="clojurescript">
(ns dom.test
(:require [clojure.browser.event :as event]
[clojure.browser.dom :as dom]))
(defn log [& args]
(.log js/console (apply pr-str args)))
(defn log-obj [obj]
(.log js/console obj))
(defn log-listener-count []
(log "listener count: " (event/total-listener-count)))
(def source (dom/get-element "source"))
(def destination (dom/get-element "destination"))
(dom/append source
(dom/element "Testing me ")
(dom/element "out!"))
(def success-count (atom 0))
(log-listener-count)
(event/listen source
:click
(fn [e]
(let [i (swap! success-count inc)
e (dom/element :li
{:id "testing"
:class "test me out please"}
"It worked!")]
(log-obj e)
(log i)
(dom/append destination
e))))
(log-obj (dom/element "Text node"))
(log-obj (dom/element :li))
(log-obj (dom/element :li {:class "foo"}))
(log-obj (dom/element :li {:class "bar"} "text node"))
(log-obj (dom/element [:ul [:li :li :li]]))
(log-obj (dom/element :ul [:li :li :li]))
(log-obj (dom/element :li {} [:ul {} [:li :li :li]]))
(log-obj (dom/element [:li {:class "baz"} [:li {:class "quux"}]]))
(log-obj source)
(log-listener-count)
</pre></code>
</section>
</section>
<section>
<section id="sec-3-2" >
<h3>DSLs</h3>
<ul class="org-ul">
<li>Templating – Handlebars, etc.
</li>
<li>Frameworks – Opa and Angular
</li>
</ul>
<aside class="notes">
<p>
DSLs include templating languages and html compilers like Angular, and server/client hybrids like meteor and opa.
Typically, some part of the DSL is parsed into the js namespace and extensions are written in js using
some kind of pluggable architecture.
</p>
</aside>
</section>
<section id="sec-3-2-1" >
<h4>Handlebars</h4>
<ul class="org-ul">
<li><a href="http://handlebarsjs.com/">http://handlebarsjs.com/</a>
</li>
<li>Templating language that compiles to js functions
</li>
<li>Complete grammar
</li>
<li>Extensible via js functions called Helpers
</li>
</ul>
<aside class="notes">
<p>
Handlebars is a DSL for outputting html strings.
Expressions can be entered using double-brackets.
Expressions can be altered using helper functions defined in js and made known to
the handlebars compiler at compile time. fullname is a function helper here.
Object literals are passed that contain the names required by the template to the
templating engine, and the values are interpolated into the string.
Output is a js string that can be used to insert into the dom.
</p>
</aside>
<pre><code data-trim class="html">
<div class="post">
<h1>By {{fullName author}}</h1>
<div class="body">{{body}}</div>
<h1>Comments</h1>
{{#each comments}}
<h2>By {{fullName author}}</h2>
<div class="body">{{body}}</div>
{{/each}}
</div>
</code></pre>
</section>
<section id="sec-3-2-2" >
<h4>Opa</h4>
<ul class="org-ul">
<li>Typesafe, Inferred
</li>
<li>Dual runtime – server & client
</li>
<li>Rich
</li>
<li>Functional/OO Hybrid
</li>
</ul>
<aside class="notes">
<p>
Skipping over angular, the HTML compiler here because you're probably familiar with it.
Opa is a hybrid server-side client-side framework for rich web apps.
It includes a type inferred OO/Functional paradigm language that lifts the level of abstraction
from pure js apps. Seamless js interop is available.
Runs on client and server – one language to rule them all.
Supports many functional features like object destructuring and pattern matching, shown here.
URL is a Type, and it has properties that can be matched, like path. This guides decision logic.
</p>
</aside>
<pre><code data-trim class="opa">
function start(url) {
match (url) {
case {path: {nil} ... } :
{ display("Hello") };
case {path: path ...} :
{ display(String.concat("::", path)) };
}
}
</pre></code>
</section>
</section>
<section>
<section id="sec-3-3" >
<h3>Experiments</h3>
<ul class="org-ul">
<li>Completely different languages than JS
</li>
<li>ASMjs
</li>
<li>GHCjs
</li>
<li>Scal
</li>
</ul>
<aside class="notes">
<p>
These are the experimental left field compile to js languages.
They often are of an entirely different paradigm than js, though they may look similar.
They are not in heavy production use, but are usable. May take some work to get them to play nice.
</p>
</aside>
</section>
<section id="sec-3-3-1" >
<h4>ASMjs</h4>
<ul class="org-ul">
<li><a href="http://asmjs.org/spec/latest/">http://asmjs.org/spec/latest/</a>
</li>
<li>Type-safe, type annotated optimizable subset of js
</li>
<li>REALLY FAST
</li>
<li>Intended to be a better compile target for ALT-JS langs (C++ via llvm for example)
</li>
</ul>
<aside class="notes">
<p>
ASM js is a better js compile target, since its js can be optimized heavily at runtime.
Type safe.
Allows for a target for to js compilers that is stricter than js proper.
Included here because I think this will be the lang most to-js langs target in the future.
</p>
</aside>
<pre><code data-trim class="JavaScript">
function DiagModule(stdlib) {
"use asm";
var sqrt = stdlib.Math.sqrt;
function square(x) {
x = +x;
return +(x*x);
}
function diag(x, y) {
x = +x;
y = +y;
return +sqrt(square(x) + square(y));
}
return { diag: diag };
}
var fast = DiagModule(window); // produces AOT-compiled version
console.log(fast.diag(3, 4));
</code></pre>
</section>
<section id="sec-3-3-2" >
<h4>GHC Js</h4>
<ul class="org-ul">
<li>Haskell compiled to Javascript
</li>
<li>Yes, Haskell
</li>
<li>JS interop using FFI (Foreign Function Interface)
</li>
<li>Just write haskell
</li>
</ul>
<aside class="notes">
<p>
If you hate dynamic languages, need good libraries, and love functional code, use Haskell.
Pretty much the antithesis to js, and at the cutting edge of useful pl out there.
Compiles with ghc, and can up the type safety to maximum.
Takes some work (that is mostly done in available libraries) to work with traditional js libraries.
Uses unsafe FFI to call out to js.
Who says you can't do a gui in Haskell?
</p>
</aside>
<pre><code data-trim class="haskell">
{-# LANGUAGE CPP, TemplateHaskell, QuasiQuotes, ScopedTypeVariables, NoMonomorphismRestriction, Rank2Types, DeriveDataTypeable #-}
module Main (
main, lazyLoad_freecell
) where
import Prelude hiding ((!!))
import Control.Monad.Trans ( liftIO )
import System.IO (stderr, hPutStrLn, stdout, hFlush)
import GHCJS.DOM (runWebGUI, postGUISync, postGUIAsync, webViewGetDomDocument)
import GHCJS.DOM.Document
(documentCreateElement, documentGetElementById, documentGetBody)
import GHCJS.DOM.HTMLElement
(htmlElementSetInnerText, htmlElementSetInnerHTML)
import Data.Text.Lazy (Text, unpack)
import Text.Blaze.Html.Renderer.Text (renderHtml)
import Text.Hamlet (shamlet)
import Text.Blaze.Html (Html)
import GHCJS.DOM.Types
(Node(..), castToHTMLElement, castToHTMLDivElement,
castToHTMLInputElement)
import Control.Applicative ((<$>))
import GHCJS.DOM.Element
(elementGetStyle, elementSetAttribute, elementOnclick,
elementOnkeypress, elementOnkeyup, elementOnkeydown, elementFocus)
import GHCJS.DOM.HTMLInputElement
(htmlInputElementGetValue)
import Control.Concurrent
(tryTakeMVar, takeMVar, threadDelay, putMVar, forkIO, newEmptyMVar, forkIOWithUnmask)
import Control.Monad (when, forever)
import GHCJS.DOM.EventM
(mouseShiftKey, mouseCtrlKey)
import GHCJS.DOM.Node
(nodeInsertBefore, nodeAppendChild)
import GHCJS.DOM.CSSStyleDeclaration
(cssStyleDeclarationSetProperty)
import Language.Javascript.JSaddle
(strToText, valToStr, JSNull(..), deRefVal, valToObject, js, JSF(..), js1, js4, jsg,
valToNumber, (!), (!!), (#), (<#), global, eval, fun, val, array, new, runJSaddle_,
valToText, MakeValueRef(..), JSValue(..), call, JSM(..), JSValueRef)
import Control.Monad.Reader (ReaderT(..))
import qualified Data.Text as T (unpack, pack)
import FRP.Sodium
import Engine
import Freecell -- What could this be for ? :-)
#ifdef jmacro_MIN_VERSION
import Language.Javascript.JSC
(evalJME, evalJM)
import Language.Javascript.JMacro
(jmacroE, jLam, jmacro, renderJs, ToJExpr(..), JStat(..))
#endif
import Language.Haskell.TH (Exp(..), Lit(..))
import System.IO.Unsafe (unsafePerformIO)
import Control.Lens ((^.))
import Control.Exception (throwTo, catch, SomeException, Exception)
import Data.Typeable (Typeable)
data NewValueException = NewValueException deriving (Show, Typeable)
instance Exception NewValueException
main = do
-- Running a GUI creates a WebKitGtk window in native code,
-- but just returns the browser window when compiled to JavaScript
runWebGUI $ \ webView -> do
-- WebKitGtk provides the normal W3C DOM functions
Just doc <- webViewGetDomDocument webView
Just body <- documentGetBody doc
-- Lets use some Hamlet to replace HTerm with some HTML
Just div <- fmap castToHTMLDivElement <$> documentCreateElement doc "div"
htmlElementSetInnerHTML div . unpack $ renderHtml [shamlet|$newline always
....
|]
-- Now we need to add this div to the document body
-- If we are in the browser then let's shrink the terminal window to make room
mbTerminal <- fmap castToHTMLDivElement <$> documentGetElementById doc "terminal"
case mbTerminal of
Just terminal -> do
Just style <- elementGetStyle terminal
cssStyleDeclarationSetProperty style "height" "200px" ""
cssStyleDeclarationSetProperty style "position" "absolute" ""
cssStyleDeclarationSetProperty style "bottom" "0" ""
nodeInsertBefore body (Just div) (Just terminal)
_ -> do
nodeAppendChild body (Just div)
-- We can get the elements by ID
Just numInput <- fmap castToHTMLInputElement <$> documentGetElementById doc "num"
Just prime <- fmap castToHTMLDivElement <$> documentGetElementById doc "prime"
Just heading <- fmap castToHTMLElement <$> documentGetElementById doc "heading"
-- You can also use your favorite JavaScript libraries
-- Run JavaScript using postGUISync to make sure it runs on the Gtk thread.
-- This should avoid threading issues when using WebKitGTK+.
let runjs = postGUIAsync . runJSaddle_ webView
runjs $ do
-- Declare the javascript property getters we will be using
document <- jsg "document"
let getElementById = js1 "getElementById"
getContext = js1 "getContext"
fillStyle = js "fillStyle"
fillRect :: Double -> Double -> Double -> Double -> JSF
fillRect = js4 "fillRect"
-- var canvas = document.getElementById("canvas")
canvas <- document ^. getElementById "canvas"
-- var ctx = canvas.getContext("2d")
ctx <- canvas ^. getContext "2d"
liftIO . forkIO . forever $ do
runjs $ do
-- ctx.fillStyle = "#00FF00"
-- ctx.fillRect( 0, 0, 150, 75 )
ctx ^. fillStyle <# "#00FF00"
ctx ^. fillRect 0 0 10 10
liftIO $ threadDelay 500000
runjs $ do
ctx ^. fillStyle <# "#FF0000"
ctx ^. fillRect 0 0 10 10
liftIO $ threadDelay 500000
-- We don't want to work on more than on prime number test at a time.
-- So we will have a single worker thread and a queue with just one value.
next <- newEmptyMVar
ready <- newEmptyMVar
worker <- forkIOWithUnmask $ \unmask -> forever $ (do
putMVar ready ()
n <- takeMVar next
postGUISync $ do
htmlElementSetInnerHTML prime $ "Thinking about " ++ n
unmask . postGUISync $ do
htmlElementSetInnerHTML prime . unpack $ validatePrime n)
`catch` \ (e :: SomeException) -> print e
-- Something to set the next work item
let setNext = do
n <- htmlInputElementGetValue numInput
tryTakeMVar next -- Discard existing next item
throwTo worker NewValueException
takeMVar ready
putMVar next n
-- Lets wire up some events
elementOnkeydown numInput (liftIO setNext)
elementOnkeyup numInput (liftIO setNext)
elementOnkeypress numInput (liftIO setNext)
putStrLn "This is stdout."
hPutStrLn stderr "This is stderr."
putStrLn "You can get input from stdin."
putStrLn "(we also support threads and MVar, so you can wait 20 seconds if you don't have a keyboard)"
putStr "What is your name ? "
hFlush stdout
-- We can use MVars and threads
nameMVar <- newEmptyMVar
-- Wait for input on one thread
forkIO $ do
line <- getLine
putMVar nameMVar line
-- Wait for 20s on another
forkIO $ do
threadDelay 20000000
putMVar nameMVar "World"
-- Get the first result
forkIO $ do
name <- takeMVar nameMVar
postGUISync $ do
htmlElementSetInnerText heading $ "Hello " ++ name ++ " and Welcome GHCJS"
-- Set the input focus to the prime number test
elementFocus numInput
-- Now stdout is free let's try some more JavaScript stuff...
runjs $ do
-- Some helper functions to print JS values
let log v = deRefVal v >>= (liftIO . print)
logNumber v = valToNumber v >>= (liftIO . print)
logText v = valToText v >>= (liftIO . print)
logList v = mapM deRefVal v >>= (liftIO . print)
-- Add Java Script logText function that calls the haskell logText
jsLogText <- jsg "logText" <# fun (\_f _this [s] -> logText s)
-- logText("Hello World")
jsLogText # ["Hello World"]
-- console.log(Math.sin(1))
math <- jsg "Math"
let sin = js1 "sin"
math ^. sin (1::Double) >>= logNumber
-- (new Date()).toString()
-- (new Date(2013,1,1)).toString()
date <- jsg "Date"
new date () >>= logText
new date [2013,1,1::Double] >>= logText
-- eval("logText('Hello'); 1+2")
eval "logText('Hello'); 1+2" >>= log
-- logText(["Test", navigator.appVersion.length].length)
navigator <- jsg "navigator"
let appVersion = js "appVersion"
jsLength = js "length"
jsLogText # array ("Test", navigator ^. appVersion . jsLength) ^. jsLength
-- callbackToHaskell = function () { console.log(arguments); }
callBack <- jsg "callbackToHaskell" <# fun (\f this -> logList)
-- callbackToHaskell(null, undefined, true, 3.14, "Hello")
callBack # [ValNull, ValUndefined, ValBool True, ValNumber 3.14, ValString $ T.pack "List of JSValues"]
-- or
callBack # [val JSNull, val (), val True, val (3.14 :: Double), val "List of JSC JSValueRefs"]
-- or
callBack # (JSNull, (), True, (3.14 :: Double), "5-tuple")
-- or
eval "callbackToHaskell(null, undefined, true, 3.14, \"Eval\")"
#ifdef jmacro_MIN_VERSION
-- or
$([evalJM|callbackToHaskell(null, undefined, true, 3.14, "Evaled JMacro")|])
-- or
jmfunc <- $([evalJME| \ a b c d e -> callbackToHaskell(a, b, c, d, e) |])
let callJM :: (JSNull, (), Bool, Double, String) -> JSC JSValueRef = call jmfunc jmfunc
callJM (JSNull, (), True, 3.14, "Via JMacro Evaled Function")
#endif
-- var a = []; for(var i = 0; i != 10; ++i) a[i] = i; console.log(a[5]);
array ([0..10]::[Double]) !! 5 >>= log
return ()
-- What is this?
elementOnclick heading $ do
shiftIsPressed <- mouseShiftKey
when shiftIsPressed . liftIO $ lazyLoad_freecell webView doc body
return ()
-- Integer uses goog.math.Integer compiled to Javascript
isPrime :: Integer -> Bool
isPrime p = p > 1 && (all (\n -> p `mod` n /= 0)
$ takeWhile (\n -> n*n <= p) [2..])
validatePrimeMessage :: Integer -> Html
validatePrimeMessage p | isPrime p = [shamlet|$newline always
<b>Yes</b>, #{p} is a prime|]
| otherwise = [shamlet|$newline always
<b>No</b>, #{p} is not a prime|]
validatePrime :: String -> Text
validatePrime s = renderHtml $
case reads s of
[(n, "")] -> validatePrimeMessage n
_ -> [shamlet|$newline always
<b>No</b>, that is not a number|]
-- Sometimes you might have something that needs more JavaScript than everything else
-- you can tell the GHCJS linker to put its dependancies in a sparate file using
-- a lazyLoad_ prefix
{-# NOINLINE lazyLoad_freecell #-}
lazyLoad_freecell webView doc body = do
htmlElementSetInnerHTML body $
"<div style=\"position:relative;left:0px;top:0px;background-color:#e0d0ff;width:700px;height:500px\" "++
"id=\"freecell\" draggable=\"false\"></div>"
unlisten <- engine webView "freecell" =<< mkFreecell
-- Prevent finalizers running too soon
forkIO $ forever (threadDelay 1000000000) >> unlisten
return ()
</code></pre>
</section>
<section id="sec-3-3-3" >
<h4>Scalajs</h4>
<ul class="org-ul">
<li><a href="http://www.scala-js.org/">http://www.scala-js.org/</a>
</li>
<li>Scala in javascript!
</li>
<li>Good interop with js
</li>
<li>Write Scala, call js using js.Dynamic
</li>
<li>Type-safe, rich
</li>
</ul>
<aside class="notes">
<p>
Same vein as GHC js.
But for scala.
Compilers and types mean less run, crash, or test.
Nice libraries. Syntax is noiser than Haskell.
Great if your team uses scala.
Good interoperability and type safety with js libs like jquery.
Callable from js. No more [] + {} issues (unless you make an implicit conversion)
</p>
</aside>
<pre><code data-trim class="scala">
package example
import org.scalajs.dom
import scalatags.all._
import scalatags.Tags2.section
import scalatags.ExtendedString
import rx._
import rx.core.Propagator
import scala.scalajs.js.annotation.JSExport
case class Task(txt: Var[String], done: Var[Boolean])
@JSExport
object ScalaJSExample {
import Framework._
val editing = Var[Option[Task]](None)
val tasks = Var(
Seq(
Task(Var("TodoMVC Task A"), Var(true)),
Task(Var("TodoMVC Task B"), Var(false)),
Task(Var("TodoMVC Task C"), Var(false))
)
)
val filters: Map[String, Task => Boolean] = Map(
("All", t => true),
("Active", !_.done()),
("Completed", _.done())
)
val filter = Var("All")
val inputBox = new DomRef[dom.HTMLInputElement](input(
id:="new-todo",
placeholder:="What needs to be done?",
autofocus:=true
))
@JSExport
def main(): Unit = {
dom.document.body.innerHTML = Seq(
section(id:="todoapp")(
header(id:="header")(
h1("todos"),
form(
inputBox,
onsubmit <~ {
tasks() = Task(Var(inputBox.value), Var(false)) +: tasks()
inputBox.value = ""
}
)
),
section(id:="main")(
input(
id:="toggle-all",
`type`:="checkbox",
cursor:="pointer",
onclick <~ {
val target = tasks().exists(_.done() == false)
Var.set(tasks().map(_.done -> target): _*)
}
),
label(`for`:="toggle-all", "Mark all as complete"),
Rx{
dom.console.log("A")
ul(id:="todo-list")(
for(task <- tasks() if filters(filter())(task)) yield {
dom.console.log("B", task.txt())
val inputRef = new DomRef[dom.HTMLInputElement](
input(`class`:="edit", value:=task.txt())
)
li(if(task.done()) `class`:="completed" else (), if(editing() == Some(task)) `class`:="editing" else ())(
div(`class`:="view")(
"ondblclick".attr <~ {editing() = Some(task)},
input(
`class`:="toggle",
`type`:="checkbox",
cursor:="pointer",
onchange <~ {task.done() = !task.done()},
if(task.done()) checked:=true else ()
),
label(task.txt()),
button(
`class`:="destroy",
cursor:="pointer",
onclick <~ (tasks() = tasks().filter(_ != task))
)
),
form(
onsubmit <~ {
task.txt() = inputRef.value
editing() = None
},
inputRef
)
)
}
)
},
footer(id:="footer")(
span(id:="todo-count")(strong(Rx(tasks().count(!_.done()).toString)), " item left"),
Rx{
ul(id:="filters")(
for ((name, pred) <- filters.toSeq) yield {
li(a(
if(name == filter()) `class`:="selected" else (),
name,
href:="#",
onclick <~ (filter() = name)
))
}
)
},
button(
id:="clear-completed",
onclick <~ {tasks() = tasks().filter(!_.done())},
"Clear completed (", Rx(tasks().count(_.done()).toString), ")"
)
)
),
footer(id:="info")(
p("Double-click to edit a todo"),
p(a(href:="https://github.com/lihaoyi/workbench-example-app/blob/todomvc/src/main/scala/example/ScalaJSExample.scala")("Source Code")),
p("Created by ", a(href:="http://github.com/lihaoyi")("Li Haoyi"))
)
)
).mkString
}
}
</pre></code>
</section>
</section>
<section id="sec-4" >
<h2>Javascript Can run Anything</h2>
<ul class="org-ul">
<li>JS or ASMJS can be the basis for any language you like
</li>
<li>No more WAT
</li>
<li>Have fun
</li>
</ul>
</section>
</div>
</div>
<p> Created by jack.viers. </p>
<script src="http://localhost:8000/lib/js/head.min.js"></script>
<script src="http://localhost:8000/js/reveal.min.js"></script>
<script>
// Full list of configuration options available here:
// https://github.com/hakimel/reveal.js#configuration
Reveal.initialize({
controls: true,
progress: true,
history: false,
center: true,
slideNumber: true,
rollingLinks: true,
keyboard: true,
overview: true,
width: 1200, // slide width