summaryrefslogtreecommitdiff
path: root/index.html
blob: c263af8fd3baa0a7c68ef94d236829b5e5ba7d9b (plain) (blame)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
<html><head><link href="META-INF/resources/webjars/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet" /><link href="styles.css" rel="stylesheet" /><style>
.scalatex-site-Styles-headerLink{
  color: #777;
  opacity: 0.05;
  text-decoration: none;
}


.scalatex-site-Styles-hoverContainer:hover .scalatex-site-Styles-headerLink{
  color: #777;
  opacity: 0.5;
  text-decoration: none;
}
.scalatex-site-Styles-hoverContainer:hover .scalatex-site-Styles-headerLink:hover{
  opacity: 1.0;
}
.scalatex-site-Styles-hoverContainer:hover .scalatex-site-Styles-headerLink:active{
  opacity: 0.75;
}

.scalatex-site-Styles-content{
  color: #777;
  line-height: 1.6em;
  margin: 0 auto;
  margin-left: auto;
  margin-right: auto;
  max-width: 800;
  padding: 0 1em;
  padding-bottom: 50px;
}
.scalatex-site-Styles-content *{
  position: relative;
}
.scalatex-site-Styles-content p{
  text-align: justify;
}
.scalatex-site-Styles-content a:link{
  color: #37a;
  text-decoration: none;
}
.scalatex-site-Styles-content a:visited{
  color: #949;
  text-decoration: none;
}
.scalatex-site-Styles-content a:hover{
  text-decoration: underline;
}
.scalatex-site-Styles-content a:active{
  color: #000;
  text-decoration: underline;
}
.scalatex-site-Styles-content code{
  color: #000;
}

/*Workaround for bug in highlight.js IDEA theme*/
span.hljs-tag, span.hljs-symbol{
    background: none;
}
    </style><script src="scripts.js"></script><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><link rel="shortcut icon" type="image/png" href="favicon.png" /><title>Hands-on Scala.js</title><script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
    (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','//www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-27464920-4', 'auto');
  ga('send', 'pageview');
      </script></head><body><body><div>
<div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="Hands-onScala.js" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;">Hands-on Scala.js<a class=" scalatex-site-Styles-headerLink" href="#Hands-onScala.js" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /><h2 style="font-weight: 300;color: #ccc;padding: 0px;margin-top: 0px;">Writing client-side web applications in Scala</h2></div><div class=" scalatex-site-Styles-content">
  <div class="pure-g">
    <div class="pure-u-1 pure-u-md-13-24">
      <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">var x = 0.0
type Graph = (String, Double =&gt; Double)
val graphs = Seq[Graph](
  (&quot;red&quot;, sin),
  (&quot;green&quot;, x =&gt; abs(x % 4 - 2) - 1),
  (&quot;blue&quot;, x =&gt; sin(x/12) * sin(x))
).zipWithIndex
dom.setInterval(() =&gt; {
  x = (x + 1) % w; if (x == 0) clear()
  for (((color, f), i) &lt;- graphs) {
    val offset = h / 3 * (i + 0.5)
    val y = f(x / w * 75) * h / 30
    brush.fillStyle = color
    brush.fillRect(x, y + offset, 3, 3)
  }
}, 20)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/Splash.scala#L24-L40" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
    <div class="pure-u-1 pure-u-md-11-24">
      <canvas id="example0" style="display: block;overflow: scroll;"></canvas><script>Splash().main(document.getElementById('example0'))</script>
</div></div>
  <p>
    <a href="http://www.scala-js.org/">Scala.js</a> 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. This book is an introduction to Scala.js, which aims to get you from knowing-nothing about it to being relatively proficient.
</p>
  <p>
    This book contains something for all levels of experience with Scala.js: absolute beginners can get started with the <a href="#IntrotoScala.js">Intro to Scala.js</a> and <a href="#HandsOn">Hands On</a> tutorial, people who have used it before can skip ahead to the later parts of the tutorial: <a href="#MakingaCanvasApp">Making a Canvas App</a> or <a href="#InteractiveWebPages">Interactive Web Pages</a>. Intermediate users will find interest in the chapters on <a href="#CrossPublishingLibraries">Cross Publishing Libraries</a> with Scala.js or <a href="#IntegratingClient-Server">Integrating Client-Server</a>, and even experienced users will find the <a href="#InDepth">In Depth</a> documention useful. Feel free to explore the navigation bar on the left to find chapters of interest.
</p>
  <p>
    Even if we do not require any familiarity of Scala.js, this book nonetheless assumes a good amount of background knowledge: of Scala, of Javascript, and of web development as a whole. In general, you will not need deep knowledge of any of these subjects, though if you are coming in entirely without knowledge of any one of them, you'll have to be willing to spend time Google-ing things and picking things up as we go along. Someone who comes in without previous web-dev experience may miss or not-notice many of the nice touches and benefits that Scala.js brings to the table, having never done web-dev any other way,
</p>
  <p>
    Many of the code samples are taken from examples available on the book's <a href="https://github.com/lihaoyi/scala-js-book">Github Page</a>; for those code samples (e.g. the animation above), there is a <i class="fa fa-link "></i> link in the top-right corner of the snippet that you can click on to go to the original code. These come in handy if you find you need additional context around the snippet, e.g. what imports you need for the code to work, or what the complete executable example looks like.
</p>
  <p>
    This book is roughly divided into two sections:
</p>
  <ul>
    <li>
      <a href="#HandsOn">Hands On</a> 
is a set of tutorials that walks you through getting started with Scala.js. You'll build a range of small projects, from <a href="#MakingaCanvasApp">Making a Canvas App</a> to <a href="#InteractiveWebPages">Interactive Web Pages</a> to <a href="#IntegratingClient-Server">Integrating Client-Server</a>, and in the process will get a good overview of both Scala.js's use cases as well as the development experience
</li>
    <li>
      <a href="#InDepth">In Depth</a> 
is a set of detailed expositions on various parts of the Scala.js platform. Nothing in here is necessary for you to make your first demos, but as you dig deeper into the platform, you will likely need or want to care about these things so you can properly understand what's going on &quot;under the hood&quot;

</li></ul>
  <p>
    Feel free to jump ahead to either of them if you have some prior exposure to Scala.js. If not, it is best to start with the introduction...
</p></div>
<div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="IntrotoScala.js" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;">Intro to Scala.js<a class=" scalatex-site-Styles-headerLink" href="#IntrotoScala.js" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div><div class=" scalatex-site-Styles-content">
  
<p>
  Scala.js compiles Scala code to equivalent, executable Javascript. Here's the compilation of a trivial hello-world example:
</p>
<div class="pure-g">
  <div class="pure-u-1 pure-u-md-1-2">
    <pre><code class="scala scalatex-site-Styles-highlightMe">object Main extends js.JSApp{
  def main() = {
    var x = 0
    while(x &lt; 10) x += 3
    println(x)
    // 12
  }
}
</code></pre></div>
  <div class="pure-u-1 pure-u-md-1-2">
    <pre><code class="javascript scalatex-site-Styles-highlightMe">ScalaJS.c.LMain$.prototype.main__V = (function() {
  var x = 0;
  while ((x &lt; 10)) {
    x = ((x + 3) | 0)
  };
  ScalaJS.m.s_Predef$()
           .println__O__V(x)
  // 12
});
</code></pre></div></div>
<p>
  As you can see, both of the above programs do identical things: they'll count the variable <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">x</code> from <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">0</code>, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">3</code>, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">9</code>, and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">12</code> before finally printing it out. It's just that the first is written in Scala and the second is in Javascript.
</p>
<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, the browser-client only runs Javascript. Even if your back-end is all written in Scala, 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:
</p>
<ul>
  <li>
    Typo-safety due to its compiler which catches many silly errors before the code is run</li>
  <li>
    In-editor support for autocomplete, error-highlighting, refactors, and intelligent navigation</li>
  <li>
    Moderate sized compiled executables, in the 100-400kb range</li>
  <li>
    Source-maps for ease of debugging
</li></ul>
<p>
  The value proposition is that due to the superior language and tooling, writing a web application in Scala.js will result in a codebase that is more flexible and robust than an equivalent application written in Javascript. The hope is that the benefits of using Scala.js will outweigh the additional (non-trivial) messiness of adding a whole new toolchain, as compared to directly writing raw Javascript.
</p>
<p>
  I won't spend time on a detailed discussion on why Scala is good or why Javascript is bad; people's opinions on both sides can be found on the internet. The assumption is, going in, that you either already know and like Scala, or you are familiar with Javascript and are willing to try something new.
</p>
<div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="AboutJavascript" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="AboutJavascript">About Javascript<a class=" scalatex-site-Styles-headerLink" href="#AboutJavascript" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
  <p>
    Javascript is the language supported by web browsers, and is the only language available if you wish to write interactive web applications. As more and more activity moves online, the importance of web apps will only increase over time. Adobe Flash, Java Applets and Silverlight (which have historically allowed browser-client development in other languages) are all but dead: historically they have been the source of security vulnerabilities, none of them are available on the mobile browsers of Android or iOS or Windows8+. That leaves Javascript.
</p>
  <h1 id="Javascript-the-language" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Javascript-the-language" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Javascript-the-language</h1>
    <p>
      Javascript is an OK language to do small-scale development: an animation here, an on-click transition there. There are a number of warts in the language, e.g. its verbosity, and a large amount of surprising behavior, but while your code-base doesn't extend past a few hundred lines of code, you often will not mind or care.
</p>
    <p>
      However, Javascript is not an easy language to work in at scale: when your code-base extends to thousands, tens or hundreds of thousands of lines of code. The un-typed nature of the language, which is fine for small applications, becomes an issue when you are mainly working with code that you did not write.
</p>
    <p>
      In a large code-base, finding out what methods or properties a variable has is often a long chase through dozens of files to see how it ended up being passed to the current function. Refactorings, which are OK when you can just test the code to see if it works, become dangerous when your code base is large enough that &quot;just test all the code&quot; would take hours. Language-warts which are slightly annoying in small programs become a minefield in large ones: it's only a matter of time before you hit one, often in code you did-not/cannot test, resulting in breakages in production.
</p>
    <p>
      Apart from the inherent danger of the language, Javascript has another major problem: the language has left many things unspecified, yet at the same time provides the ability to emulate these things in a variety of ways. This means that rather than having a single way of e.g. defining a class and instantiating an object, there is a decade-long debate between a dozen different and equally-bad, hand-crafted alternatives. Large code-bases use third-party libraries, and most are guaranteed (purely due to how stastistics work) to do these basic things differently from your own code, making understanding these disparate code-bases (e.g. when something goes wrong) very difficult.
</p>
    <p>
      To work in Javascript, you need the discipline to limit yourself to the sane subset of the language, avoiding all the pitfalls along the way:
</p>
    <img src="images/javascript-the-good-parts-the-definitive-guide.jpg" style="margin: auto;display: block;" />

    <p>
      Even if you manage to do so, what constitutes a pitfall and what constitutes a clever-language-feature changes yearly, making it difficult to maintain cohesiveness over time. This is compounded by the fact that refactoring is difficult, and so removing &quot;unwanted&quot; patterns from a large code-base a difficult (often multi-year) process.
</p>
  <h1 id="Javascript-the-platform" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Javascript-the-platform" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Javascript-the-platform</h1>
    <p>
      However, even though Javascript-the-language is pretty bad, Javascript-the-platform has some very nice properties that make it a good target for application developers:
</p>
    <ul>
      <li>
        Zero-install distribution: just go to a URL and have the application downloaded and ready to use.</li>
      <li>
        Hyperlinks: being able to link to a particular page or item within a web app is a feature other platforms lack, and makes it much easier to cross-reference between different systems</li>
      <li>
        Sandboxed security: web applications are secure by default. No matter how sketchy the websites you visit, you can be sure that once you close the page, they're gone
</li></ul>
    <p>
      These features are all very nice to have, and together have made the web platform the success it is today. When you compare it to traditional applications, you can see the draw:</p>
    <ul>
      <li>
        Installing traditional desktop applications is usually a several-minute-long process. If something goes wrong in the installation, that often leaves a botched half-install on your computer which makes installing, uninstalling, or running the program impossible without manual surgery to excise the broken files.</li>
      <li>
        Desktop applications generally do not talk to each other at all. While on the web you can easily link a page to someone, trying to get someone to a particular screen in desktop software often involves a chain of screenshots with detailed instructions of which buttons to click at each stage.</li>
      <li>
        Desktop application security is non-existent. Install one rogue application and it can take over your computer, steal your credit card number, use your email for sending spam, and all sorts of other nasty things. Removing these for-good sometimes involves re-installing your entire operating system. Hence people are much more wary about only installing desktop software from people they &quot;trust&quot;.
</li></ul>
    <p>
      In many ways, mobile App platforms like Android and iOS have closed the gap between &quot;native&quot; and &quot;web&quot; applications. Installing a new App may take 30 seconds, you can often deep-link to certain pages within an App, and Apps have a much tighter security model than desktop software does. Nevertheless, 30 seconds is still much longer than the 0.5 seconds it takes to open a web page, deep-linking in apps is not very prevalent, and the security model still often leaves space for rogue Apps to misbehave and steal data.
</p>
  <hr />
  <p>
    Despite the problems with Javascript (and other tools like HTML an CSS, which have their own problems) the Web platform got a lot of things right, and the Desktop and Mobile platforms have a lot of catching up to do. If only we could improve upon the parts that aren't so great. This is where Scala.js comes in.
</p>
<div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="AboutScala.js" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="AboutScala.js">About Scala.js<a class=" scalatex-site-Styles-headerLink" href="#AboutScala.js" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>

  <p>
    With Scala.js, you can cross compile your Scala code to a Javascript executable that can run on all major web browsers. You get all the benefits of the web platform in terms of deployability, security, and hyperlinking, with none of the problems of writing your software in Javascript. Scala.js provides a <a href="#TheLanguage">better language</a> to do your work in, but also provides some other goodies that have in-so-far never been seen in mainstream web development: <a href="#SharingCode">shared-code</a> and <a href="#Client-ServerIntegration">client-server integration</a>.
</p>
  <h1 id="TheLanguage" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#TheLanguage" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The Language</h1>
    <p>
      At a first approximation, Scala.js provides you a sane language to do development in the web browser. This saves you from an endless stream of Javascript warts like this one:
</p>
    <pre><code class="javascript scalatex-site-Styles-highlightMe">javascript&gt; [&quot;10&quot;, &quot;10&quot;, &quot;10&quot;, &quot;10&quot;].map(parseInt)
[10, NaN, 2, 3] // WTF
</code></pre>
    <pre><code class="scala scalatex-site-Styles-highlightMe">scala&gt; List(&quot;10&quot;, &quot;10&quot;, &quot;10&quot;, &quot;10&quot;).map(parseInt)
List(10, 10, 10, 10) // Yay!

</code></pre>
    <p>
      Not only do you have an expressive language with static types, you also have great tooling with IDEs like IntelliJ and Eclipse, a rich library of standard collections, and many other modern conveniences that we take for granted but are curiously missing when working in the wild west of web development: the browser! You get all of the upside of developing for the web platform.
</p>
    <p>
      While not useful for small applications, where most of the logic is gluing together external APIs, this comes in very useful in large applications where a lot of the complexity and room-for-error is entirely internal. With larger apps, you can no longer blame browser vendors for confusing APIs that make your code terrible: these confusing APIs only lurk in the peripherals around a larger, complex application. One thing you learn working in large-ish web client-side code-bases is that the bulk of the confusion and complexity is no-one's fault but your own, as a team.
</p>
    <p>
      At this point, all of Google, Facebook, and Microsoft have all announced work on a typed variant of Javascript. These are not academic exercises: <a href="https://www.dartlang.org/">Dart</a>/<a href="https://docs.google.com/document/d/11YUzC-1d0V1-Q3V0fQ7KSit97HnZoKVygDxpWzEYW0U/edit">AtScript</a>/<a href="https://lobste.rs/s/fp9ibi/flow_facebook_s_new_javascript_type_checker">Flow</a>/<a href="http://www.typescriptlang.org/">Typescript</a> are all problems that solve a real need, that these large companies have all faced once they've grown beyond a certain size. Clearly, Javascript isn't cutting it anymore, and the convenience and &quot;native-ness&quot; of the language is more than made up for in the constant barrage of self-inflicted problems. Scala.js takes this idea and runs with it!
</p>
  <h1 id="SharingCode" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#SharingCode" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Sharing Code</h1>
    <p>
      Shared code is one of the holy-grails of web development. Traditionally the client-side code and server-side code has been written in separate languages: PHP or Perl or Python or Ruby or Java on the server, with only Javascript on the client. This means that algorithms were often implemented twice, constants copied-&amp;-pasted, or awkward Ajax calls are made in an attempt to centralize the logic in one place (the server). With the advent of Node.js in the last few years, you can finally re-use the same code on the server as you can on the client, but with the cost of having all the previously client-only <a href="#Javascript-the-language">problems with Javascript</a> now inflicted upon your server code base. Node.js expanded your range-of-options for writing shared client/server logic from &quot;Write everything twice&quot; to &quot;Write everything twice, or write everything in Javascript&quot;. More options is always good, but it's not clear which of the two choices is more painful!
</p>
    <p>
      Scala.js provides an alternative to this dilemma. With Scala.js, you can utilize the same libraries you use writing your Scala servers when writing your Scala web clients! On one end, you are sharing your templating language with <a href="https://github.com/lihaoyi/scalatags">Scalatags</a> or sharing your serialization logic with <a href="https://github.com/lihaoyi/upickle">uPickle</a>. At the other, you are sharing large, abstract libraries like <a href="https://github.com/japgolly/scalaz">Scalaz</a> or <a href="https://groups.google.com/forum/#!searchin/scala-js/shapeless/scala-js/5Sf2up0z3PU/9F9SYB0qHEcJ">Shapeless</a>.
</p>
    <p>
      Sharing code means several things:
</p>
    <ul>
      <li>
        Not having to find two libraries to do a particular common task</li>
      <li>
        Not having to re-learn two different ways of doing the exact same thing</li>
      <li>
        Not needing to implement the same algorithms twice, for the times you can't find a good library to do what you want</li>
      <li>
        Not having to debug problems caused by subtle differences in the two implementations</li>
      <li>
        Not having to resort to awkward Ajax-calls or pre-computation to avoid duplicating logic between the client and server
</li></ul>
    <p>
      Shared code doesn't just mean sharing pre-made libraries between the client and server. You can easily <a href="#CrossPublishingLibraries">publish your own libraries</a> that can be used on both Scala-JVM and Scala.js. This means that as a library author, you can at once target two completely different platforms, and (with some work) take advantage of the intricacies of each platform to optimize your library for each one. Take Scalatags as an example: as the first client-server Scala.js-ScalaJVM shared libraries, it enjoys a roughly even split of downloads from people using it on both platforms:
</p>
    <img src="images/Scalatags Downloads.png" style="width: 100%;" />

    <p>
      Shared code means that if you, as an application writer, want some logic to be available on both the client and server, you simply <a href="#AClient-ServerSetup">put it in a shared/ folder</a>, and that's the end of the discussion. No architectural patterns to follow, no clever techniques need to be involved. Shared logic, whether that means constants, functions, data structures, all the way to algorithms and entire libraries, can simply be placed in <code>shared/</code> and be instantly accessible from both your client-side web code and your server.
</p>
    <p>
      Shared code has long been the holy-grail of web development. Even now, people speak of shared code as if it were a myth. With Scala.js, shared code is the simple, boring reality. And all this while, just as importantly, you don't need to re-write your large enterprise back-end systems in a language that doesn't scale well beyond 100s of lines of code.
</p>
  <h1 id="Client-ServerIntegration" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Client-ServerIntegration" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Client-Server Integration</h1>
    <p>
      There is an endless supply of new platforms which have promised to change-the-way-we-do-web-development-forever. From old-timers like <a href="http://www.impredicative.com/ur/">Ur-Web</a>, to <a href="http://www.gwtproject.org/">GWT</a>, to Asana's <a href="https://asana.com/luna">LunaScript</a>, to more recently things like <a href="https://www.meteor.com/">Meteor.js</a>.</p>
    <p>
      One common theme in all these platforms is that their main selling point is their tight, seamless client-server integration, to the point where you can just make method calls across the client-server boundary and the platform/language/compiler figures out what to do.</p>
    <p>
      With Scala.js and Scala-JVM, such conveniences like making method calls across the client-server boundary is the <a href="#IntegratingClient-Server">boring reality</a>. Not only are the calls transparent, they are also statically checked, so any mistake in the route name or the parameters it expects, or the result type it returns to you, will be caught by the compiler long before even manual testing. It becomes <a href="#What'sLeft?">impossible to make a malformed Ajax call</a>.</p>
    <p>
      There's a lot to be said for automating things using a computer. The entire field of software engineering is basically about automating tasks that were previously done manually: accounting, banking, making travel arrangements, and all that. However, in the world of web-development, there has always been one set of tasks that has traditionally be done manually: the task of ensuring the web-clients are properly synchronized with the web-servers. Communication between the two has always been a manual, tedious, error-prone process, and mistakes often end un-noticed until something breaks in production.</p>
    <p>
      With Scala.js, like the other experimental platforms that have come before us, we attempt to provide a way forward from this manual-tedium.
</p>
  <hr />

  <p>
    In many ways, Scala.js all-at-once provides many of the traditional holy-grails of web development: People have always dreamed about doing web development in a sane, best-of-breed language that compiles to both client and server. Of not having to worry too hard about whether code goes on the client or on the server, and being able to move or share it if necessary. Of having a compiler that will verify and check that your entire system is correct.
</p>
  <p>
    Scala.js provides all these things, and much more. If you're interested enough to want to make use of Scala.js, read on!</p>

</div>
<div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="HandsOn" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;">Hands On<a class=" scalatex-site-Styles-headerLink" href="#HandsOn" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /><h2 style="font-weight: 300;color: #ccc;padding: 0px;margin-top: 0px;">Writing your first Scala.js programs</h2></div><div class=" scalatex-site-Styles-content">
  <p>
    This half of the book 
is a set of tutorials that walks you through getting started with Scala.js. You'll build a range of small projects, from <a href="#MakingaCanvasApp">Making a Canvas App</a> to <a href="#InteractiveWebPages">Interactive Web Pages</a> to <a href="#IntegratingClient-Server">Integrating Client-Server</a>, and in the process will get a good overview of both Scala.js's use cases as well as the development experience

</p>
  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="GettingStarted" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="GettingStarted">Getting Started<a class=" scalatex-site-Styles-headerLink" href="#GettingStarted" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    

<p>
  To get started with Scala.js, you will need to prepare a few things:
</p>
<ul>
  <li>
    <a href="http://www.scala-sbt.org/">sbt</a>: 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. (If you are already using Typesafe Activator, that is effectively sbt.)</li>
  <li>
    An editor for Scala: <a href="http://blog.jetbrains.com/scala/">IntelliJ Scala</a> and <a href="http://scala-ide.org/">Eclipse ScalaIDE</a> are the most popular choices and work on all platforms, though there are others.</li>
  <li>
    <a href="http://git-scm.com/">Git</a>: This is a version-control system that we will use to download and manage our Scala.js projects.</li>
  <li>
    A terminal: on OSX you have <a href="http://guides.macrumors.com/Terminal">Terminal.app</a> already installed, in Linux you have <a href="https://help.ubuntu.com/community/UsingTheTerminal">Terminal</a>, and on Windows you have <a href="http://en.wikipedia.org/wiki/Windows_PowerShell">PowerShell</a>.</li>
  <li>
    Your favorite web browser: <a href="https://www.google.com/chrome">Chrome</a> and <a href="https://www.mozilla.org/en-US/firefox">Firefox</a> are the most popular.
</li></ul>
<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>
<p>
  The quickest way to get started with Scala.js is to <code>git clone</code> <a href="https://github.com/lihaoyi/workbench-example-app">workbench-example-app</a>, go into the repository root, and run <code>sbt ~fastOptJS</code>
</p>
<pre><code class="bash scalatex-site-Styles-highlightMe">git clone https://github.com/lihaoyi/workbench-example-app
cd workbench-example-app
sbt ~fastOptJS
</code></pre>
<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
</p>
<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)
</pre>
<p>
  The line <code>Waiting for source changes...</code> 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</code> in your browser, you should see the following:

  <img src="images/Hello World.png" style="max-width: 100%;" />
</p>
<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.
</p>
<h1 id="OpeninguptheProject" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#OpeninguptheProject" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Opening up the Project</h1>

  <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</code> would look like this:
</p>
  <img src="images/IntelliJ Hello.png" style="max-width: 100%;" />

  <p>
    Let's try changing one line to change the background fill from black to white:
</p>
  <pre><code class="diff scalatex-site-Styles-highlightMe">- ctx.fillStyle = &quot;black&quot;
+ ctx.fillStyle = &quot;white&quot;
</code></pre>
  <p>
    Because we started <code>sbt ~fastOptJS</code> with the <code>~</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.
</p>
  <img src="images/Hello World White.png" style="max-width: 100%;" />

  <p>
    If you open up your browser's developer console, you'll see that the SBT log output is being mirrored there:
</p>
  <img src="images/Hello World Console.png" style="max-width: 100%;" />

  <p>
    Apart from the SBT log output (which is handled by Workbench) any <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">println</code>s in your Scala.js code will also end up in the browser console (the <code>main</code> 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.
</p>
<h1 id="TheApplicationCode" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#TheApplicationCode" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The Application Code</h1>

  <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:</p>
  
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package example
import scala.scalajs.js.annotation.JSExport
import org.scalajs.dom
import org.scalajs.dom.html
import scala.util.Random

case class Point(x: Int, y: Int){
  def +(p: Point) = Point(x + p.x, y + p.y)
  def /(d: Int) = Point(x / d, y / d)
}

@JSExport
object ScalaJSExample {
  @JSExport
  def main(canvas: html.Canvas): Unit = {
    val ctx = canvas.getContext(&quot;2d&quot;)
                    .asInstanceOf[dom.CanvasRenderingContext2D]

    var count = 0
    var p = Point(0, 0)
    val corners = Seq(Point(255, 255), Point(0, 255), Point(128, 0))

    def clear() = {
      ctx.fillStyle = &quot;black&quot;
      ctx.fillRect(0, 0, 255, 255)
    }

    def run = for (i &lt;- 0 until 10){
      if (count % 3000 == 0) clear()
      count += 1
      p = (p + corners(Random.nextInt(3))) / 2

      val height = 512.0 / (255 + p.y)
      val r = (p.x * height).toInt
      val g = ((255-p.x) * height).toInt
      val b = p.y
      ctx.fillStyle = s&quot;rgb($g, $r, $b)&quot;

      ctx.fillRect(p.x, p.y, 1, 1)
    }

    dom.setInterval(() =&gt; run, 50)
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/workbench-example-app/blob/master/src/main/scala/example/ScalaJSExample.scala#L0-L44" target="_blank"><i class="fa fa-link "></i></a></pre>

  <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 <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom</code> library and a few weird annotations. Let's pick it apart starting from the top:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">case class Point(x: Int, y: Int){
  def +(p: Point) = Point(x + p.x, y + p.y)
  def /(d: Int) = Point(x / d, y / d)
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/workbench-example-app/blob/master/src/main/scala/example/ScalaJSExample.scala#L6-L11" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Here we are defining a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Point</code> 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. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Point</code> here behaves identically as it would if you had run Scala on the JVM.
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">@JSExport
object ScalaJSExample {
  @JSExport
  def main(canvas: html.Canvas): Unit = {</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/workbench-example-app/blob/master/src/main/scala/example/ScalaJSExample.scala#L11-L15" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    This <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@JSExport</code> annotation is used to tell Scala.js that you want this method to be visible and callable from Javascript. By default, Scala.js does <a href="#FastOptimization">dead code elimination</a> 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. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@JSExport</code> is used to tell Scala.js that the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">ScalaJSExample</code> object and its <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">def main</code> 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. In this case, we are going to call this method from Javascript to start the Scala.js program.
</p>
  <p>
    Apart from this annotation, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">ScalaJSExample</code> is just a normal Scala <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">object</code>, and behaves like one in every way. Note that the main-method in this case takes a <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement">html.Canvas</a>: 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 <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Array[String]</code> and returns <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Unit</code>. 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 &quot;main&quot; entry point. It is entirely possible to define multiple exported classes and methods, and build a &quot;library&quot; using Scala.js of methods that are intended for external Javascript to use.
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val ctx = canvas.getContext(&quot;2d&quot;)
                .asInstanceOf[dom.CanvasRenderingContext2D]</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/workbench-example-app/blob/master/src/main/scala/example/ScalaJSExample.scala#L15-L18" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Here we are retrieving a handle to the canvas we will draw on using <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">document.getElementById</code>, and from it we can get a <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">CanvasRenderingContext2D</a> which we actually use to draw on it.
</p>
  <p>
    We need to perform the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">asInstanceOf</code> call because depending on what you pass to <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">getElementById</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">getContext</code>, you could be returned elements and contexts of different types. Hence we need to tell the compiler explicitly that we're expecting a <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement">html.Canvas</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">CanvasRenderingContext2D</a> back from these methods for the strings we passed in.
</p>
  <p>
    Note how the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement">html.Canvas</a> comes from the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">html</code> namespace, while the <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">CanvasRenderingContext2D</a> comes from the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom</code> namespace. Traditionally, these types are imported via their qualified names: e.g. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">html.Canvas</code> rather than just <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Canvas</code>.
</p>
  <p>
    In general, <a href="http://scala-js.github.io/scala-js-dom/">scala-js-dom</a> provides <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">org.scalajs.dom.html</code> to access the HTML element types of the browser, an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">org.scalajs.dom</code> to access other things. There are a number of other namespaces (<code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom.svg</code>, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom.idb</code>, etc.) accessible inside <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">org.scalajs.dom</code>: read the <a href="http://scala-js.github.io/scala-js-dom/">scala-js-dom docs</a> to learn more.
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def run = for (i &lt;- 0 until 10){
  if (count % 3000 == 0) clear()
  count += 1
  p = (p + corners(Random.nextInt(3))) / 2

  val height = 512.0 / (255 + p.y)
  val r = (p.x * height).toInt
  val g = ((255-p.x) * height).toInt
  val b = p.y
  ctx.fillStyle = s&quot;rgb($g, $r, $b)&quot;

  ctx.fillRect(p.x, p.y, 1, 1)
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/workbench-example-app/blob/master/src/main/scala/example/ScalaJSExample.scala#L27-L41" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    This is the part of the Scala.js program which does the real work. It runs 10 iterations of a <a href="http://en.wikipedia.org/wiki/Sierpinski_triangle#Chaos_game">small algorithm</a> that generates a Sierpinski Triangle point-by-point. The steps, as described by the linked article, are roughly:
</p>
  <ul>
    <li>
      Pick a random corner of the large-triangle</li>
    <li>
      Move your current-position <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">p</code> halfway between its current location and that corner</li>
    <li>
      Draw a dot</li>
    <li>
      Repeat
</li></ul>
  <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.
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">dom.setInterval(() =&gt; run, 50)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/workbench-example-app/blob/master/src/main/scala/example/ScalaJSExample.scala#L41-L42" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Now this is the call that actually does the useful work. All this method does is call <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom.setInterval</code>, which tells the browser to run the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">run</code> method every 50 milliseconds. As mentioned earlier, the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom.*</code> methods are simply facades to their native Javascript equivalents, and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom.setInterval</code> is <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval">no different</a>. Note how you can pass a Scala lambda to <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">setInterval</code> to have it called by the browser, where in Javascript you'd need to pass a Javascript <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">function(){...</code>}
</p>
<h1 id="TheProjectCode" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#TheProjectCode" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The Project Code</h1>

  <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</i> self contained. It's wrapped in a small SBT project that sets up the necessary dependencies and infrastructure for this application to work.
</p>
  <h2 id="project/build.sbt" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#project/build.sbt" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>project/build.sbt</h2>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">addSbtPlugin(&quot;org.scala-js&quot; % &quot;sbt-scalajs&quot; % &quot;0.6.0&quot;)

addSbtPlugin(&quot;com.lihaoyi&quot; % &quot;workbench&quot; % &quot;0.2.3&quot;)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/workbench-example-app/blob/master/project/build.sbt#L0-L3" target="_blank"><i class="fa fa-link "></i></a></pre>

    <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</code>) and the <a href="https://github.com/lihaoyi/workbench">Workbench</a> plugin, which is used to provide the auto-reload-on-change behavior and the forwarding of SBT logspam to the browser console.
</p>
    <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.

</p>
  <h2 id="build.sbt" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#build.sbt" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>build.sbt</h2>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">import com.lihaoyi.workbench.Plugin._

enablePlugins(ScalaJSPlugin)

workbenchSettings

name := &quot;Example&quot;

version := &quot;0.1-SNAPSHOT&quot;

scalaVersion := &quot;2.11.4&quot;

libraryDependencies ++= Seq(
  &quot;org.scala-js&quot; %%% &quot;scalajs-dom&quot; % &quot;0.8.0&quot;
)

bootSnippet := &quot;example.ScalaJSExample().main(document.getElementById('canvas'));&quot;

updateBrowsers &lt;&lt;= updateBrowsers.triggeredBy(fastOptJS in Compile)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/workbench-example-app/blob/master/build.sbt#L0-L20" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      The <code>build.sbt</code> project file for this application is similarly unremarkable: It includes the settings for the two SBT plugins we saw earlier, as well as boilerplate <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">name</code>/<code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">version</code>/<code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scalaVersion</code> values common to all projects.
</p>
    <p>
      Of interest is the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">libraryDependencies</code>. 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>
    <p>
      Lastly, we have two Workbench related settings: <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">bootSnippet</code> basically tells Workbench how to restart your application when a new compilation run finishes, and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">updateBrowsers</code> actually tells it to perform this application-restarting.
</p>
  <h2 id="src/main/resources/index-dev.html" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#src/main/resources/index-dev.html" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>src/main/resources/index-dev.html</h2>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="html scalatex-site-Styles-highlightMe">&lt;!DOCTYPE html&gt;
&lt;html&gt;
&lt;head&gt;
  &lt;title&gt;Example Scala.js application&lt;/title&gt;
  &lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;/&gt;
&lt;/head&gt;
&lt;body style=&quot;margin: 0px&quot;&gt;

&lt;div&gt;
    &lt;canvas style=&quot;display: block&quot; id=&quot;canvas&quot; width=&quot;255&quot; height=&quot;255&quot;/&gt;
&lt;/div&gt;

&lt;script type=&quot;text/javascript&quot; src=&quot;../example-fastopt.js&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot; src=&quot;/workbench.js&quot;&gt;&lt;/script&gt;
&lt;script&gt;
    example.ScalaJSExample().main(document.getElementById('canvas'));
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/workbench-example-app/blob/master/src/main/resources/index-dev.html#L0-L19" target="_blank"><i class="fa fa-link "></i></a></pre>

    <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 <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;script&gt;</code> tags: <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;../example-fastopt.js&quot;</code> 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. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;workbench.js&quot;</code> is the client for the Workbench plugin that connects to SBT, reloads the browser and forwards logspam to the browser console.
</p>
    <p>
      The <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">example.ScalaJSExample().main()</code> call is what kicks off the Scala.js application and starts its execution. Scala.js follows Scala semantics in that <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">object</code>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</code> is imported! We have to call the main-method first. In this case, we're passing the canvas object (attained using <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">getElementById</code>) to it so it knows where to do its thing.

</p>
  <p>
    <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">document.getElementById</code> is the exact same API that's used in normal Javascript, as documented <a href="https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById">here</a>. In fact, the entire <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">org.scalajs.dom</code> namespace (imported at the top of the file) comprises statically typed facades for the javascript APIs provided by the browser.

    <p>
      Lastly, only <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@JSExport</code>ed objects and methods can be called from Javascript. Also, although this example only exports the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">main</code> 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 &quot;library&quot; which is available to external Javascript as an API.
</p></p>
<h1 id="Publishing" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Publishing" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Publishing</h1>
  <p>
    The last thing that we'll do with our toy application is to publish it. If you look in the <code>target/scala-2.11</code> folder, you'll see the output of everything we've done so far:
</p>
  <pre><code class="bash scalatex-site-Styles-highlightMe">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
</code></pre>
  <p>
    All the <code>.class</code> and <code>.sjsir</code> 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</code> and <code>example-fastopt.js</code>. You may recognize <code>index-dev.html</code> as the file that we were navigating to in the browser earlier.
</p>
  <p>
    These two files can be extracted and published as-is: you can put them on <a href="https://pages.github.com/">Github-Pages</a>, <a href="http://docs.aws.amazon.com/gettingstarted/latest/swh/website-hosting-intro.html">Amazon Web Services</a>, or a hundred other places. However, one thing of note is the fact that the generated Javascript file is quite large:
</p>
  <pre><code class="bash scalatex-site-Styles-highlightMe">haoyi-mbp:temp haoyi$ du -h target/scala-2.11/example-fastopt.js
656K  target/scala-2.11/example-fastopt.js
</code></pre>
  <p>
    656 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:
</p>
  <pre><code class="javascript scalatex-site-Styles-highlightMe">var v1 = i;
if (((count$1.elem$1 % 3000) === 0)) {
  ScalaJS.m.Lexample_ScalaJSExample$().example$ScalaJSExample$$clear$1__Lorg_scalajs_dom_CanvasRenderingContext2D__V(ctx$1)
};
count$1.elem$1 = ((1 + count$1.elem$1) | 0);
var jsx$1 = ScalaJS.as.Lexample_Point(p$1.elem$1);
var this$4 = ScalaJS.m.s_util_Random$();
p$1.elem$1 = jsx$1.$$plus__Lexample_Point__Lexample_Point(ScalaJS.as.Lexample_Point(corners$1.apply__I__O(this$4.self$1.nextInt__I__I(3)))).$$div__I__Lexample_Point(2);
var height = (512.0 / ((255 + ScalaJS.as.Lexample_Point(p$1.elem$1).y$1) | 0));
var r = ((ScalaJS.as.Lexample_Point(p$1.elem$1).x$1 * height) | 0);
var g = ((((255 - ScalaJS.as.Lexample_Point(p$1.elem$1).x$1) | 0) * height) | 0);
</code></pre>
  <p>
    As you can see, this code is still very verbose, with lots of unnecessarily long identifiers such as <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Lexample_ScalaJSExample$</code> in it. This is because we've only performed the <a href="#FastOptimization">Fast Optimization</a> on this file, to try and keep the time taken to edit -&gt; compile while developing reasonably short.
</p>
  <h2 id="Optimization" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Optimization" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Optimization</h2>
    <p>
      If we're planning on publishing the app for real, we can run the <a href="#FullOptimization">Full Optimization</a>. This takes several seconds longer than the <a href="#FastOptimization">Fast Optimization</a>, but results in a significantly smaller and leaner output file <code>example-opt.js</code>.
</p>
    <pre><code class="bash scalatex-site-Styles-highlightMe">haoyi-mbp:temp haoyi$ du -h target/scala-2.11/example-opt.js
104K  target/scala-2.11/example-opt.js
</code></pre>
    <p>
      104 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 <a href="https://developers.google.com/closure/compiler/">Google Closure Compiler</a>.
</p>
    <pre><code class="javascript scalatex-site-Styles-highlightMe">  y=fb(gb((new F).Ya([&quot;rgb(&quot;,&quot;, &quot;,&quot;, &quot;,&quot;)&quot;])),(new F).Ya([(255-c.l.Db|0)*y|0,c.l.Db*y|0,c.l.Eb]));a.fillStyle=y;a.fillRect(c.l.Db,c.l.Eb,1,1);w=1+w|0}}}(a,b,c,e),50)}Xa.prototype.main=function(a){Ya(a)};Xa.prototype.a=new x({$g:0},!1,&quot;example.ScalaJSExample$&quot;,B,{$g:1,b:1});var hb=void 0;function bb(){hb||(hb=(new Xa).c());return hb}ba.example=ba.example||{};ba.example.ScalaJSExample=bb;function Da(){this.Pb=null}Da.prototype=new A;
</code></pre>

    <p>
      These files are basically unreadable, but nonetheless behave the same as the <code>-fastopt</code> versions. Try it out by opening the <code>index-opt.html</code> file in the <code>target/scala-2.11/classes</code> directory with your browser: you should see the thing as when opening <code>index-dev</code>, except it will be pulling in the fully-optmized version of your application.
</p>
    <p>
      This means you can develop and debug using <code>fastOptJS</code>, and only spend the extra time (and increased debugging-difficulty) on the <code>fullOptJS</code> 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.
</p>
  <h2 id="BlobSize" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#BlobSize" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Blob Size</h2>
    <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:
</p>
    <ul>
      <li>
        A large portion of this 104k 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 104k, a <a href="https://github.com/lihaoyi/roll">much larger ~2000 line application</a> is only 288k.</li>
      <li>
        This size is pre-<a href="http://en.wikipedia.org/wiki/Gzip">gzip</a>, and most webservers serve their contents compressed via gzip to reduce the download size. Gzip cuts the actual download size down to 28k, which is more acceptable.</li>
      <li>
        You will likely have other portions of the page that are of similar size: e.g. <a href="http://jquery.com/">JQuery</a> is extremely popular, and weights in at a comparable 32kb minified and gzipped, while <a href="http://facebook.github.io/react/downloads.html">React.js</a> weighs in at a cool 150kb gzipped. Scala.js arguably provides more than either of these libraries.
</li></ul>
    <p>
      Regardless, there is ongoing work to shrink the size of these executables. If you want to read more about this, check out the section on <a href="#TheCompilationPipeline">The Compilation Pipeline</a> to learn about what we currently do to crunch the executables down.
</p>
  <hr />

  <p>
    In general, all the output of the Scala.js compiler is bundled up into the <code>example-fastopt.js</code> and <code>example-opt.js</code> files. As a first approximation, these files can be included directly on a HTML page (as we have here, with <code>index-dev.html</code> and <code>index-opt.html</code>) 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>
  <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</code> 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 chapter <a href="#IntegratingClient-Server">Integrating Client-Server</a>.
</p>
<h1 id="Recap" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Recap" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Recap</h1>

  <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:
</p>
  <ul>
    <li>
      Getting a Scala.js application</li>
    <li>
      Building it and seeing it work in the browser</li>
    <li>
      Made modifications to it to see it update</li>
    <li>
      Examined the source code to try and understand what it's doing</li>
    <li>
      Examined the output code, at two levels of optimization, to see how the Scala.js compiler works</li>
    <li>
      Packaged the application in a form that can be easily published online
</li></ul>
  <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>
  <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:
</p>
  <ul>
    <li>
      Javascript includes APIs for <a href="http://stackoverflow.com/questions/1248081/get-the-browser-viewport-dimensions-with-javascript">getting the size of the window</a> and <a href="http://stackoverflow.com/questions/9251480/set-canvas-size-using-javascript">changing the size of a canvas</a>. 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>
    <li>
      The <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">CanvasRenderingContext2D</a> 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>
    <li>
      We've looked at the <code>master</code> branch of <code>workbench-example-app</code>, but this project also has several other branches showing off different facets of Scala.js: <a href="https://github.com/lihaoyi/workbench-example-app/tree/dodge-the-dots">dodge-the-dots</a> and <a href="https://github.com/lihaoyi/workbench-example-app/tree/space-invaders">space-invaders</a> are both interesting branches worth playing with as a beginner. Check them out!</li>
    <li>
      Try publishing the output code somewhere. You only need <code>example-opt.js</code> and <code>index-opt.html</code>; try putting them somewhere online where the world can see it.
</li></ul>
  <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!</p>


  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="MakingaCanvasApp" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="MakingaCanvasApp">Making a Canvas App<a class=" scalatex-site-Styles-headerLink" href="#MakingaCanvasApp" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    
<p>
  By this point, you've already cloned and got your hands dirty fiddling around with the toy <a href="https://github.com/lihaoyi/workbench-example-app">workbench-example-app</a>. 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>
<p>
  In this section of the book, we will walk through making a small canvas application. This will expose you to important concepts like:
</p>
<ul>
  <li>
    Taking input with Javascript event handlers</li>
  <li>
    Writing your application logic in Scala</li>
  <li>
    Using a timer to drive periodic actions
</li></ul>
<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</code>; the rest of the project will remain unchanged.
</p>
<h1 id="MakingaSketchpadusingMouseInput" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#MakingaSketchpadusingMouseInput" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Making a Sketchpad using Mouse Input</h1>

  <p>
    To begin with, lets remove all the existing stuff in our <code>.scala</code> file and leave only the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">object</code> and the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">main</code> method. Let's start off with some necessary boilerplate:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">/*setup*/
val renderer = canvas.getContext(&quot;2d&quot;)
                     .asInstanceOf[dom.CanvasRenderingContext2D]

canvas.width = canvas.parentElement.clientWidth
canvas.height = canvas.parentElement.clientHeight

renderer.fillStyle = &quot;#f8f8f8&quot;
renderer.fillRect(0, 0, canvas.width, canvas.height)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/canvasapp/ScratchPad.scala#L12-L22" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    As described earlier, this code uses the <a href="https://developer.mozilla.org/en-US/docs/Web/API/document.getElementById">document.getElementById</a> function to fish out the <code>canvas</code> element that we interested in from the DOM. It then gets a rendering context from that <code>canvas</code>, 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>
  <p>
    Next, let's set some event handlers on the canvas:
</p>
  <div class="pure-g">
    <div class="pure-u-1 pure-u-md-13-24">
      <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">/*code*/
renderer.fillStyle = &quot;black&quot;
var down = false
canvas.onmousedown =
  (e: dom.MouseEvent) =&gt; down = true

canvas.onmouseup =
  (e: dom.MouseEvent) =&gt; down = false

canvas.onmousemove = {
  (e: dom.MouseEvent) =&gt;
    val rect =
      canvas.getBoundingClientRect()
    if (down) renderer.fillRect(
      e.clientX - rect.left,
      e.clientY - rect.top,
      10, 10
    )
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/canvasapp/ScratchPad.scala#L22-L41" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
    <div class="pure-u-1 pure-u-md-11-24">
      <canvas id="example1" style="display: block;overflow: scroll;"></canvas><script>canvasapp.ScratchPad().main(document.getElementById('example1'))</script>
</div></div>
  <p>
    This code sets up the <a href="https://developer.mozilla.org/en-US/docs/Web/Events/mousedown">mousedown</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/Events/mouseup">mouseup</a> 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>
  <p>
    In general, you have access to all the DOM APIs through the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom</code> package as well as through Javascript objects such as the <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement">html.Canvas</a>. Setting the <code>onmouseXXX</code> 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:
</p>
  <img src="images/Dropdown.png" style="max-width: 100%;" />

  <p>
    Apart from mouse events, keyboard events, scroll events, input events, etc. are all usable from Scala.js as you'd expect. If you have problems getting this to work, feel free to click on the link <i class="fa fa-link "></i> icon below the code snippet to see what the full code for the example looks like
</p>
<h1 id="MakingaClockusingsetInterval" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#MakingaClockusingsetInterval" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Making a Clock using setInterval</h1>

  <p>
    You've already seen this in the previous example, but <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval">WindowTimers.setInterval</a> can be used to schedule recurring, periodic events in your program. Common use cases include running the <a href="http://gameprogrammingpatterns.com/game-loop.html">event loop for a game</a>, making smooth animations, and other tasks of that sort which require some work to happen over a period of time.
</p>
  <p>
    Again, we need roughly the same boilerplate as just now to set up the canvas:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">/*setup*/
val renderer = canvas.getContext(&quot;2d&quot;)
                     .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,&quot;red&quot;)
gradient.addColorStop(0.5,&quot;green&quot;)
gradient.addColorStop(1,&quot;blue&quot;)
renderer.fillStyle = gradient
//renderer.fillStyle = &quot;black&quot;

renderer.textAlign = &quot;center&quot;
renderer.textBaseline = &quot;middle&quot;</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/canvasapp/Clock.scala#L11-L30" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    The only thing unusual here is that I'm going to create a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">linearGradient</code> in order to make the stopwatch look pretty. This is by no means necessary, and you could simply make the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">fillStyle</code> <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;black&quot;</code> if you want to keep things simple.
</p>
  <p>
    Once that's done, it's only a few lines of code to set up a nice, live clock:
</p>
  <div class="pure-g">
    <div class="pure-u-1 pure-u-md-13-24">
      <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">/*code*/
def render() = {
  val date = new js.Date()
  renderer.clearRect(
    0, 0, canvas.width, canvas.height
  )

  renderer.font = &quot;75px sans-serif&quot;
  renderer.fillText(
    Seq(
      date.getHours(),
      date.getMinutes(),
      date.getSeconds()
    ).mkString(&quot;:&quot;),
    canvas.width / 2,
    canvas.height / 2
  )
}
dom.setInterval(render _, 1000)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/canvasapp/Clock.scala#L30-L49" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
    <div class="pure-u-1 pure-u-md-11-24">
      <canvas id="example2" style="display: block;overflow: scroll;"></canvas><script>canvasapp.Clock().main(document.getElementById('example2'))</script>
</div></div>
  <p>
    As you can see, we're using more <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">Canvas APIs</a>, in this case dealing with rendering text on the canvas. Another thing we're using is the Javascript <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date">Date</a> class, in Scala.js under the full name <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scala.scalajs.js.Date</code>, here imported as <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">js.Date</code>. Again, click on the link <i class="fa fa-link "></i> icon to view the full-code if you're having trouble here.
</p>
<h1 id="Tyingittogether:FlappyBox" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Tyingittogether:FlappyBox" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Tying it together: Flappy Box</h1>

  <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 &quot;Scala&quot; 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>
  <p>
    In this example we will make a spiritual clone of the popular <a href="http://en.wikipedia.org/wiki/Flappy_Bird">Flappy Bird</a> video game. This game involves a few simple rules
</p>
  <ul>
    <li>
      Your character starts in the middle of the screen</li>
    <li>
      Gravity pulls your character down</li>
    <li>
      Clicking/tapping the screen makes your character jump up</li>
    <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>
    <li>
      Don't go out of bounds!
</li></ul>
  <p>
    It's a relatively simple game, but there should be enough &quot;business logic&quot; in here that we won't be simply gluing together APIs. Let's start!
</p>
  <h2 id="SettingUptheCanvas" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#SettingUptheCanvas" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Setting Up the Canvas</h2>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">/*setup*/
val renderer = canvas.getContext(&quot;2d&quot;)
                     .asInstanceOf[dom.CanvasRenderingContext2D]

canvas.width = canvas.parentElement.clientWidth
canvas.height = 400

renderer.font = &quot;50px sans-serif&quot;
renderer.textAlign = &quot;center&quot;
renderer.textBaseline = &quot;middle&quot;</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/canvasapp/FlappyLine.scala#L12-L23" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      This section of the code is peripherally necessary, but not core to the implementation or logic of Flappy Box. We see the same <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas</code>/<code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">renderer</code> 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>
    <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 helper functions, so the verbosity and non-idiomatic-scala-ness doesn't bother you much.
</p>
  <h2 id="DefiningourState" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#DefiningourState" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Defining our State</h2>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">/*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, &gt;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]</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/canvasapp/FlappyLine.scala#L23-L42" target="_blank"><i class="fa fa-link "></i></a></pre>

    <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>
    <p>
      One notable thing is that we're using a <a href="http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html">collection.mutable.Queue</a> 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.
</p>
  <h2 id="GameLogic" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#GameLogic" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Game Logic</h2>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def runLive() = {
  frame += 2

  // Create new obstacles, or kill old ones as necessary
  if (frame &gt;= 0 &amp;&amp; frame % obstacleGap == 0)
    obstacles.enqueue(Random.nextInt(canvas.height - 2 * holeSize) + holeSize)
  if (obstacles.length &gt; 7){
    obstacles.dequeue()
    frame -= obstacleGap
  }

  // Apply physics
  playerY = playerY + playerV
  playerV = playerV + gravity


  // Render obstacles, and check for collision
  renderer.fillStyle = &quot;darkblue&quot;
  for((holeY, i) &lt;- obstacles.zipWithIndex){
    // Where each obstacle appears depends on what frame it is.
    // This is what keeps the obstacles moving to the left as time passes.
    val holeX = i * obstacleGap - frame + canvas.width
    renderer.fillRect(holeX, 0, 5, holeY - holeSize)
    renderer.fillRect(
      holeX, holeY + holeSize, 5, canvas.height - holeY - holeSize
    )

    // Kill the player if he hits some obstacle
    if (math.abs(holeX - canvas.width/2) &lt; 5 &amp;&amp;
      math.abs(holeY - playerY) &gt; holeSize){
      dead = 50
    }
  }

  // Render player
  renderer.fillStyle = &quot;darkgreen&quot;
  renderer.fillRect(canvas.width / 2 - 5, playerY - 5, 10, 10)

  // Check for out-of-bounds player
  if (playerY &lt; 0 || playerY &gt; canvas.height){
    dead = 50
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/canvasapp/FlappyLine.scala#L42-L86" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      The <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">runLive</code> function is the meat of Flappy Box. In it, we
</p>
    <ul>
      <li>
        Clear the canvas</li>
      <li>
        Generate new obstacles</li>
      <li>
        Apply velocity and acceleration to the player</li>
      <li>
        Check for collisions or out-of-bounds, killing the player if it happens</li>
      <li>
        Rendering everything, including the player as the namesake box
</li></ul>
    <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.
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def runDead() = {
  playerY = canvas.height / 2
  playerV = 0
  frame = -50
  obstacles.clear()
  dead -= 1
  renderer.fillStyle = &quot;darkred&quot;
  renderer.fillText(&quot;Game Over&quot;, canvas.width / 2, canvas.height / 2)
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/canvasapp/FlappyLine.scala#L86-L96" target="_blank"><i class="fa fa-link "></i></a></pre>

    <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 <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dead</code> counter until it reaches zero and we're considered alive again.
</p>
  <h2 id="AWorkingProduct" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#AWorkingProduct" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>A Working Product</h2>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def run() = {
  renderer.clearRect(0, 0, canvas.width, canvas.height)
  if (dead &gt; 0) runDead()
  else runLive()
}

dom.setInterval(run _, 20)

canvas.onclick = (e: dom.MouseEvent) =&gt; {
  playerV -= 5
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/canvasapp/FlappyLine.scala#L96-L107" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      And finally, this is the code that kicks everything off: we define the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">run</code> function to swap between <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">runLive</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">runDead</code>, register an <a href="https://developer.mozilla.org/en-US/docs/Web/Events/onclick">onclick</a> handler to make the player jump by tweaking his velocity, and we call <a href="https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval">WindowTimers.setInterval</a> to run the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">run</code> function every 20 milliseconds.
</p>
    <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!
</p>
    <div>
      <canvas id="example3" style="display: block;overflow: scroll;"></canvas><script>canvasapp.FlappyLine().main(document.getElementById('example3'))</script>
</div>
<h1 id="CanvasRecap" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#CanvasRecap" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Canvas Recap</h1>
  <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?
</p>
  <h2 id="DevelopmentSpeed" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#DevelopmentSpeed" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Development Speed</h2>
    <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>
    <p>
      Apart from the compilation/reload speed, you've probably noticed the benefit of tooling around Scala.js. Unlike Javascript editors, your existing Scala IDEs like <a href="http://blog.jetbrains.com/scala/">IntelliJ</a> or <a href="http://scala-ide.org/">Eclipse</a> 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.
</p>
  <h2 id="FullScala" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#FullScala" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Full Scala</h2>
    <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>
    <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.
</p>
  <h2 id="SeamlessJavascriptInterop" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#SeamlessJavascriptInterop" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Seamless Javascript Interop</h2>
    <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:
</p>
    <ul>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">obstacles</code> is a Scala <a href="http://docs.scala-lang.org/overviews/collections/concrete-mutable-collection-classes.html">mutable.Queue</a>, as we defined it earlier, and all the methods on it are Scala method calls</li>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">renderer</code> is a Javascript <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">CanvasRenderingContext2D</a>, and all the methods on it are Javascript method calls directly on the Javascript object</li>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">frame</code> is a Scala <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Int</code>, and obeys Scala semantics, though it is implemented as a Javascript <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Number</code> under the hood.</li>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">playerY</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">playerV</code> are Scala <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Double</code>s, implemented directly as Javascript <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Number</code>s
</li></ul>
    <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>
    <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. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">renderer</code>, for example is of type <a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D">CanvasRenderingContext2D</a> which is a subtype of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scalajs.js.Object</code>, indicating to the compiler that it needs special treatment. Primitives like <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Double</code>s and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Int</code>s have similar treatment
</p>
    <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.
</p>
  <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:
</p>
  <ul>
    <li>
      Make more video games! I have a set of <a href="http://lihaoyi.github.io/scala-js-games/">retro-games ported to Scala.js</a>. 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 href="http://lihaoyi.github.io/roll/">pretty elaborate</a>.
</li>
    <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 href="https://developer.mozilla.org/en-US/docs/Web/API">zoo of functionality</a>. Try making an application that uses <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage">localStorage</a> to save state even when you close the tab, or an application that works with the HTML DOM.
</li>
    <li>
      Draw something pretty! We have a working canvas, a nice programming language, and a way to easily publish the results online. <a href="http://www.scala-js-fiddle.com/gist/77a3840678d154257ca1/KochSnowflake.scala">Various</a> <a href="http://www.scala-js-fiddle.com/gist/77a3840678d154257ca1/KochCurve.scala">fractals</a>, or <a href="http://www.scala-js-fiddle.com/gist/9443f8e0ecc68d1058ad/RayTracer.scala">colorful visualizations</a> are all possibilities.
</li></ul>
  <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</p>


  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="InteractiveWebPages" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="InteractiveWebPages">Interactive Web Pages<a class=" scalatex-site-Styles-headerLink" href="#InteractiveWebPages" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    

<p>
  Most web applications aren't neat little games which live on a single canvas: they are large, structured HTML pages, which involve displaying data (whether from the user or from the web) in multiple ways, while allowing the user to make changes to the data that can be saved back to whatever remote web-service/database it came from.
</p>
<p>
  At this point, you are already competent at using Scala.js to make basic, self-contained canvas applications. In this chapter, we will cover how to use Scala.js to build the sort of interactive-web-pages that make up the bulk of the modern-day internet. We'll cover how to use powerful libraries that turn front-end development form the typical fragile-mess into a structured, robust piece of software.
</p>


<h1 id="HelloWorld:HTML" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#HelloWorld:HTML" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Hello World: HTML</h1>

  <p>
    The most basic way of building interactive web pages using Scala.js is to use the Javascript APIs to blat HTML strings directly into some container <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;div&gt;</code> or <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;body&gt;</code>. This approach works, as the following code snippet demonstrates:
</p>
  <div class="pure-g">
    <div class="pure-u-1 pure-u-md-13-24">
      <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package webpage
import org.scalajs.dom
import dom.html
import scalajs.js.annotation.JSExport
@JSExport
object HelloWorld0 extends{
  @JSExport
  def main(target: html.Div) ={
    val (f, d) = (&quot;fox&quot;, &quot;dog&quot;)
    target.innerHTML = s&quot;&quot;&quot;
    &lt;div&gt;
      &lt;h1&gt;Hello World!&lt;/h1&gt;
      &lt;p&gt;
        The quick brown &lt;b&gt;$f&lt;/b&gt;
        jumps over the lazy &lt;i&gt;$d&lt;/b&gt;
      &lt;/p&gt;
    &lt;/div&gt;
    &quot;&quot;&quot;
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/HelloWorld0.scala#L0-L20" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
    <div class="pure-u-1 pure-u-md-11-24">
      <div id="example4" style="display: block;overflow: scroll;"></div><script>webpage.HelloWorld0().main(document.getElementById('example4'))</script>
</div></div>
  <p>
    Remember that we're now requiring a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">html.Div</code> instead of a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">html.Canvas</code> to be passed in when the Javascript calls <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">webpage.HelloWorld0().main(...)</code>. If you're coming to this point from the previous chapter, you'll need to update the on-page Javascript's <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">document.getElementById</code> to pick a <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;div&gt;</code> rather than the <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;canvas&gt;</code> we were using in the previous chapter.
</p>
  <p>
    This approach works, as the above example shows, but has a couple of disadvantages:
</p>
  <ul>
    <li>
      It is untyped: it is easy to accidentally mistype something, and result in malformed HTML. A typo such as <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;dvi&gt;</code> would go un-noticed at build-time. Depending on where the typo happens, it could go un-noticed until the application is deployed, causing subtle bugs that only get resolved much later.</li>
    <li>
      It is insecure: <a href="http://en.wikipedia.org/wiki/Cross-site_scripting">Cross-site Scripting</a> is a real thing, and it is easy to forget to escape the values you are putting into your HTML strings. Above they're constants like <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;dog&quot;</code>, but if they're user-defined, you may not notice there is a problem until something like <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;&lt;script&gt;...&lt;/script&gt;&quot;</code> sneaks through and your users' accounts &amp; data is compromised.
</li></ul>
  <p>
    There are more, but we won't go deep into the intricacies of these problems. Suffice to say it makes mistakes easy to make and hard to catch, and we have something better...
</p>
<h1 id="Scalatags" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Scalatags" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Scalatags</h1>
  <p>
    <a href="https://github.com/lihaoyi/scalatags">Scalatags</a> is a cross-platform Scala.js/Scala-JVM library that is designed to generate HTML. To use Scalatags, you need to add it as a dependency to your Scala.js SBT project, in the <code>build.sbt</code> file:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">libraryDependencies += &quot;com.lihaoyi&quot; %%% &quot;scalatags&quot; % &quot;0.4.6&quot;</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/build.sbt#L16-L17" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    With that, the above snippet of code re-written using Scalatags looks as follows:
</p>
  <div class="pure-g">
    <div class="pure-u-1 pure-u-md-13-24">
      <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package webpage
import org.scalajs.dom
import dom.html
import scalajs.js.annotation.JSExport
import scalatags.JsDom.all._
@JSExport
object HelloWorld1 extends{
  @JSExport
  def main(target: html.Div) = {
    val (animalA, animalB) = (&quot;fox&quot;, &quot;dog&quot;)
    target.appendChild(
      div(
        h1(&quot;Hello World!&quot;),
        p(
          &quot;The quick brown &quot;, b(animalA),
          &quot; jumps over the lazy &quot;,
          i(animalB), &quot;.&quot;
        )
      ).render
    )
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/HelloWorld1.scala#L0-L22" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
    <div class="pure-u-1 pure-u-md-11-24">
      <div id="example5" style="display: block;overflow: scroll;"></div><script>webpage.HelloWorld1().main(document.getElementById('example5'))</script>
</div></div>
  <p>
    Scalatags has some nice advantages over plain HTML: it's type-safe, so typos like <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dvi</code> get caught at compile-time. It's also secure, such that you don't need to worry about script-tags in strings or similar. The <a href="https://github.com/lihaoyi/scalatags#scalatags">Scalatags Readme</a> elaborates on these points and other advantages. As you can see, it takes just 1 import at the top of the file to bring it in scope, and then you can use all of Scalatags' functionality.
</p>
  <p>
    The Scalatags github page has <a href="https://github.com/lihaoyi/scalatags#hello-world">comprehensive documentation</a> on how to express all manner of HTML fragments using Scalatags, so anyone who's familiar with how HTML works can quickly get up to speed. Instead of a detailed listing, we'll walk through some interactive examples to show Scalatags in action!
</p>
  <h2 id="UserInput" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#UserInput" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>User Input</h2>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val box = input(
  `type`:=&quot;text&quot;,
  placeholder:=&quot;Type here!&quot;
).render

val output = span.render

box.onkeyup = (e: dom.Event) =&gt; {
  output.textContent =
    box.value.toUpperCase
}

target.appendChild(
  div(
    h1(&quot;Capital Box!&quot;),
    p(
      &quot;Type here and &quot; +
      &quot;have it capitalized!&quot;
    ),
    div(box),
    div(output)
  ).render
)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Inputs.scala#L11-L34" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div style="height: 150px;display: block;overflow: scroll;" id="example6"></div><script>webpage.Inputs().main(document.getElementById('example6'))</script>
</div></div>
    <p>
      In Scalatags, you build up fragments of type <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Frag</code> using functions like <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">div</code>, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">h1</code>, etc., and call <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">.render</code> on it to turn it into a real <a href="https://developer.mozilla.org/en-US/docs/Web/API/Element">Element</a>. Different fragments render to different things: e.g. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">input.render</code> gives you a <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement">html.Input</a>, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">span.render</code> gives you a <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLSpanElement">html.Span</a>. You can then access the properties of these elements: adding callbacks, checking their value, anything you want.
</p>
    <p>
      In this example, we render and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">input</code> element and a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">span</code>, wire up the input to set the value of the span whenever you press a key in the input, and then stuff both of them into a larger HTML fragment that forms the contents of our <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">target</code> element.
</p>
  <h2 id="Re-rendering" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Re-rendering" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Re-rendering</h2>
    <p>
      Let's look at a slightly longer example. While above we spliced small snippets of text into the DOM, here we are going to re-render entire sections of HTML! The goal of this little exercise is to make a filtering search-box: starting from a default list of items, narrow it down as the user enters text into the box.
</p>
    <p>
      To begin with, let's define our list of items: Fruits!
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val listings = Seq(
  &quot;Apple&quot;, &quot;Apricot&quot;, &quot;Banana&quot;, &quot;Cherry&quot;,
  &quot;Mango&quot;, &quot;Mangosteen&quot;, &quot;Mandarin&quot;,
  &quot;Grape&quot;, &quot;Grapefruit&quot;, &quot;Guava&quot;
)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Search0.scala#L11-L17" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      Next, let's think about how we want to render these fruits. One natural way would be as a list, which in HTML is represented by a <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;ul&gt;</code> with <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;li&gt;</code>s inside of it if we wanted the list to be unordered. We'll make it a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">def</code>, because we know up-front we're going to need to re-render this listing as the search query changes. Lastly, we know we want 1 list item for each fruit, but only if the fruit starts with the search query.
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def renderListings = ul(
  for {
    fruit &lt;- listings
    if fruit.toLowerCase.startsWith(
      box.value.toLowerCase
    )
  } yield li(fruit)
).render</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Search0.scala#L17-L26" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      Using a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">for</code>-loop with a filter inside the Scalatags fragment is just normal Scala, since you can nest arbitrary Scala expressions inside a Scalatags snippet. In this case, we're converting both the fruit and the search query to lower case so we can compare them case-insensitively.
</p>
    <p>
      Lastly, we just need to define the input box and output-container (as we did earlier), set the <a href="https://developer.mozilla.org/en-US/docs/Web/Events/onkeyup">onkeyup</a> event handler, and place it in a larger fragment, and then into our target:
</p>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val output = div(renderListings).render

box.onkeyup = (e: dom.Event) =&gt; {
  output.innerHTML = &quot;&quot;
  output.appendChild(renderListings)
}

target.appendChild(
  div(
    h1(&quot;Search Box!&quot;),
    p(
      &quot;Type here to filter &quot; +
      &quot;the list of things below!&quot;
    ),
    div(box),
    output
  ).render
)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Search0.scala#L31-L49" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div id="example7" style="display: block;overflow: scroll;"></div><script>webpage.Search0().main(document.getElementById('example7'))</script>
</div></div>
    <p>
      And there you have it! A working search box. This is a relatively self-contained example: all the items its searching are available locally, no Ajax calls, and there's no fancy handling of the searched items. If we want to, for example, highlight the matched section of each fruit's name, we can modify the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">def renderListings</code> call to do so:
</p>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def renderListings = ul(
  for {
    fruit &lt;- listings
    if fruit.toLowerCase.startsWith(
      box.value.toLowerCase
    )
  } yield {
    val (first, last) = fruit.splitAt(
      box.value.length
    )
    li(
      span(
        backgroundColor:=&quot;yellow&quot;,
        first
      ),
      last
    )
  }
).render</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Search1.scala#L16-L37" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div id="example8" style="display: block;overflow: scroll;"></div><script>webpage.Search1().main(document.getElementById('example8'))</script>
</div></div>
    <p>
      Here, instead of sticking the name of the matched fruits directly into the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">li</code>, we instead first split off the part which matches the query, and then highlght the first section yellow. Easy!
</p>
  <hr />

  <p>
    Hopefully this has given you a good overview of how to do things using Scala.js and Scalatags. I won't go too deep into the various ways you can use Scalatags: the <a href="https://github.com/lihaoyi/scalatags">documentation</a> should cover most of it. Now that you've gone through this experience, it's worth re-iterating a few things you've probably already noticed about Scalatags
</p>
  <ul>
    <li>
      It's safe! If you make a trivial syntactic mistake, the compiler will catch it, because Scalatags is plain Scala. Try it!</li>
    <li>
      It's composable! You can easily define fragments and assign them to variables, to be used later. You can break apart large Scalatags fragments the same way you break apart normal code, avoiding the huge monolithic HTML templates that are common in other templating systems.</li>
    <li>
      It's Scala! You have the full power of the Scala language to write your fragments. No need to learn special syntax/cases for conditionals or repetitions: you can use plain-old-Scala <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">if</code>-<code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">else</code>s, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">for</code>-loops, etc.
</li></ul>
  <p>
    Now that you've gotten a quick overview of the kinds of things you can do with Scalatags, let's move on to the next section of our hands-on tutorial...
</p>
<h1 id="UsingWebServices" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#UsingWebServices" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Using Web Services</h1>

  <p>
    One half of the web application faces forwards towards the user, managing and rendering HTML or Canvas for the user to view and interact with. Another half faces backwards, talking to various web-services or databases which turn the application from a standalone-widget into part of a greater whole. We've already seen how to make the front half, let's now talk about working with the back half.
</p>
  <h2 id="RawJavascript" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#RawJavascript" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Raw Javascript</h2>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val xhr = new dom.XMLHttpRequest()
xhr.open(&quot;GET&quot;,
  &quot;http://api.openweathermap.org/&quot; +
  &quot;data/2.5/weather?q=Singapore&quot;
)
xhr.onload = (e: dom.Event) =&gt; {
  if (xhr.status == 200) {
    target.appendChild(
      pre(xhr.responseText).render
    )
  }
}
xhr.send()</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Weather0.scala#L12-L25" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div style="height: 400px;display: block;overflow: scroll;" id="example9"></div><script>webpage.Weather0().main(document.getElementById('example9'))</script></div></div>
    <p>
      The above snippet of code uses the raw Javascript Ajax API in order to make a request to <a href="http://openweathermap.org/">openweathermap.org</a>, to get the weather data for the city of Singapore as a JSON blob. The part of the API that we'll be using is documented <a href="http://openweathermap.org/current">here</a>, and if you're interested you can read all about the various options that they provide. For now, we're unceremoniously dumping it in a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">pre</code> so you can see the raw response data.
</p>
    <p>
      As you can see, using the raw Javascript API to make the Ajax call looks almost identical to actually doing this in Javascript, shown below:
</p>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="javascript scalatex-site-Styles-highlightMe">var xhr = new XMLHttpRequest()

xhr.open(&quot;GET&quot;,
    &quot;http://api.openweathermap.org/data/&quot; +
    &quot;2.5/weather?q=Singapore&quot;
);

xhr.onload = function (e) {
    if (xhr.status == 200) {
        var pre = document.createElement(&quot;pre&quot;);
        pre.textContent = xhr.responseText;
        target.appendChild(pre);
    }
};
xhr.send();</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/resources/webpage/weather.js#L1-L16" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div id="example10" style="display: block;overflow: scroll;"></div><script>WeatherJs(document.getElementById('example10'))</script>
</div></div>
    <p>
      The primary syntactic differences are:
</p>
    <ul>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">val</code>s for immutable data v.s. mutable <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">var</code>s.</li>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">=&gt;</code> v.s. <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">function</code> to define the callback.</li>
      <li>
        Scalatags' <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">pre</code> v.s. <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">document.createElement(&quot;pre&quot;)</code>
</li></ul>
    <p>
      Overall, they're pretty close, which is a common theme in Scala.js: using Javascript APIs in Scala.js is often as seamless and easy as using them in Javascript itself, and it often looks almost identical.
</p>
  <h2 id="dom.extensions" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#dom.extensions" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>dom.extensions</h2>
    <p>
      Although the Javascript XMLHttpRequest API is workable, it's kind of awkward and clunky compared to what you're used to in Scala. We create a half-baked object, set some magic properties, and call a magic function, which all has to be done in the correct order or it won't work.
</p>
    <p>
      With Scala.js, we provide a simpler API that is more clearly functional. First, you need to import some things into scope:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">import dom.html
@JSExport
object Weather1 extends{
  @JSExport
  def main(target: html.Div) = {
    import dom.ext._
    import scala.scalajs
                .concurrent
                .JSExecutionContext
                .Implicits
                .runNow</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Weather1.scala#L7-L19" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      The first import brings in Scala adapters to several DOM APIs, which allow you to use them more idiomatically from Scala. The second brings in an implicit <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scala.concurrent.ExecutionContext</code> that we'll need to run our asynchronous operations.
</p>
    <p>
      Then we need the code itself:
</p>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val url =
  &quot;http://api.openweathermap.org/&quot; +
  &quot;data/2.5/weather?q=Singapore&quot;

Ajax.get(url).onSuccess{ case xhr =&gt;
  target.appendChild(
    pre(xhr.responseText).render
  )
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Weather1.scala#L19-L28" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div style="height: 400px;overflow: scroll;display: block;overflow: scroll;" id="example11"></div><script>webpage.Weather1().main(document.getElementById('example11'))</script>
</div></div>
    <p>
      A single call to <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajax.get(...)</code>, with the URL, and we receive a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scala.concurrent.Future</code> that we can use to get access to the result when ready. Here we're just using it's <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">onSuccess</code>, but we could use it in a for-comprehension, with <a href="https://github.com/scala/async">Scala Async</a>, or however else we can use normal <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future</code>s
</p>
  <h2 id="ParsingtheData" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#ParsingtheData" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Parsing the Data</h2>
    <p>
      We've taken the data-dump from OpenWeatherMap in three different ways, but there's still something missing: we need to actually parse the JSON data to make use of it! Most people don't use their JSON data as strings but as structured documents, querying and extracting only the bits we need.
</p>
    <p>
      First, let's make the call prettyprint the document, so at least we can see what it contains:
</p>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">Ajax.get(url).onSuccess{ case xhr =&gt;
  target.appendChild(
    pre(
      js.JSON.stringify(
        js.JSON.parse(xhr.responseText),
        space=4
      )
    ).render
  )
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Weather2.scala#L24-L34" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div style="height: 400px;display: block;overflow: scroll;" id="example12"></div><script>webpage.Weather2().main(document.getElementById('example12'))</script>
</div></div>
    <p>
      We do this by taking <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">xhr.responseText</code> and putting it through both <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">JSON.parse</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">JSON.stringify</code>, passing in a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">space</code> argument to tell <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">JSON.stringify</code> to spread it out nicely.
</p>
    <p>
      Now that we've pretty-printed it, we can immediately see what data it contains and which part of the data we want. Let's change the previous example's <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">onSuccess</code> call to extract the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">weather</code>, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">temp</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">humidity</code> and put them in a nice, human-friendly format for us to enjoy:
</p>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">Ajax.get(url).onSuccess{ case xhr =&gt;
  if (xhr.status == 200) {
    val json = js.JSON.parse(
      xhr.responseText
    )
    val name = json.name.toString
    val weather = json.weather
                      .pop()
                      .main
                      .toString

    def celsius(kelvins: js.Dynamic) = {
      kelvins.asInstanceOf[Double] - 273.15
    }.toInt
    val min = celsius(json.main.temp_min)
    val max = celsius(json.main.temp_max)
    val humid = json.main.humidity.toString
    target.appendChild(
      div(
        b(&quot;Weather in Singapore:&quot;),
        ul(
          li(b(&quot;Country &quot;), name),
          li(b(&quot;Weather &quot;), weather),
          li(b(&quot;Temp &quot;), min, &quot; - &quot;, max),
          li(b(&quot;Humidity &quot;), humid, &quot;%&quot;)
        )
      ).render
    )
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/Weather3.scala#L24-L54" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div style="height: 400px;overflow: scroll;display: block;overflow: scroll;" id="example13"></div><script>webpage.Weather3().main(document.getElementById('example13'))</script>
</div></div>
    <p>
      First we parse the incoming response, extract a bunch of values from it, and then stick it in a Scalatags fragment for us to see. Note how we can use the names of the attributes e.g. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">json.name</code> even though <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">name</code> is a dynamic property which you can't be sure exists: this is because <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">json</code> is of type <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">js.Dynamic</code>, which allows us to refer to arbitrary parameters and methods on the underlying object without type-checking.
</p>
    <p>
      Calls on <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">js.Dynamic</code> resolve directly to javascript property/method references, and will fail at run-time with an exception if used wrongly. This is also why we need to call <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">.toString</code> or <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">.asInstanceOf</code>on the values before use: without these casts, the compiler can't be sure what kind of value is underneath the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">js.Dynamic</code> type, and so we have to provide it the guarantee that it is what it needs.
</p>
<h1 id="Tyingittogether:WeatherSearch" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Tyingittogether:WeatherSearch" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Tying it together: Weather Search</h1>
  <p>
    At this point we've made a small app that allows us to search from a pre-populated list of words, as well as a small app that lets us query a remote web-service to find the weather in Singapore. The natural thing to do is to put these things together to make a app that will let us search from a list of countries and query the weather in any country we desire. Let's start!
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">lazy val box = input(
  `type`:=&quot;text&quot;,
  placeholder:=&quot;Type here!&quot;
).render

lazy val output = div(
  height:=&quot;400px&quot;,
  overflowY:=&quot;scroll&quot;
).render

box.onkeyup = (e: dom.Event) =&gt; {
  output.innerHTML = &quot;Loading...&quot;
  fetchWeather(box.value)
}

target.appendChild(
  div(
    h1(&quot;Weather Search&quot;),
    p(
      &quot;Enter the name of a city to pull the &quot;,
      &quot;latest weather data from api.openweathermap.com!&quot;
    ),
    p(box),
    hr, output, hr
  ).render
)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/WeatherSearch.scala#L15-L42" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    This sets up the basics: an input box, an output div, and sets an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">onkeyup</code> that fetches the weather data each time you hit a key. It then renders all these components and sticks them into the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">target</code> div. This is basically the same stuff we saw in the early examples, with minor tweaks e.g. adding a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">maxHeight</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">overflowY:=&quot;scroll&quot;</code> to the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">output</code> box in case the output is too large. Whenever we enter something in the box, we call the function <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">fetchWeather</code>, which is defined as:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def fetchWeather(query: String) = {
  val searchUrl =
    &quot;http://api.openweathermap.org/data/&quot; +
    &quot;2.5/find?type=like&amp;mode=json&amp;q=&quot; +
    query

  for{
    xhr &lt;- Ajax.get(searchUrl)
    if query == box.value
  } js.JSON.parse(xhr.responseText).list match{
    case jsonlist: js.Array[js.Dynamic] =&gt;
      output.innerHTML = &quot;&quot;
      showResults(jsonlist, query)
    case _ =&gt;
      output.innerHTML = &quot;No Results&quot;
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/WeatherSearch.scala#L42-L60" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    This is where the actual data fetching happens. It's relatively straightforward: we make an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajax.get</code> request, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">JSON.parse</code> the response, and feed it into the callback function. We're using a slightly different API from earlier: we now have the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;type=like&quot;</code> flag, which is documented in the <a href="http://openweathermap.org/current#other">OpenWeatherMap API docs</a> to return multiple results for each city whose name matches your query.
</p>
  <p>
    Notably, before we re-render the results, we check whether the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">query</code> that was passed in is the same value that's in the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">box</code>. This is to prevent a particularly slow ajax call from finishing out-of-order, potentially stomping over the results of more recent searches. We also check whether the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">.list: js.Dynamic</code> property we want is an instance of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">js.Array</code>: if it isn't, it means we don't have any results to show, and we can skip the whole render-output step.
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def showResults(jsonlist: js.Array[js.Dynamic], query: String) = {
  for (json &lt;- jsonlist) {
    val name = json.name.toString
    val country = json.sys.country.toString
    val weather = json.weather.pop().main.toString

    def celsius(kelvins: js.Dynamic) = {
      kelvins.asInstanceOf[Double] - 273.15
    }.toInt

    val min = celsius(json.main.temp_min)
    val max = celsius(json.main.temp_max)
    val humid = json.main.humidity.toString
    val (first, last) = name.splitAt(query.length)
    output.appendChild(
      div(
        b(span(first, backgroundColor:=&quot;yellow&quot;), last, &quot;, &quot;, country),
        ul(
          li(b(&quot;Weather &quot;), weather),
          li(b(&quot;Temp &quot;), min, &quot; - &quot;, max),
          li(b(&quot;Humidity &quot;), humid, &quot;%&quot;)
        )
      ).render
    )
  }

}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/webpage/WeatherSearch.scala#L60-L89" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Here is the meat and potatoes of this program: every time it gets called with an array of weather-data, we iterate over the cities in that array. It then does a similar sort of data-extraction that we did earlier, putting the results into the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">output</code> div we defined above, including highlighting.
</p>
  <div id="example14" style="display: block;overflow: scroll;"></div><script>webpage.WeatherSearch().main(document.getElementById('example14'))</script>

  <p>
    And that's the working example! Try searching for cities like &quot;Singapore&quot; or &quot;New York&quot; or &quot;San Francisco&quot; and watch as the search narrows as you enter more characters into the text box. Note that the OpenWeatherMap API limits ambiguous searches to about a dozen results, so if a city doesn't turn up in a partial-search, try entering more characters to narrow it down.
</p>
<h1 id="InteractiveWebPagesRecap" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#InteractiveWebPagesRecap" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Interactive Web Pages Recap</h1>
  <p>
    In this chapter, we've explored the basics of how you can use Scala.js to build interactive web pages. The two main contributions are using Scalatags to render HTML in a concise, safe way, and making Ajax calls to external web services. We combined these two capabilities in a small weather-search app that let a user interactively search for the weather in different cities around the world.</p>
  <p>
    Some things you may have noticed in the process:
</p>
  <ul>
    <li>
      Using Scalatags to render HTML fragments, and managing them at runtime with callbacks and getting/setting properties, is really quite nice</li>
    <li>
      Using <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">new dom.XMLHttpRequest</code> to make web requests feels just like the Javascript code to do so</li>
    <li>
      Using <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajax.get(...)</code> and working with the resultant : <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future</code> feels a lot cleaner than directly using the Javascript API
</li></ul>
  <p>
    You're at this point reasonably pro</p>


  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="TheCommandLine" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="TheCommandLine">The Command Line<a class=" scalatex-site-Styles-headerLink" href="#TheCommandLine" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    

<p>
  We've by this point done a bunch of work in the browser: we've made a small game that runs in the web browser on the HTML5 canvas, and we've made a number of small web-apps that interact with HTML and 3rd party web-services. However, there's a whole other side to the Scala.js ecosystem: the command line interace, or CLI.
</p>
<p>
  Even though the goal of Scala.js is to get your code running in peoples' browsers, it still is useful to be familiar with the things that you can do in the command-line. It is much easier to write-code-print-results in the command line without having to set up a HTML page and opening a browser to test it, and this extends to things like unit test suites, which are almost exclusively run in the command-line using <code>sbt ~test</code> to keep re-running them when the code changes.
</p>
<p>
  The Scala.js command line is where you go to do things to your Scala.js code. Although Scala.js comes with <a href="http://www.scala-js.org/downloads.html">standalone executables</a> that can be used from any shell (sh, bash, zsh, etc.) the primary supported way of setting up, compiling and testing your Scala.js applications is through <a href="http://www.scala-sbt.org/">SBT</a>: Scala's primary build tool.
</p>
<p>
  You've already used fragments of the Scala.js CLI in earlier chapters of this book: <code>~fastOptJS</code> is what you used for development, <code>fullOptJS</code> for publishing. Apart from these, Scala.js allows you to execute code via <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino">Rhino</a>/<a href="http://nodejs.org/">Node.js</a>/<a href="http://phantomjs.org/">PhantomJS</a> from the command-line, as well as running test-suites under the same conditions. This chapter will go deeper into the various things you can do with the Scala.js command line:
</p>
<ul>
  <li>
    <code>compile</code>: converting code from Scala source into not-yet-executable Scala.js IR</li>
  <li>
    <code>package</code>: bundling up our Scala.js IR into a <code>.jar</code> file, for publishing or distribution as a library</li>
  <li>
    <code>fastOptJS</code>: aggregating our Scala.js IR and converting it to a <code>.js</code> executable.</li>
  <li>
    <code>fullOptJS</code>: aggregating our Scala.js IR and converting it to a smaller, faster <code>.js</code> executable.</li>
  <li>
    <code>run</code>: run your compiled Scala.js code as Javascript in Rhino, Node.js or Phantom.js</li>
  <li>
    <code>test</code>: run your compiled Scala.js code as a test suite in Rhino, Node.js or Phantom.js
</li></ul>
<p>
  Now, let's open up your SBT console in your Scala.js app
</p>
<pre><code class="bash scalatex-site-Styles-highlightMe">&gt;
</code></pre>
<p>
  And let's get started!
</p>
<h1 id="Commands" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Commands" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Commands</h1>
  <p>
    The most fundamental thing you can do in the Scala.js CLI is to compile your code. Let's go through the various mechanisms of &quot;compiling&quot; things:
</p>
  <h2 id="ThecompileCommand" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#ThecompileCommand" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The compile Command</h2>
    <pre><code class="bash scalatex-site-Styles-highlightMe">&gt; compile
</code></pre>
    <p>
      Just as you can <code>compile</code> Scala-JVM projects, you can also <code>compile</code> Scala.js projects. Like compiling Scala-JVM projects, this leaves a bunch of <code>.class</code> files in your <code>target</code> directory. Unlike Scala-JVM projects, this also leaves a bunch of <code>.sjsir</code> files, which correspond to your Scala.js output files:
</p>
    <pre><code class="bash scalatex-site-Styles-highlightMe">classes
└── 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
</code></pre>
    <p>
      However, unlike on Scala-JVM, you cannot directly run the <code>.sjsir</code> files spat out by the Scala.js compiler. These files are an Intermediate Representation, which needs to go through the next step in the compilation pipeline before being turned into Javascript.
</p>
  <h2 id="ThepackageCommand" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#ThepackageCommand" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The package Command</h2>
    <pre><code class="bash scalatex-site-Styles-highlightMe">&gt; package</code></pre>
    <p>
      Also like on Scala-JVM, Scala.js also supports the <code>package</code> command. This command generates a <code>.jar</code> like it does in Scala-JVM, except this version appends this weird <code>_sjs0.6</code> suffix.
</p>
    <pre><code class="bash scalatex-site-Styles-highlightMe">target/scala-2.11/
└── example_sjs0.6_2.11-0.1-SNAPSHOT.jar
</code></pre>
    <p>
      The purpose of this suffix is to link the compiled <code>.jar</code> file to the version of Scala.js used to compile it. This allows you to make sure that you don't accidentally depend on a version of a jar that is incompatible with your current version.
</p>
    <p>
      Again, unlike Scala-JVM, these <code>.jar</code> files are not directly executable: the <code>.sjsir</code> files need further processing to turn into runnable Javascript. Instead, their sole purpose is to hold bundles of <code>.sjsir</code> files to be published and depended-upon: they can be <code>publishLocal</code>ed to be used by other projects on your computer, or <code>publishSigned</code>ed to <a href="http://search.maven.org/">Maven Central</a>, just like any Scala-JVM project.
</p>
  <h2 id="ThefastOptJSCommand" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#ThefastOptJSCommand" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The fastOptJS Command</h2>
    <pre><code class="bash scalatex-site-Styles-highlightMe">&gt; fastOptJS</code></pre>
    <p>
      <code>fastOptJS</code> is a command we've used in earlier chapters. It basically runs the <a href="#FastOptimization">Fast Optimization</a> stage of the compilation pipeline. This results in a moderately-sized executable, which you can then load in the browser with a <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;script&gt;</code> tag and run.
</p>
    <p>
      This is the first phase which actually results in an executable blob of Javascript. I won't go into much detail about this command: you've used it before, and more details about the particular kind of optimization and how it fits into the large process is available in the chapter on The Compilation Pipeline. Nonetheless, it's fast, produces not-too-huge output code, and is what you typically use for iterative development in the browser.
</p>
  <h2 id="ThefullOptJSCommand" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#ThefullOptJSCommand" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The fullOptJS Command</h2>
    <pre><code class="bash scalatex-site-Styles-highlightMe">&gt; fullOptJS</code></pre>
    <p>
      <code>fullOptJS</code> is another command that we've seen before: it performs an aggressive, somewhat slower <a href="#FullOptimization">Full Optimization</a> pass on the generated Javascript. This results in a much smaller executable Javascript blob, which you can also load via a <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;script&gt;</code> tag and run.</p>
    <p>
      Again, I won't go into much details, as exactly what this optimization does is described in the chapter on the Compilation Pipeline. This command is somewhat too-slow to be running during iterative development, and is instead typically used just before deployment to minimize the size of the file your users have to download.
</p>
  <h2 id="TherunCommand" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#TherunCommand" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The run Command</h2>
    <pre><code class="bash scalatex-site-Styles-highlightMe">&gt; run</code></pre>
    <p>
      Here's something you haven't seen before: the <code>run</code> command gives you the ability to run a Scala.js program from the command line. This prints its output to standard output (i.e. the terminal). Like Scala-JVM, you need a <code>main</code> method to run to kick off your program. Unlike Scala-JVM, the main method is marked on an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">object</code> which <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">extends scala.scalajs.js.JSApp</code>, e.g.
</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">// src/main/scala/RunMe.scala
object RunMe extends scala.scalajs.js.JSApp{
  def main(): Unit = {
    println(&quot;Hello World!&quot;)
    println(&quot;In Scala.js, (1.0).toString is ${(1.0).toString}!&quot;)
  }
}
</code></pre>
    <p>
      Running <code>sbt run</code> with the above Scala.js code will print out
</p>
    <pre><code class="bash scalatex-site-Styles-highlightMe">Hello World!
In Scala.js, (1.0).toString is 1!
</code></pre>
    <p>
      This exhibits the weirdness of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Double.toString</code> in Scala.js, which is one of the few ways in which <a href="#DeviationsfromScala-JVM">Scala.js deviates from Scala-JVM</a>. This also shows us we're really running on Scala.js: on Scala-JVM, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">(1.0).toString</code> returns <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;1.0&quot;</code> rather than <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;1&quot;</code>!
</p>
    <p>
      One thing you may be wondering is: when you run a Scala.js program in the terminal, how does it execute the output Javascript? What about the DOM? and Ajax calls? Can it access the filesystem? The answer to all these questions is &quot;it depends&quot;: it turns out there are multiple ways you can run Scala.js from the command-line, dictated by the <i>stage</i> and the <i>environment</i>.
</p>
    <p>
      By default, runs are done in the <code>PreLinkStage</code>, which uses the Rhino environment. With the sbt setting <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">jsDependencies += RuntimeDOM</code>, the Scala.js runner will automatically set up <b>env.js</b> in Rhino so that you have access to an emulation of the DOM API.
</p>
    <p>
      You can enable a different stage, <code>FastOptStage</code> or <code>FullOptStage</code>, with the following sbt command:
</p>
    <pre><code class="bash scalatex-site-Styles-highlightMe">&gt; set scalaJSStage in Global := FastOptStage
</code></pre>
    <p>
      In <code>FastOptStage</code> and <code>FullOptStage</code>, the environment can be one of <b>Node.js</b> or <b>PhantomJS</b>. These JavaScript VMs must be installed separately.
</p>
    <ul>
      <li>
        By default, Node.js is used.</li>
      <li>
        With the sbt setting <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">jsDependencies += RuntimeDOM</code>, PhantomJS is used instead, so that a headless DOM is available.
</li></ul>
    <p>
      Typically, the best way to get started is using Rhino, since it's setup-free, and setting up Node.js or PhantomJS later as necessary. The next two sections elaborate on the differences between these ways of running your code. Check out the later sections on <a href="#HeadlessRuntimes">Headless Runtimes</a> and <a href="#Stages">Stages</a> to learn more about the other settings and why you would want to use them.
</p>
  <h2 id="ThetestCommand" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#ThetestCommand" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The test Command</h2>
    <pre><code class="bash scalatex-site-Styles-highlightMe">&gt; test
</code></pre>
    <p>
      The <code>sbt test</code> command behaves very similarly to <code>sbt run</code>. It also runs on Rhino, Node.js or PhantomJS, dependending of the stage and the dependency on the DOM.</p>
    <p>
      The difference is that instead of simply running your <code>main</code> method, <code>sbt test</code> runs whatever test-suite you have set-up, which will look through your <code>tests/</code> folder to find suites of tests it has to run, and aggregate the results formatted nicely for you to see. The exact operation of this depends on which testing library you're using.</p>
    <p>
      We won't spend much time talking about <code>sbt test</code> here. Not because it's not important: it most certainly is! Rather, we will be spending a good amount of time setting up tests in <a href="#CrossPublishingLibraries">the next chapter</a>, so feel free to jump ahead if you want to see an example usage of <code>sbt test</code>.
</p>
<h1 id="HeadlessRuntimes" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#HeadlessRuntimes" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Headless Runtimes</h1>
  <ul>
    <li>
      <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino">Rhino</a> is the default way of running Scala.js applications. The upside of using Rhino is that it is pure-Java, and doesn't need any additional binaries or installation. The downside of using Rhino is that it is slow: maybe a hundred times slower than the alternatives, making it not suitable for running long-running, compute-intensive programs.</li>
    <li>
      <a href="http://nodejs.org/">Node.js</a>, a relatively new Javascript runtime based on Google's V8 Javascript engine, Node.js lets you run your Scala.js application from the command line much faster than in Rhino, with performance that matches that of modern browsers. However, you need to separately <a href="http://nodejs.org/download/">install Node.js</a> in order to use it. Node.js does not have DOM or browser-related functionality. You need to set the stage with <code>set scalaJSStage in Global := FastOptStage</code> to run using Node.js.</li>
    <li>
      <a href="http://phantomjs.org/">PhantomJS</a> is a headless Webkit browser. This means that unlike Node.js, PhantomJS provides you with a full DOM and all its APIs to use in your tests, if you wish to e.g. test interactions with the HTML of the web page. On the other hand, it is somewhat slower than Node.js, though still much faster than Rhino. Like Node.js, it needs to be installed separately. You need to set the stage with <code>set scalaJSStage in Global := FastOptStage</code>, as well as setting the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">jsDependencies += RuntimeDOM</code> flag in your SBT configuration, to use PhantomJS.</li></ul>
  <p>
    These are your three options to run your Scala.js code via the command-line. Generally, it's easiest to get started with Rhino since it's the default and requires no setup, though you will quickly find it worthwhile to setup Node.js or PhantomJS to speed up your runs and tests.
</p>
<h1 id="Stages" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Stages" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Stages</h1>
  <p>
    Let us recap the three different stages of execution, and what they mean.
</p>
  <ul>
    <li>
      <code>PreLinkStage</code> (the default): this does not perform any optimization of the output Scala.js files, and does lazy-loading to minimize the amount of files being loading into the interpreter. This is necessary for Rhino because it can't handle large blobs of Javascript, but doesn't map to any compilation mode you'd use for the browser.</li>
    <li>
      <code>FastOptStage</code>: this performs the same compilation and optimization as <code>sbt fastOptJS</code>, as described under Fast Optimizations. It then takes the entire output executable (which probably weighs around 1mb) and hands it to Node.js or PhantomJS, which then run it.</li>
    <li>
      <code>FullOptStage</code>: this performs the same compilation and optimization as <code>sbt fullOptJS</code>, as described under Full Optimizations. This takes longer to run than the <code>FastOptStage</code>, and results in a smaller/faster executable. Practically speaking, this size/speed advantage does not matter from the command line, but <code>FullOptStage</code> is still useful to verify that the behavior does not change (it shouldn't!) under the aggressive full optimization. This is typically used in continuous integration builds, but rarely manually.
</li></ul>
<hr />

<p>
  Hopefully by this point you more-or-less know your way around the Scala.js command-line tools. As mentioned earlier, command line tools make it much easier to run a bunch of Scala.js code, e.g. unit tests, without having to muck around with HTML pages or refreshing the browser. That will come in handy soon, as we're next going to learn to publish a standalone, distributable Scala.js module. And what's a module without tests...</p>

  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="CrossPublishingLibraries" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="CrossPublishingLibraries">Cross Publishing Libraries<a class=" scalatex-site-Styles-headerLink" href="#CrossPublishingLibraries" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    
<p>
  We've spent several chapters exploring the experience of making web apps using Scala.js, but any large application (web or not!) likely relies on a host of libraries in order to implement large chunks of its functionality. Ideally these libraries would be re-usable, and can be shared among different projects, teams or even companies.
</p>
<p>
  Not all code is developed in the browser. Maybe you want to run simple snippets of Scala.js which don't interact with the browser at all, and having to keep a browser open is an overkill. Maybe you want to write unit tests for your browser-destined code, so you can verify that it works without firing up Chrome. Maybe it's not a simple script but a re-distributable library, and you want to run the same command-line unit tests on both Scala.js and Scala-JVM to verify that the behavior is identical. This chapter will go through all these cases.

</p>
<h1 id="ASimpleCross-BuiltLibrary" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#ASimpleCross-BuiltLibrary" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>A Simple Cross-Built Library</h1>

  <p>
    As always, we will start with an example: in this case a toy library whose sole purpose in life is to take a series of timestamps (milliseconds UTC) and format them into a single, newline-delimited string. This is what the project layout looks like:
</p>
  <pre><code class="bash scalatex-site-Styles-highlightMe">$ tree
.
├── build.sbt
├── project/build.sbt
└── library
    ├── js/src/main/scala/simple/Platform.scala
    ├── jvm/src/main/scala/simple/Platform.scala
    └── shared/src/main/scala/simple/Simple.scala
</code></pre>
  <p>
    As you can see, we have three main places where code lives: <code>js/</code> is where Scala-JS specific code lives, <code>jvm/</code> for Scala-JVM specific code, and <code>shared/</code> for code that is common between both platforms. Depending on your project, you may have more or less code in the <code>shared/</code> folder: a mostly-the-same cross-compiled module may have most or all its code in <code>shared/</code> while a <a href="#IntegratingClient-Server">client-server web application</a> would have lots of client/server js/jvm-specific code.
</p>
  <h2 id="BuildConfiguration" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#BuildConfiguration" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Build Configuration</h2>
    <p>
      From the bash shell in the project root. Let's take a look at the various files that make up this project. First, the <code>build.sbt</code> files:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">/*project/build.sbt*/
addSbtPlugin(&quot;org.scala-js&quot; % &quot;sbt-scalajs&quot; % &quot;0.6.0&quot;)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/simple/project/build.sbt#L0-L2" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      The <code>project/build.sbt</code> file is uneventful: it simply includes the Scala.js SBT plugin. However, the <code>build.sbt</code> file is a bit more interesting:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">
val library = crossProject.settings(
  libraryDependencies += &quot;com.lihaoyi&quot; %%% &quot;utest&quot; % &quot;0.3.0&quot;,
  testFrameworks += new TestFramework(&quot;utest.runner.Framework&quot;)
).jsSettings(
  // JS-specific settings here
).jvmSettings(
  // JVM-specific settings here
)

lazy val js = library.js

lazy val jvm = library.jvm</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/simple/build.sbt#L0-L13" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      Unlike the equivalent <code>build.sbt</code> files you saw in earlier chapters, this does not simply enable the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">ScalaJSPlugin</code> to the root project. Rather, it uses the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">crossProject</code> function provided by the Scala.js plugin to set up two projects: one in the <code>app/js/</code> folder and one in the <code>jvm/</code> folder. We also have places to put settings related to either the JS side, the JVM side, or both. In this case, we add a dependency on <a href="https://github.com/lihaoyi/utest">uTest</a>, which we will use as the test framework for our library. Note how we use triple <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">%%%</code> to indicate that we're using the platform-specific version of uTest, such that the Scala.js or Scala-JVM version will be properly pulled in when compiling for each platform.
</p>
  <h2 id="SourceFiles" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#SourceFiles" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Source Files</h2>
    
    <p>
      Now, let's look at the contents of the <code>.scala</code> files that make up the meat of this project:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">// library/shared/src/main/scala/simple/Simple.scala
package simple
object Simple{
  def formatTimes(timestamps: Seq[Long]): Seq[String] = {
    timestamps.map(Platform.format).map(_.dropRight(5))
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/simple/library/shared/src/main/scala/simple/Simple.scala#L0-L7" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      In <code>Simple.scala</code> we have the shared, cross-platform API of our library: a single <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">object</code> with a single method <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">def</code> which does what we want, which can then be used in either Scala.js or Scala-JVM. In general, you can put as much shared logic here as you want: classes, objects, methods, anything that can run on both Javascript and on the JVM. We're chopping off the last 5 characters (the milliseconds) to keep the formatted dates slightly less verbose.
</p>
    <p>
      However, when it comes to actually formatting the date, we have a problem: Javascript and Java provide different utilities for formatting dates! They both let you format them, but they provide different APIs. Thus, to do the formatting of each individual date, we call out to the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Platform.format</code> function, which is implemented twice: once in <code>js/</code> and once in <code>jvm/</code>:
</p>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-1-2">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">// library/js/src/main/scala/simple/Platform.scala
package simple
import scalajs.js

object Platform{
  def format(ts: Long) = {
    new js.Date(ts).toISOString()
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/simple/library/js/src/main/scala/simple/Platform.scala#L0-L9" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-1-2">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">// library/jvm/src/main/scala/simple/Platform.scala
package simple
import java.text.SimpleDateFormat
import java.util.TimeZone

object Platform{
  def format(ts: Long) = {
    val fmt = new SimpleDateFormat(
      &quot;yyyy-MM-dd'T'HH:mm:ss.sss'Z'&quot;
    )
    fmt.setTimeZone(TimeZone.getTimeZone(&quot;UTC&quot;))
    fmt.format(new java.util.Date(ts))
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/simple/library/jvm/src/main/scala/simple/Platform.scala#L0-L14" target="_blank"><i class="fa fa-link "></i></a></pre>
</div></div>
    <p>
      In the <code>js/</code> version, we are using the Javascript <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Date</code> object to take the millis and do what we want. In the <code>jvm/</code> version, we instead use <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">java.text.SimpleDateFormat</code> with a custom formatter (The syntax is defined <a href="http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html">here</a>).
</p>
    <p>
      Again, you can put as much platform-specific logic in these files as you want, to account for differences in the available APIs. Maybe you want to use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse">Json.parse</a> for parsing JSON blobs in <code>js/</code>, but <a href="http://jackson.codehaus.org/">Jackson</a> or <a href="https://code.google.com/p/google-gson/">GSON</a> for parsing them in <code>jvm/</code>.
</p>
  <h2 id="RunningtheModule" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#RunningtheModule" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Running the Module</h2>
    <pre><code class="bash scalatex-site-Styles-highlightMe">&gt; ;libraryJS/test ;libraryJVM/test
[info] Compiling 1 Scala source to library/js/target/scala-2.10/test-classes...
[info] ---------------------------Results---------------------------
[info] simple.SimpleTest		Success
[info]     format		Success
[info]         nil		Success
[info]         timeZero		Success
[info]     zero		Success
[info]         0
[info]
[info] Tests: 5
[info] Passed: 5
[info] Failed: 0
[success] Total time: 12 s, completed Feb 4, 2015 8:44:49 AM
[info] Compiling 1 Scala source to library/jvm/target/scala-2.10/test-classes...
[info] 1/5     simple.SimpleTest.format.nil		Success
[info] 2/5     simple.SimpleTest.format.timeZero		Success
[info] 3/5     simple.SimpleTest.format		Success
[info] 4/5     simple.SimpleTest.zero		Success
[info] 0.0
[info] 5/5     simple.SimpleTest		Success
[info] ---------------------------Results---------------------------
[info] simple.SimpleTest		Success
[info]     format		Success
[info]         nil		Success
[info]         timeZero		Success
[info]     zero		Success
[info]         0.0
[info]
[info] Tests: 5
[info] Passed: 5
[info] Failed: 0
[success] Total time: 2 s, completed Feb 4, 2015 8:44:51 AM
</code></pre>
    <p>
      As you can see, both runs printed the same results, modulo three things:
</p>
    <ul>
      <li>
        The <code>&quot;Compiling 1 Scala source to...&quot;</code> line, which tells us that both JS and JVM versions are being compiled.</li>
      <li>
        The time taken: the second run is instant while the first takes eleven seconds! This is because by default we run on <a href="https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino">Rhino</a>, which is a simple interpreter hundreds of times slower than running code natively on the JVM.</li>
      <li>
        In Scala-JVM the double 1.0 is printed as <code>1.0</code>, while in Scala.js it's printed as <code>1</code>. This is one of a small number of differences between Scala.js and Scala-JVM, and verifies that we are indeed running on both platforms!
</li></ul>
    <p>
      Apart from running each sub-project manually as we did above, you can also simply hit <code>test</code> and SBT will run tests for both
</p>
<h1 id="FurtherWork" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#FurtherWork" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Further Work</h1>
  <p>
    You've by this point set up a basic cross-building Scala.js/Scala-JVM project! If you wish, you can do more things with this project you've set up:
</p>
  <ul>
    <li>
      Flesh it out! Currently this module only does a single, trivial thing. If you've done any web development before, I'm sure you can find some code snippet, function or algorithm that you'd like to share between client and server. Try implementing it in the <code>shared/</code> folder to be usable in both Scala.js and Scala-JVM</li>
    <li>
      Publish it! Both <code>sbt publishLocal</code> and <code>sbt publishSigned</code> work on this module, for publishing either locally, Maven Central via Sonatype, or Bintray. Running the command bare should be sufficient to publish both the <code>js</code> or <code>jvm</code> projects, or you can also specify which one e.g. <code>jvm/publishLocal</code> to publish only one subproject.</li>
    <li>
      Cross-cross build it! You can use <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">crossScalaVersions</code> in your <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">crossProject</code> to build a library that works across all of {Scala.js, Scala-JVM} X {2.10, 2.11}. Many existing libraries, such as <a href="https://github.com/lihaoyi/scalatags">Scalatags</a> or <a href="https://github.com/lihaoyi/utest">uTest</a> are published like that.
</li></ul>
  <p>
    Now that you've gotten your code cross-compiling to Scala.js/Scala-JVM, the sky's the limit in what you can do. In general, although a large amount of your Scala-JVM code <i>does</i> deal with files or networks or other Scala-JVM-speciic functionality, in most applications there is a large library of helpers which don't. These could easily be packaged up into a cross-platform library and shared with your front-end Scala.js (or even pure-Javascript!) code.
</p>
<h1 id="OtherTestingLibraries" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#OtherTestingLibraries" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Other Testing Libraries</h1>
  <p>
    You can also try using a different testing library. While uTest was the first Scala.js testing library, it is definitely not the last! Here are a few alternatives worth trying:
</p>
  <ul>
    <li>
      <a href="https://github.com/monifu/minitest">Minitest</a></li>
    <li>
      <a href="https://github.com/InTheNow/zcheck">zCheck</a></li>
    <li>
      <a href="https://github.com/cgta/otest">oTest</a></li>
    <li>
      <a href="https://github.com/greencatsoft/greenlight">Greenlight</a>
</li></ul>
  <p>
    These (and others) are built and maintained by members of the community, so if one of them does not fit your tastes, it is worth trying the others.
</p>
  <p>
    Note that you cannot use <a href="http://www.scalatest.org/">Scalatest</a> or <a href="http://etorreborre.github.io/specs2">Specs2</a> in Scala.js. Despite the popularity of those libraries, they depend on too many Java-specific details of Scala-JVM to be easily ported to Scala.js. Thus you'll have to use one of the (relatively new) libraries which supports Scala.js, such as uTest or those above.</p>


  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="IntegratingClient-Server" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="IntegratingClient-Server">Integrating Client-Server<a class=" scalatex-site-Styles-headerLink" href="#IntegratingClient-Server" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    


<p>
  Historically, sharing code across client &amp; server has been a holy-grail for web development. There are many things which have made it hard in the past:
</p>
<ul>
  <li>
    Javascript on the client v.s. PHP/Perl/Python/Ruby/Java on the server</li>
  <li>
    Most back-ends make heavy use of C extensions, and front-end code was tightly coupled to the DOM. Even if you manage to port the main language</li></ul>
<p>
  There have been some attempts in recent years with more traction: Node.js, for example, has been very successful at running Javascript on the server, the Clojure/Clojurescript community has their own version of cross-built code, and there are a number of smaller, more esoteric platforms.
</p>
<p>
  Scala.js lets you share code between client and server relatively straightforwardly. As we saw in the previous chapter, where we made a shared module. Let's work to turn that shared module into a working client-server application!
</p>


<h1 id="AClient-ServerSetup" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#AClient-ServerSetup" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>A Client-Server Setup</h1>
  <p>
    Getting started with client-server integration, let's go with the simplest configuration possible: a Spray server and a Scala.js client. Most of the other web-frameworks (<a href="https://www.playframework.com/">Play</a>, <a href="http://www.scalatra.org/">Scalatra</a>, etc.) will have more complex configurations, but the basic mechanism of wiring up Scala.js to your web framework will be the same. Just like our project in <a href="#CrossPublishingLibraries">Cross Publishing Libraries</a>, our project will look like this:
</p>
  <pre><code class="bash scalatex-site-Styles-highlightMe">$ tree
.
├── build.sbt
├── project/build.sbt
└── app
    ├── shared/src/main/scala/simple/FileData.scala
    ├── js/src/main/scala/simple/Client.scala
    └── jvm/src/main/scala/simple/
                            ├── Page.scala
                            └── Server.scala
</code></pre>
  <p>
    First, let's do the wiring in <code>build.sbt</code>:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">import NativePackagerKeys._

val app = crossProject.settings(
  unmanagedSourceDirectories in Compile +=
    baseDirectory.value  / &quot;shared&quot; / &quot;main&quot; / &quot;scala&quot;,
  libraryDependencies ++= Seq(
    &quot;com.lihaoyi&quot; %%% &quot;scalatags&quot; % &quot;0.4.6&quot;,
    &quot;com.lihaoyi&quot; %%% &quot;upickle&quot; % &quot;0.2.7&quot;
  ),
  scalaVersion := &quot;2.11.5&quot;
).jsSettings(
  libraryDependencies ++= Seq(
    &quot;org.scala-js&quot; %%% &quot;scalajs-dom&quot; % &quot;0.8.0&quot;
  )
).jvmSettings(
  libraryDependencies ++= Seq(
    &quot;io.spray&quot; %% &quot;spray-can&quot; % &quot;1.3.2&quot;,
    &quot;io.spray&quot; %% &quot;spray-routing&quot; % &quot;1.3.2&quot;,
    &quot;com.typesafe.akka&quot; %% &quot;akka-actor&quot; % &quot;2.3.6&quot;
  )
)

lazy val appJS = app.js
lazy val appJVM = app.jvm.settings(
  (resources in Compile) += (fastOptJS in (appJS, Compile)).value.data
)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/build.sbt#L0-L27" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Again, we are using <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">crossProject</code> to define our <code>js/</code> and <code>jvm/</code> sub-projects. Both projects share a number of settings: the settings to add <a href="https://github.com/lihaoyi/scalatags">Scalatags</a> and <a href="https://github.com/lihaoyi/upickle">uPickle</a> to the build. Note that those two dependencies use the triple <code>%%%</code> instead of the double <code>%%</code> to declare: this means that for each dependency, we will pull in the Scala-JVM or Scala.js version depending on whether it's being used in a Scala.js project. Note also the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">packageArchetype.java_application</code> setting, which isn't strictly necessary depending on what you want to do with the application, but this example needs it as part of the deployment to Heroku.
</p>
  <p>
    The <code>js/</code> sub-project is uneventful, with a dependency on the by-now-familiar <code>scalajs-dom</code> library. The <code>jvm/</code> project, on the other hand, is interesting: it contains the dependencies required for us to set up out Spray server, and one additional thing: we add the output of <code>fastOptJS</code> from the client to the <code>resources</code> on the server. This will allow the <code>server</code> to serve the compiled-javascript from our <code>client</code> project from its resources.
</p>
  <p>
    Next, let's kick off the Spray server in our Scala-JVM main method:

</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package simple

import akka.actor.ActorSystem
import spray.http.{HttpEntity, MediaTypes}
import spray.routing.SimpleRoutingApp

import scala.util.Properties

object Server extends SimpleRoutingApp{
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()
    val port = Properties.envOrElse(&quot;PORT&quot;, &quot;8080&quot;).toInt
    startServer(&quot;0.0.0.0&quot;, port = port){
      get{
        pathSingleSlash{
          complete{
            HttpEntity(
              MediaTypes.`text/html`,
              Page.skeleton.render
            )
          }
        } ~
        getFromResourceDirectory(&quot;&quot;)
      } ~
      post{
        path(&quot;ajax&quot; / &quot;list&quot;){
          extract(_.request.entity.asString) { e =&gt;
            complete {
              upickle.write(list(e))
            }
          }
        }
      }
    }
  }
  def list(path: String) = {
    val (dir, last) = path.splitAt(path.lastIndexOf(&quot;/&quot;) + 1)
    val files =
      Option(new java.io.File(&quot;./&quot; + dir).listFiles())
        .toSeq.flatten
    for{
      f &lt;- files
      if f.getName.startsWith(last)
    } yield FileData(f.getName, f.length())
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/app/jvm/src/main/scala/simple/Server.scala#L0-L46" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    This is a not-very-interesting <a href="http://spray.io/documentation/1.2.2/spray-routing/">spray-routing</a> application: we set up a server on <code>localhost:8080</code>, have the root URL serve the main page on GET, and have other GET URLs serve resources. This includes the <code>js-fastopt.js</code> file that is now in our resources because of our <code>build.sbt</code> config earlier! We also add a POST route to allow the client ask the server to list files various directories.
</p>
  <p>
    The HTML template <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Page.skeleton</code> is not shown above; I put it in a separate file for neatness:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package simple
import scalatags.Text.all._

object Page{
  val boot =
    &quot;simple.Client().main(document.getElementById('contents'))&quot;
  val skeleton =
    html(
      head(
        script(src:=&quot;/appjs-fastopt.js&quot;),
        link(
          rel:=&quot;stylesheet&quot;,
          href:=&quot;https://cdnjs.cloudflare.com/ajax/libs/pure/0.5.0/pure-min.css&quot;
        )
      ),
      body(
        onload:=boot,
        div(id:=&quot;contents&quot;)
      )
    )
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/app/jvm/src/main/scala/simple/Page.scala#L0-L21" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    This is a typical <a href="https://github.com/lihaoyi/scalatags">Scalatags</a> HTML snippet. Note that since we're serving it directly from the server in Scala code, we do not need to leave a <code>.html</code> file somewhere on the filesystem! We can declare all HTML, including the skeleton of the page, in Scalatags. Otherwise it's the same as what we saw in earlier chapters: A simple HTML page which includes a script tag to run our Scala.js application.</p>
  <p>
    Lastly, we'll set up the Scala.js main method, which we are calling in the <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;script&gt;</code> tag above to kick off the client-side application.
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package simple

import scalatags.JsDom.all._
import scalajs.concurrent.JSExecutionContext.Implicits.runNow
import org.scalajs.dom
import dom.html
import dom.ext.Ajax
import scalajs.js.annotation.JSExport

@JSExport
object Client extends{
  @JSExport
  def main(container: html.Div) = {
    val inputBox = input.render
    val outputBox = ul.render
    def update() = Ajax.post(&quot;/ajax/list&quot;, inputBox.value).foreach{ xhr =&gt;
      val data = upickle.read[Seq[FileData]](xhr.responseText)
      outputBox.innerHTML = &quot;&quot;
      for(FileData(name, size) &lt;- data){
        outputBox.appendChild(
          li(
            b(name), &quot; - &quot;, size, &quot; bytes&quot;
          ).render
        )
      }
    }
    inputBox.onkeyup = (e: dom.Event) =&gt; update()
    update()
    container.appendChild(
      div(
        h1(&quot;File Search&quot;),
        inputBox,
        outputBox
      ).render
    )
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/app/js/src/main/scala/simple/Client.scala#L0-L37" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Again this is a simple Scala.js application, not unlike what we saw in earlier chapters. However, there is one difference: earlier, we made our Ajax calls to <code>api.openweathermap.org/...</code>. Here, we're making it to <code>/ajax</code>: the same server the page is served from!
</p>
  <p>
    You may have noticed in both client and server, we have made reference to a mysterious <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">FileData</code> type which holds the name and size of each file. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">FileData</code> is defined in the <code>shared/</code> folder, so it can be accessed from both Scala-JVM and Scala.js:

</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package simple

case class FileData(name: String, size: Long)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/app/shared/src/main/scala/simple/FileData.scala#L0-L3" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Now, if we go to the browser at <code>localhost:8080</code>, we should see our web-page!
</p>
  <iframe id="heroku1" style="width: 100%;height: 350px;" frameBorder="0"></iframe>
  <script>
  window.addEventListener("load", function(){
    document.getElementById("heroku1").src = 'https://hands-on-scala-js.herokuapp.com/'
  })
</script>


  <p>
    This is a real, live example running on a <a href="https://hands-on-scala-js.herokuapp.com/">Heroku server</a>. Feel free to poke around and explore the filesystem on the server, just to convince yourself that this actually works and is not just a mock up.
</p>
<h1 id="Client-ServerReflections" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Client-ServerReflections" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Client-Server Reflections</h1>
  <p>
    By now you've already set up your first client-server application. However, it might not be immediately clear what we've done and why it's interesting! Here are some points to consider.
</p>
  <h2 id="SharedTemplating" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#SharedTemplating" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Shared Templating</h2>

    <p>
      In both the client code and the server code, we made use of the same Scalatags HTML generation library. This is pretty neat: transferring rendering logic between client and server no longer means an annoying/messy rewrite! You can simply C&amp;P the Scalatags snippet over. That means it's easy if you want to e.g. shift the logic from one side to the other in order to optimize for performance or time-to-load or other things.</p>
    <p>
      One thing to take note of is that we're actually using subtly <i>different</i> implementations of Scalatags on both sides: on the server, we're importing from <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scalatags.Text</code>, while on the client we're using <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scalatags.JsDom</code>. The <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Text</code> backend renders directly to Strings, and is available on both Scala-JVM and Scala.js. The <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">JsDom</code> backend, on the other hand, renders to <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement">html.Element</a>-s which only exist on Scala.js. Thus while on the client you can do things like attach event listeners to the rendered <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement">html.Element</a> objects, or checking their runtime <code>.value</code>, on the server you can't. And that's exactly what you want!
</p>
  <h2 id="SharedCode" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#SharedCode" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Shared Code</h2>
    <p>
      One thing that we skimmed over is the fact that we could easily define our <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">case class FileData(name: String, size: Long)</code> in the <code>shared/</code> folder, and have it instantly and consistently available on both client and server. This perhaps does not seem so amazing: we've already done many similar things earlier when we were building Cross-platform Modules. Nevertheless, in the context of web development, it is a relatively novel idea to be able to ad-hoc share bits of code between client and server.</p>
    <p>
      Sharing code is not limited to class definitions: <i>anything</i> can be shared. Objects, classes, interfaces/traits, functions and algorithms, constants: all of these are things that you will likely want to share at some point or another. Traditionally, people have simply re-implemented the same code twice in two languages, or have resorted to awkward Ajax calls to push the logic to the server. With Scala.js, you no longer need to do so: you can easily, create ad-hoc bits of code which are available on both platforms.
</p>
  <h2 id="Boilerplate-freeSerialization" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Boilerplate-freeSerialization" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Boilerplate-free Serialization</h2>
    <p>
      The Ajax/RPC layer is one of the more fragile parts of web applications. Often, you have your various Ajax endpoints written once on the server, have a set of routes written to connect those Ajax endpoints to URLs, and client code (traditionally Javascript) made calls to those URLs with &quot;raw&quot; data: basically whatever you wanted, packed in an ad-hoc mix of CSV and JSON and raw-strings.
</p>
    <p>
      This has always been annoying boilerplate, and Scala.js removes it. With <a href="https://github.com/lihaoyi/upickle">uPickle</a>, you can simply call <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">upickle.write(...)</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">upickle.read[T](...)</code> to convert your collections, primitives or case-classes to and from JSON. This means you do not need to constantly re-invent different ways of making Ajax calls: you can just fling the data right across the network from client to server and back again.
</p>
<h1 id="What'sLeft?" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#What'sLeft?" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>What's Left?</h1>
  <p>
    We've built a small client-server web application with a Scala.js web-client that makes Ajax calls to a Scala-JVM web-server running on Spray. We performed these Ajax calls using uPickle to serialize the data back and forth, so serializing the arguments and return-value was boilerplate-free and correct.
</p>
  <p>
    However, there is still some amount of duplication in the code. In particular, the definition of the endpoint name &quot;list&quot; is duplicated 4 times:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">path(&quot;ajax&quot; / &quot;list&quot;){</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/app/jvm/src/main/scala/simple/Server.scala#L25-L26" target="_blank"><i class="fa fa-link "></i></a></pre>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">upickle.write(list(e))</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/app/jvm/src/main/scala/simple/Server.scala#L28-L29" target="_blank"><i class="fa fa-link "></i></a></pre>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def list(path: String) = {</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/app/jvm/src/main/scala/simple/Server.scala#L35-L36" target="_blank"><i class="fa fa-link "></i></a></pre>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def update() = Ajax.post(&quot;/ajax/list&quot;, inputBox.value).foreach{ xhr =&gt;</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/app/js/src/main/scala/simple/Client.scala#L15-L16" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Three times on the server and once on the client! What's worse, two of the appearances of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;list&quot;</code> are in string literals, which are not checked by the compiler to match up with themselves or the name of the method <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">list</code>. Apart from this, there is one other piece of duplication that is unchecked: the type being returned from <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">list</code> (<code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Seq[FileData]</code>) is being repeated on the client in <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">upickle.read[Seq[FileData]]</code> in order to de-serialize the serialized data. This leaves three opportunities for error wide-open:
</p>
  <ul>
    <li>
      You could change the string literals <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;list&quot;</code> and forget to change the method-name <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">list</code>, thus confusing future maintainers of the code.</li>
    <li>
      You could change one of literal <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;list&quot;</code>s but forget to change the other, thus causing an error at run-time (e.g. a 404 NOT FOUND response)</li>
    <li>
      You could update the return type of the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">list</code> method and forget to update the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">upickle.read</code> deserialization call on the client, resulting in a deserialization failure at runtime.
</li></ul>
  <p></p>

  <p>
    Neither of these scenarios is great! Although we've already made great progress in making our client-server application type-safe (via Scala.js on the client) and DRY (via shared code in <code>shared/</code>) we still have this tiny bit of annoying, un-checked duplication and danger lurking in the code-base. The basic problem is that what is normally called the &quot;routing layer&quot; in the web application is still unsafe, and so these silly errors can go un-caught and blow up on unsuspecting developers at run-time. Let's see how we can fix it.
</p>
<h1 id="Autowire" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Autowire" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Autowire</h1>

  <p>
    <a href="https://github.com/lihaoyi/autowire">Autowire</a> is a library that turns your request routing layer from a fragile, hand-crafted mess into a solid, type-checked, boilerplate-free experience. Autowire basically turns what was previously a stringly-typed, hand-crafted Ajax call and route:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def update() = Ajax.post(&quot;/ajax/list&quot;, inputBox.value).foreach{ xhr =&gt;</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver/app/js/src/main/scala/simple/Client.scala#L15-L16" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Into a safe, type-checked function call:
</p>
  
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def update() = Ajaxer[Api].list(inputBox.value).call().foreach{ data =&gt;</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver2/app/js/src/main/scala/simple/Client.scala#L26-L27" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Let's see how we can do that.
</p>
  <h2 id="SettingupAutowire" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#SettingupAutowire" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Setting up Autowire</h2>

    <p>
      To begin with, Autowire requires you to provide three things:
</p>
    <ul>
      <li>
        An <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">autowire.Server</code> on the Server, set up to feed the incoming request into Autowire's routing logic</li>
      <li>
        An <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">autowire.Client</code> on the Client, set up to take a serialized request and send it across the network to the server.</li>
      <li>
        An interface (A Scala <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">trait</code>) which defines the interface between these two
</li></ul>
    <p>
      Let's start with our client-server interface definition
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package simple

case class FileData(name: String, size: Long)

trait Api{
  def list(path: String): Seq[FileData]
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver2/app/shared/src/main/scala/simple/Shared.scala#L0-L7" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      Here, you can see that in addition to sharing the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">FileData</code> class, we are also creating an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Api</code> trait which contains the signature of our <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">list</code> method. The exact name of the trait doesn't matter. We need it to be in <code>shared/</code> so that the code in both client and server can reference it.
</p>
    <p>
      Next, let's look at modifying our server code to make use of Autowire:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package simple

import akka.actor.ActorSystem
import spray.http.{HttpEntity, MediaTypes}
import spray.routing.SimpleRoutingApp
import scala.concurrent.ExecutionContext.Implicits.global

object Router extends autowire.Server[String, upickle.Reader, upickle.Writer]{
  def read[Result: upickle.Reader](p: String) = upickle.read[Result](p)
  def write[Result: upickle.Writer](r: Result) = upickle.write(r)
}

object Server extends SimpleRoutingApp with Api{
  def main(args: Array[String]): Unit = {
    implicit val system = ActorSystem()
    startServer(&quot;localhost&quot;, port = 8080){
      get{
        pathSingleSlash{
          complete{
            HttpEntity(
              MediaTypes.`text/html`,
              Page.skeleton.render
            )
          }
        } ~
        getFromResourceDirectory(&quot;&quot;)
      } ~
      post{
        path(&quot;ajax&quot; / Segments){ s =&gt;
          extract(_.request.entity.asString) { e =&gt;
            complete {
              Router.route[Api](Server)(
                autowire.Core.Request(
                  s,
                  upickle.read[Map[String, String]](e)
                )
              )
            }
          }
        }
      }
    }
  }
  def list(path: String) = {
    val (dir, last) = path.splitAt(path.lastIndexOf(&quot;/&quot;) + 1)
    val files =
      Option(new java.io.File(&quot;./&quot; + dir).listFiles())
        .toSeq.flatten
    for{
      f &lt;- files
      if f.getName.startsWith(last)
    } yield FileData(f.getName, f.length())
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver2/app/jvm/src/main/scala/simple/Server.scala#L0-L54" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      Now, instead of hard-coding the route <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;ajax&quot; / &quot;list&quot;</code>, we now take in any route matching <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&quot;ajax&quot; / Segments</code>, feeding the resultant path segments into the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Router</code> object:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">path(&quot;ajax&quot; / Segments){ s =&gt;
  extract(_.request.entity.asString) { e =&gt;
    complete {
      Router.route[Api](Server)(
        autowire.Core.Request(
          s,
          upickle.read[Map[String, String]](e)
        )
      )
    }
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver2/app/jvm/src/main/scala/simple/Server.scala#L28-L40" target="_blank"><i class="fa fa-link "></i></a></pre>
    <p>
      The <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Router</code> object in turn simply defines how you intend the objects to be serialized and deserialized:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">object Router extends autowire.Server[String, upickle.Reader, upickle.Writer]{
  def read[Result: upickle.Reader](p: String) = upickle.read[Result](p)
  def write[Result: upickle.Writer](r: Result) = upickle.write(r)
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver2/app/jvm/src/main/scala/simple/Server.scala#L7-L12" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      In this case using uPickle. Note how the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">route</code> call explicitly states the type (here <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Api</code>) that it is to generate routes against; this ensures that only methods which you explicitly put in your public interface <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Api</code> are publically reachable.
</p>
    <p>
      Next, let's look at the modified client code:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package simple
import scalatags.JsDom.all._
import org.scalajs.dom
import dom.html
import scalajs.js.annotation.JSExport
import scalajs.concurrent.JSExecutionContext.Implicits.runNow
import autowire._

object Ajaxer extends autowire.Client[String, upickle.Reader, upickle.Writer]{
  override def doCall(req: Request) = {
    dom.ext.Ajax.post(
      url = &quot;/ajax/&quot; + req.path.mkString(&quot;/&quot;),
      data = upickle.write(req.args)
    ).map(_.responseText)
  }

  def read[Result: upickle.Reader](p: String) = upickle.read[Result](p)
  def write[Result: upickle.Writer](r: Result) = upickle.write(r)
}

@JSExport
object Client extends{
  @JSExport
  def main(container: html.Div) = {
    val inputBox = input.render
    val outputBox = ul.render
    def update() = Ajaxer[Api].list(inputBox.value).call().foreach{ data =&gt;
      outputBox.innerHTML = &quot;&quot;
      for(FileData(name, size) &lt;- data){
        outputBox.appendChild(
          li(
            b(name), &quot; - &quot;, size, &quot; bytes&quot;
          ).render
        )
      }
    }
    inputBox.onkeyup = (e: dom.Event) =&gt; update()
    update()
    container.appendChild(
      div(
        h1(&quot;File Search&quot;),
        inputBox,
        outputBox
      ).render
    )
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver2/app/js/src/main/scala/simple/Client.scala#L0-L47" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      There are two main modifications here: the existence of the new <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajaxer</code> object, and the modification to the Ajax call-site. Let's first look at <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajaxer</code>:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">object Ajaxer extends autowire.Client[String, upickle.Reader, upickle.Writer]{
  override def doCall(req: Request) = {
    dom.ext.Ajax.post(
      url = &quot;/ajax/&quot; + req.path.mkString(&quot;/&quot;),
      data = upickle.write(req.args)
    ).map(_.responseText)
  }

  def read[Result: upickle.Reader](p: String) = upickle.read[Result](p)
  def write[Result: upickle.Writer](r: Result) = upickle.write(r)
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver2/app/js/src/main/scala/simple/Client.scala#L8-L20" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      Like the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Router</code> object, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajaxer</code> also defines how you perform the serialization and deserialization of data-structures, again using uPickle. Unlike the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Router</code> object, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajaxer</code> also defines how the out-going Ajax call gets sent over the network. Here we're doing it using the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajax.post</code> method.
</p>
    <p>
      Lastly, let's look at the modified callsite for the ajax call itself:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def update() = Ajaxer[Api].list(inputBox.value).call().foreach{ data =&gt;</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/crossBuilds/clientserver2/app/js/src/main/scala/simple/Client.scala#L26-L27" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      There are a few things of note here:
</p>
    <ul>
      <li>
        The previous call to <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajax.post</code> with the path as a string has been replaced by calling <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajaxer[Api].list(...).call()</code>, since the logic of actually performing the POST is specified once-and-only-once in the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajaxer</code> object.</li>
      <li>
        While <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajax.post</code> returned a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future[dom.XMLHttpRequest]</code> and left us to call <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">upickle.read</code> and deserialize the data ourselves, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajaxer[Api].list(...).call()</code> now returns a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future[Seq[FileData]]</code>! Thus we don't need to worry about making a mistake in the deserialization logic when we write it by hand.
</li></ul>
    <p>
      Other than that, nothing much has changed. If you've done this correctly, the web application will look and behave exactly as it did earlier!
</p>
    <iframe id="heroku2" style="width: 100%;height: 350px;" frameBorder="0"></iframe>
    <script>
  window.addEventListener("load", function(){
    document.getElementById("heroku2").src = 'https://hands-on-scala-js.herokuapp.com/'
  })
</script>


    <p>
      So why did we do this in the first place?
</p>
  <h2 id="WhyAutowire?" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#WhyAutowire?" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Why Autowire?</h2>
    <p>
      Overall, this set up requires some boilerplate to define the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajaxer</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Router</code> objects, as well as the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Api</code> trait. However, these can be defined just once and used over and over; while it might be wasteful/unnecessary for making a single Ajax call, the cost is much less amortized over a number of Ajax calls. In a non-trivial web application with dozens of routes being called all over the place, spending a dozen lines setting up things up-front isn't a huge cost.
</p>
    <p>
      What have we gotten in exchange? It turns out that by using Autowire, we have eliminated the three failure modes described earlier, that could:
</p>
    <ul>
      <li>
        It is impossible for the route and the endpoint method-name to diverge accidentally: if the endpoint is called <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">list</code>, the requests will go through the <code>/list</code> URL. No room for discussion, or to make a mistake</li>
      <li>
        You cannot accidentally rename the route on the server without changing the client, or vice versa. Attempts to do so will cause a compilation error, and even your IDE should highlight it as red. Try it out!
</li>
      <li>
        There is no chance of messing up the serialization/deserialization code, e.g. writing a response of type A on the server and trying to read a data-structure of type B on the client. You have no opportunity to make an error: you pass arguments to the Ajax call, and they are serialized/deserialized automatically, such that by the time you get access to the value on the server, it is already of the correct type! The same applies to serializing/deserializing the return-value on the client. There is simply no place for you as a developer to accidentally make a mistake!
</li></ul>
    <p>
      Although the functionality of the web application is the same, it is mostly in terms of <i>safety</i> that we have made the biggest gains. All of the common failure modes described earlier have been guarded against, and you as a developer will have a hard time trying to make a mal-formed Ajax call. It's worth taking some time to poke at the source code to see the boundaries of the type-safety provided by autowire, as it is a very different experience from the traditional &quot;route it manually&quot; approach to making interactive client-server applications.
</p>
<hr />

<p>
  Hopefully this chapter has given you a glimpse of how a basic client-server application works using Scala.js. Although it is specific to a Spray server, there isn't any reason why you couldn't set up an equivalent thing for your Play, Scalatra or whichever other web framework that you're using.
</p>
<p>
  It's probably worth taking a moment to play around with the existing client-server system you have set up. Ideas for improvement include:
</p>
<ul>
  <li>
    Try adding additional functionality to the client-server interface: what about making it show the contents of a file if you've entered its full path? This can be added as a separate Ajax call or as part of the existing one.</li>
  <li>
    How about setting up the build.sbt so it serves the fully-optimized Scala.js blob, <code>client-opt.js</code>? This is probably what you want before deployment into production, and the same technique as we used to serve the fast-optimized version applies here too.</li>
  <li>
    What if you wanted to use another server rather than Spray? How about trying to set up a Play or Scalatra server to serve our Scala.js application code?</li></ul>
</div>
<div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="InDepth" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;">In Depth<a class=" scalatex-site-Styles-headerLink" href="#InDepth" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /><h2 style="font-weight: 300;color: #ccc;padding: 0px;margin-top: 0px;">Exploring Scala.js</h2></div><div class=" scalatex-site-Styles-content">
  <p>
    This half of the book 
is a set of detailed expositions on various parts of the Scala.js platform. Nothing in here is necessary for you to make your first demos, but as you dig deeper into the platform, you will likely need or want to care about these things so you can properly understand what's going on &quot;under the hood&quot;

</p>
  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="AdvancedTechniques" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="AdvancedTechniques">Advanced Techniques<a class=" scalatex-site-Styles-headerLink" href="#AdvancedTechniques" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    
<p>
  <a href="#GettingStarted">Getting Started</a> walks you through how to set up some basic Scala.js applications, but that only scratches the surface of the things you can do with Scala.js. Apart from being able to use the same techniques you're used to in Scala-JVM in the browser, Scala.js opens up a whole range of possibilities and novel techniques that are not found in typical Scala-JVM applications.
</p>
<p>
  Although these techniques may technically be possible on the JVM, very few Scala-JVM applications are built in a way that can take advantage of them. Most Scala-JVM code runs on back-end servers which have a completely different structure from the client-side apps that Scala.js allows.</p>
<p>
  This client-side user-interface-focused code lends itself to completely different design patterns from those used to develop server-side code. This section will explore a number of techniques which are present
</p>
<ul>
  <li>
    <a href="#Functional-ReactiveUIs">Functional-reactive user interfaces</a></li>
  <li>
    <a href="#AsynchronousWorkflows">Asynchronous user-interation workflows</a>
</li></ul>
<p>
  One note is that these are &quot;Techniques&quot; rather than &quot;Libraries&quot; because they have not been packaged up in a way that is sufficiently nice that you can use them out-of-the-box just by adding a dependency somewhere. Thus, they each require some small amount of boilerplate before use, though the amount of boilerplate is fixed: it does not grow with the size of your program, and anyway gives you a chance to tweak it to do exactly what you want.
</p>


<h1 id="Functional-ReactiveUIs" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Functional-ReactiveUIs" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Functional-Reactive UIs</h1>
  <p>
    <a href="http://en.wikipedia.org/wiki/Functional_reactive_programming">Functional-reactive Programming</a> (FRP) is a field with encompasses several things:
</p>
  <ul>
    <li>
      <b>Discrete</b>: Handling of first-class event-streams like in <link>RxJShttps://github.com/Reactive-Extensions/RxJS</link></li>
    <li>
      <b>Continuous</b>: Handling of first-class signals, like in <link>Elmhttp://elm-lang.org/learn/What-is-FRP.elm</link>
</li></ul>
  <h2 id="WhyFRP" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#WhyFRP" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Why FRP</h2>
    <p>
      The value proposition of FRP is that in a &quot;traditional&quot; program, when an event occurs, events and changes propagate throughout the program in an ad-hoc manner. An event-listener may trigger additional events, call some callbacks, or set some mutable variables that subsequent code will read and react to.
</p>
    <p>
      This works, but the ad-hoc nature is both free-ing and limiting. You are free to do whatever you want in response to any action, but in return the developer who maintains your code (e.g. yourself 6 months from now) has no idea what your code is doing in response to any action: the possible consequence of an action is basically &quot;Anything&quot;!
</p>
    <p>
      Furthermore, because the propagation is ad-hoc, there is no way for the code to help ensure that you are propagating changes in a &quot;valid&quot; manner: it is thus easy for programmer errors to result in changes or events being incorrectly propagated. This most often results in data falling out of sync: a UI widget may forget to update when an action is taken, resulting in an inconsistent state being shown to the user, ultimately resulting in confused users.
</p>
    <p>
      FRP basically structures these event- or change-propagations as first-class values within the program, either as an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">EventSource[T]</code> type that represents a discrete source of individual <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">T</code> events, or as a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Signal[T]</code> type which represents a continuous time-varying value <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">T</code>. This comes at some cost within the program: you now have to program using these <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">EventSource</code>s or <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Signal</code>s, rather than just ad-hoc running callbacks or listening-to/triggering events all over the place. In exchange, you get more powerful tools to work with these values, making it easy for the library to e.g. ensure that changes always propagate correctly throughout your program, and that all values are always kept in sync.
</p>
  <h2 id="FRPwithScala.Rx" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#FRPwithScala.Rx" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>FRP with Scala.Rx</h2>
    <p>
      <a href="https://github.com/lihaoyi/scala.rx">Scala.Rx</a> is a change-propagation library that implements the <b>Continuous</b> style of FRP. To begin with, we need to include it in our <code>build.sbt</code> dependencies:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">libraryDependencies += &quot;com.lihaoyi&quot; %%% &quot;scalarx&quot; % &quot;0.2.8&quot;</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/build.sbt#L18-L19" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      Scala.Rx provides you with smart variables that automatically track dependencies with each other, such that if one smart variable changes, the rest re-compute immediately and automatically. The main primitives in Scala.Rx are:
</p>
    <ul>
      <li>
        <b>Var</b>s: Smart variables that can be set manually, and automatically notify their dependents that they need to recompute</li>
      <li>
        <b>Rx</b>s: Smart values which are set as some computation of other <b>Rx</b>s or <b>Var</b>s, which recompute automatically when their dependencies change, and notify their dependents</li>
      <li>
        <b>Obs</b>s: Observers on either an <b>Rx</b> or a <b>Var</b>, which performs some action when it changes
</li></ul>
    <p>
      <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Var</code>s and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Rx</code>s roughly correspond to the idea of a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Signal</code> described earlier. The documentation for Scala.Rx goes into this in much more detail, so if you're curious you should read it. This section will jump straight into how to use Scala.Rx with Scala.js.
</p>
    <p>
      To begin with, let's set up our imports:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package advanced

import org.scalajs.dom
import scalajs.js
import scalajs.js.annotation.JSExport
import rx._
import scalatags.JsDom.all._
import dom.html</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/BasicRx.scala#L0-L8" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      Here we are seeing the same <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scalatags</code>, imports we saw in the hands-on tutorial, as well a new <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">import rx._</code> which bring all the Scala.Rx names into the local namespace.
</p>
    <p>
      Scala.Rx does not &quot;natively&quot; bind to Scalatags, but integrating them yourself is simple enough that it's not worth putting into a separate library. He's a simple integration:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">implicit def rxFrag[T &lt;% Frag](r: Rx[T]): Frag = {
  def rSafe: dom.Node = span(r()).render
  var last = rSafe
  Obs(r, skipInitial = true){
    val newLast = rSafe
    js.Dynamic.global.last = last
    last.parentNode.replaceChild(newLast, last)
    last = newLast
  }
  last
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/BasicRx.scala#L68-L79" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      Scalatags requires that anything you want to embed in a Scalatags fragment be implicitly convertible to <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Frag</code>; here we are providing one for any Scala.Rx <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Rx[T]</code>s, as long as the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">T</code> provided is itself convertible to a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Frag</code>. We call <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">r().render</code> to extract the &quot;current&quot; value of the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Rx</code>, and then set up an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Obs</code> that watches the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Rx</code>, replacing the previous value with the current one every time its value changes.
</p>
    <p>
      Now that the set-up is out of the way, let's consider a simple HTML widget that lets you enter text in a <code class="xml scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">&lt;textarea&gt;</code>, and keeps track of the number of words, characters, and counts how long each word is.
</p>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val txt = Var(&quot;&quot;)
val numChars = Rx{txt().length}
val numWords = Rx{
  txt().split(' ')
       .filter(_.length &gt; 0)
       .length
}

val avgWordLength = Rx{
  txt().count(_ != ' ') * 1.0 / numWords()
}

val txtInput = textarea.render
txtInput.onkeyup = (e: dom.Event) =&gt; {
  txt() = txtInput.value
}

container.appendChild(
  div(
    txtInput,
    ul(
      li(&quot;Chars: &quot;, numChars),
      li(&quot;Words: &quot;, numWords),
      li(&quot;Word Length: &quot;, avgWordLength)
    )
  ).render
)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/BasicRx.scala#L12-L39" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div id="example15" style="display: block;overflow: scroll;"></div><script>advanced.BasicRx().main(document.getElementById('example15'))</script>
</div></div>
    <p>
      This snippet sets up a basic data-flow graph. We have our <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">txt</code> <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Var</code>, and a bunch of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Rx</code>s (<code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">numChars</code>, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">numWords</code>, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">avgWordLength</code>) that are computed based on <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">txt</code>.
</p>
    <p>
      Next, we construct our Scalatags fragment: a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">textarea</code> tag with a listener that updates <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">txt</code>, and a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">div</code> containing the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">textarea</code> and a list containing the bound values of our <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Rx</code>s.
</p>
    <p>
      That's all we need to end up with a live-updating widget, which re-renders the necessary bits of the page when the contents of the text box changes! Note how the code basically flows top-to-bottom, like a batch-rendering program, but at the end of it we get a live widget. The code is much simpler than a similar widget built up using jQuery or Backbone.
</p>
    <p>
      Furthermore, there is no chance for the parts of the DOM which are &quot;live&quot; to fall out of sync. There is no visible logic that handles the individual re-calulations and re-renders: that is all done by Scala.Rx and by our <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">rxFrag</code> implicit. Because we do not need to write code for each site to keep each individual <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Rx</code> and each DOM fragment in sync, that means there is no chance of the developer screwing it up and resulting in an out-of-sync page.
</p>
  <h2 id="MoreRx" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#MoreRx" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>More Rx</h2>
    <p>
      That was a pretty simple example to get you started with a simple Scala.Rx application. Let's look at a more meaty example to see how we can use Scala.Rx to help structure our interactive web application:

</p>
    <div class="pure-g">
      <div class="pure-u-1 pure-u-md-13-24">
        <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val fruits = Seq(
  &quot;Apple&quot;, &quot;Apricot&quot;, &quot;Banana&quot;, &quot;Cherry&quot;,
  &quot;Mango&quot;, &quot;Mangosteen&quot;, &quot;Mandarin&quot;,
  &quot;Grape&quot;, &quot;Grapefruit&quot;, &quot;Guava&quot;
)
val query = Var(&quot;&quot;)
val txtInput = input.render
txtInput.onkeyup = (e: dom.Event) =&gt; {
  query() = txtInput.value
}

val fragments =
  for(fruit &lt;- fruits) yield Rx {
    val shown = fruit.toLowerCase
                     .startsWith(query())
    if (shown) li(fruit)
    else li(display := &quot;none&quot;)
  }

container.appendChild(
  div(
    txtInput,
    ul(fragments)
  ).render
)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/BasicRx.scala#L42-L67" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
      <div class="pure-u-1 pure-u-md-11-24">
        <div id="example16" style="display: block;overflow: scroll;"></div><script>advanced.BasicRx().main2(document.getElementById('example16'))</script>
</div></div>
    <p>
      This is a basic re-implementation of the autocomplete widget we created in the chapter <a href="#InteractiveWebPages">Interactive Web Pages</a>, except done using Scala.Rx. Note that unlike the original implementation, we don't need to manage the clearing of the output area via <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">innerHTML = &quot;&quot;</code> and the re-rendering via <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">appendChild(...)</code>. All this is handled by the same <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">rxFrag</code> code we wrote earlier.
</p>
    <p>
      Furthermore, this implementation is more efficient than the original: In the original, everything is always re-rendered every time, which can be a problem if the number of things being rendered is large. In this implementation, only when a fruit appears-in/disappears-from the list does re-rendering happen, and only for that particular fruit. For the bulk of the fruits which did not experience any change in appearance, the DOM is left entirely untouched.
</p>
    <p>
      Again, there is no chance for the developer to make a mistake updating things, because all this rendering and re-rendering is hidden from view inside the library.
</p>
  <hr />

  <p>
    Hopefully this has given you a sense of how you can use Scala.Rx to help build complex, interactive web applications. The implementation is tricky, but the basic value proposition is clear: you get to write your code top-to-bottom, like the most old-fashioned static pages, and have it transformed by Scala.Rx into an interactive, always-consistent web app. By abstracting away the whole event-propagation, manual-updating process inside the library, we have ensured that there is no place where the developer can screw it up, and the application's UI will forever be in sync with its data.
</p>
<h1 id="AsynchronousWorkflows" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#AsynchronousWorkflows" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Asynchronous Workflows</h1>
  <p>
    In a traditional setting, Scala applications tend to have a mix of concurrency models: some spawn multiple threads and use thread-blocking operations or libraries, others do things with Actors or Futures, trying hard to stay non-blocking throughout, while most are a mix of these two paradigms.
</p>
  <p>
    On Scala.js, things are different: multi-threaded concurrency is a non-starter, since Javascript engines are all single-threaded. As a result, there are virtually no blocking APIs in Javascript: all operations need to be asynchronous if you don't want them to freeze the user interface of the browser while the operation is happening. Scala.js uses standard Javascript APIs and is no different.
</p>
  <p>
    However, Scala.js has much more powerful tools to work with than your typical Javascript libraries. The Scala standard library comes with a rich API for <a href="#Futures&amp;Promises">Futures &amp; Promises</a>, which are thankfully 100% asynchronous. Though this design was chosen for performance on the JVM, it perfectly fits our 100% asynchronous Javascript APIs. We have tools like <a href="#Scala-Async">Scala-Async</a>, which works perfectly with Scala.js, and lets you create asynchronous computations in a much less confusing manner.
</p>
  <h2 id="Futures&amp;Promises" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Futures&amp;Promises" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Futures &amp; Promises</h2>
    <p>
      A Future represents an in-progress computation that may or may not have completed. It may encapsulate a web request, or an RPC, or a task happening on another thread. They are not a novel concept, and Scala provides a good in-built implementation of Futures that works well with Scala.js.
</p>
    <p>
      To motivate this, let's consider a simple example application that:
</p>
    <ul>
      <li>
        Takes as user input a comma-separated list of city-names</li>
      <li>
        Fetches the temperature in each city from <code>api.openweathermap.org</code></li>
      <li>
        Displays the results when they are all back
</li></ul>
    <p>
      We'll work through a few implementations of this.
</p>
    <p>
      To begin with, let's write the scaffolding code, that will display the input box, deal with the listeners, and all that:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val myInput = input(value:=&quot;London,Singapore,Berlin,New York&quot;).render
val output = div.render
myInput.onkeyup = (e: dom.KeyboardEvent) =&gt; {
  if (e.keyCode == KeyCode.enter){
    handle(myInput.value.split(','), output)
  }
}
container.appendChild(
  div(
    i(&quot;Press Enter in the box to fetch temperatures &quot;),
    myInput,
    output
  ).render
)</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Futures.scala#L16-L30" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      So far so good. The only thing that's missing here is the mysterious <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">handle</code> function, which is given the list of names and the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">output</code> div, and must handle the Ajax requests, aggregating the results, and displaying them in <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">output</code>. Let's also define a small number of helper functions that we'll use later:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def urlFor(name: String) = {
  &quot;http://api.openweathermap.org/data/&quot; +
  &quot;2.5/find?mode=json&amp;q=&quot; +
  name
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Futures.scala#L31-L36" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">urlFor</code> encapsulates the messy URL-construction logic that we need to make the Ajax call to the right place.
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def parseTemp(text: String) = {
  val data = js.JSON.parse(text)
  val kelvins = data.list
                    .pop()
                    .main
                    .temp
                    .asInstanceOf[Double]
  kelvins - 272.15
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Futures.scala#L36-L45" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">parseTemp</code> encapsulates the messy result-extraction logic that we need to get the data we want (current temperature, in celsius) out of the structured JSON return blob.
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def formatResults(output: html.Element, results: Seq[(String, Double)]) = {
  output.innerHTML = &quot;&quot;
  output.appendChild(ul(
    for((name, temp) &lt;- results) yield li(
      b(name), &quot; - &quot;, temp.toInt, &quot;C&quot;
    )
  ).render)
}
@JSExport</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Futures.scala#L45-L54" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">formatResults</code> encapsulates the conversion of the final <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">(name, celsius)</code> data back into readable HTML.
</p>
    <p>
      Overall, these helper functions do nothing special, btu we're defining them first to avoid having to copy-&amp;-paste code throughout the subsequent examples. Now that we've defined all the relevant scaffolding, let's walk through a few ways that we can implement the all-important <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">handle</code> method.
</p>
    

    <h3 id="DirectUseofXMLHttpRequest" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#DirectUseofXMLHttpRequest" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Direct Use of XMLHttpRequest</h3>
      <div style="height: 200px;display: block;overflow: scroll;" id="example17"></div><script>advanced.Futures().main0(document.getElementById('example17'))</script>
      <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def handle0(names: Seq[String], output: html.Div) = {
  val results = mutable.Buffer.empty[(String, Double)]
  for(name &lt;- names){
    val xhr = new XMLHttpRequest
    xhr.open(&quot;GET&quot;, urlFor(name))
    xhr.onload = (e: dom.Event) =&gt; {
      val temp = parseTemp(xhr.responseText)
      results.append((name, temp))
      if (results.length == names.length){
        formatResults(output, results)
      }
    }
    xhr.send()
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Futures.scala#L55-L70" target="_blank"><i class="fa fa-link "></i></a></pre>

      <p>
        This is a simple solution that directly uses the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">XMLHttpRequest</code> class that is available in Javascript in order to perform the Ajax call. Every Ajax call that returns, we aggregate in a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">results</code> buffer, and when the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">results</code> buffer is full we then append the formatted results to the output div.</p>
      <p>
        This is relatively straightforward, though maybe knottier than people would be used to. For example, we have to &quot;construct&quot; the Ajax call via calling mutating methods and setting properties on the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">XMLHttpRequest</code> object, where it's easy to make a mistake. Furthermore, we need to manually aggregate the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">results</code> and keep track ourselves whether or not the calls have all completed, which again is messy and error-prone.
</p>
      <p>
        This solution is basically equivalent to the initial code given in the <a href="#RawJavascript">Raw Javascript</a> section of <a href="#InteractiveWebPages">Interactive Web Pages</a>, with the additional code necessary for aggregation. As described in <a href="#dom.extensions">dom.extensions</a>, we can make use of the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Ajax</code> object to make it slightly tidier.
</p>
    <h3 id="Usingdom.extensions.Ajax" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Usingdom.extensions.Ajax" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Using dom.extensions.Ajax</h3>
      <div style="height: 200px;display: block;overflow: scroll;" id="example18"></div><script>advanced.Futures().main1(document.getElementById('example18'))</script>
      <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def handle1(names: Seq[String], output: html.Div) = {
  val results = mutable.Buffer.empty[(String, Double)]
  for{
    name &lt;- names
    xhr &lt;- Ajax.get(urlFor(name))
  } {
    val temp = parseTemp(xhr.responseText)
    results.append((name, temp))
    if (results.length == names.length){
      formatResults(output, results)
    }
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Futures.scala#L74-L87" target="_blank"><i class="fa fa-link "></i></a></pre>

      <p>
        This solution uses the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom.extensions.Ajax</code> object, as described in <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom.extensions</code>. This basically wraps the messy <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">XMLHttpRequest</code> interface in a single function that returns a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scala.concurrent.Future</code>, which you can then map/foreach over to perform the action when the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future</code> is complete.</p>
      <p>
        However, we still have the messiness inherent in the result aggregation: we don't actually want to perform our action (writing to the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">output</code> div) when one <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future</code> is complete, but only when <i>all</i> the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future</code>s are complete. Thus we still need to do some amount of manual book-keeping in the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">results</code> buffer.
</p>
    <h3 id="FutureCombinators" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#FutureCombinators" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Future Combinators</h3>
      <div style="height: 200px;display: block;overflow: scroll;" id="example19"></div><script>advanced.Futures().main2(document.getElementById('example19'))</script>
      <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">def handle2(names: Seq[String], output: html.Div) = {
  val futures = for(name &lt;- names) yield{
    Ajax.get(urlFor(name)).map( xhr =&gt;
      (name, parseTemp(xhr.responseText))
    )
  }

  for(results &lt;- Future.sequence(futures)){
    formatResults(output, results)
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Futures.scala#L91-L103" target="_blank"><i class="fa fa-link "></i></a></pre>

      <p>
        Since we're using Scala's <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future</code>s, we aren't limited to just map/foreach-ing over them. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scala.concurrent.Future</code> provides a <a href="http://www.scala-lang.org/files/archive/nightly/docs/library/scala/concurrent/Future.html">rich api</a> that can be used to deal with common tasks like working with lists of futures in parallel, or aggregating the result of futures together.</p>
      <p>
        Here, instead of manually counting until all the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future</code>s are complete, we instead create the Futures which will contain what we want (name and temperature) and store them in a list. Then we can use the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future.sequence</code> function to invert the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Seq[Future[T]]</code> into a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future[Seq[T]]</code>, a single Future that will provide all the results in a single list when every Future is complete. We can then simply foreach- over the single Future to get the data we need to feed to <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">formatResults</code>/<code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">appendChild</code>.
</p>
      <p>
        This approach is significantly neater than the previous two examples: we no longer have any mutation going on, and the logic is expressed in a very high-level, simple manner. &quot;Make a bunch of Futures, join them, use the result&quot; is much less error-prone than the imperative result-aggregation-and-counting logic used in the previous examples.
</p>
    <hr />

    <p>
      <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">scala.concurrent.Future</code> isn't limited to just calling <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">.sequence</code> on lists. It provides the ability to <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">.zip</code> two Futures of different types together to get their result, or <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">.recover</code> in the case where Futures fail. Although these tools were originally built for Scala-JVM, all of them work unchanged on Scala.js, and serve their purpose well in simplifying messy asynchronous computations.
</p>
  <h2 id="Scala-Async" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Scala-Async" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Scala-Async</h2>
    <p>
      Let's look at how to use Scala-Async. To motivate us, let's consider a simple paint-like canvas application similar to the one we built in the section <a href="#MakingaSketchpadusingMouseInput">Making a Sketchpad using Mouse Input</a>. This application will have a few properties:
</p>
    <ul>
      <li>
        The user clicks and drags to begin drawing a line on the canvas</li>
      <li>
        When the user releases the mouse, we fill the shape that was formed by the dragging</li>
      <li>
        The user clicks again to clear the canvas; like most clicks, the action happens when the button is released</li>
      <li>
        And can repeat the process from the top, indefinitely
</li></ul>
    <p>
      This is a toy example, but is enough to bring out the difficulty of doing things the &quot;traditional&quot; way, and why using Scala-Async with Scala.js is superior. To begin with, let's set the stage:
</p>
    <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">val renderer = canvas.getContext(&quot;2d&quot;)
  .asInstanceOf[dom.CanvasRenderingContext2D]

canvas.style.backgroundColor = &quot;#f8f8f8&quot;
canvas.height = canvas.parentElement.clientHeight
canvas.width = canvas.parentElement.clientWidth

renderer.lineWidth = 5
renderer.strokeStyle = &quot;red&quot;
renderer.fillStyle = &quot;cyan&quot;
renderer</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Async.scala#L12-L23" target="_blank"><i class="fa fa-link "></i></a></pre>

    <p>
      To initialize the canvas with the part of the code which will remain the same, so we can look more closely at the code which differs.
</p>
    <h3 id="TraditionalAsynchrony" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#TraditionalAsynchrony" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Traditional Asynchrony</h3>
      <p>
        Let's look at a traditional implementation, using Scala.js but no special features. We'll just use the Javascript <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas.onmouveXXX</code> operations directly.
</p>
      <div class="pure-g">
        <div class="pure-u-1 pure-u-md-13-24">
          <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">// traditional
def rect = canvas.getBoundingClientRect()

var dragState = 0

canvas.onmousemove ={(e: dom.MouseEvent) =&gt;
  if (dragState == 1) {
    renderer.lineTo(
      e.clientX - rect.left,
      e.clientY - rect.top
    )
    renderer.stroke()
  }
}
canvas.onmouseup = {(e: dom.MouseEvent) =&gt;
  if(dragState == 1) {
    renderer.fill()
    dragState = 2
  }else if (dragState == 2){
    renderer.clearRect(0, 0, 1000, 1000)
    dragState = 0
  }
}
canvas.onmousedown ={(e: dom.MouseEvent) =&gt;
  if (dragState == 0) {
    dragState = 1
    renderer.beginPath()
    renderer.moveTo(
      e.clientX - rect.left,
      e.clientY - rect.top
    )
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Async.scala#L67-L100" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
        <div class="pure-u-1 pure-u-md-11-24">
          <canvas id="example20" style="display: block;overflow: scroll;"></canvas><script>advanced.Async().main0(document.getElementById('example20'))</script></div></div>
      <p>
        This is a working implementation, and you can play with it on the right. We basically set the three listeners:
</p>
      <ul>
        <li>
          <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas.onmousemove</code></li>
        <li>
          <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas.onmousedown</code></li>
        <li>
          <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas.onmouseup</code>
</li></ul>
      <p>
        And each listener is in charge of deciding what to do when it is it's turn to fire.
</p>
      <p>
        This code is pretty tricky and hard to follow. It's not immediately clear what it is doing. One thing you may notice is the presence of this <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dragState</code> variable, which seems to add a lot to the confusion with branches all over the place. At first you may think you can simplify the code to do without it, but attempts to do so will reveal why it is necessary.
</p>
      <p>
        This variable is necessary because each mouse event could mean different things at different times. For example, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas.onmousemove</code> should do nothing it occurs between an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas.onmousedown</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas.onmouseup</code>. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas.onmouseup</code> itself has two tasks: it either ends the dragging phase (which necessitates the fill-current-shape call) or it serves to clear the canvas if happening after a drag. And <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">canvas.onmousedown</code> should not start a new drag if the previous drawing hasn't been cleared from the canvas.
</p>
      <p>
        This is a pretty simple workflow for the user, and yet the code is already tricky enough it's not obvious that it's correct at first glance. More complex tools will have correspondingly more complex workflows, and it is easy to see how just another 1 or 2 more states can get out of hand.
</p>
    <h3 id="UsingScala-Async" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#UsingScala-Async" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Using Scala-Async</h3>
      <p>
        Now we've seen what a &quot;traditional&quot; approach looks like, let's look at how we would do this using Scala-Async.
</p>
      <div class="pure-g">
        <div class="pure-u-1 pure-u-md-13-24">
          <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">// async
def rect = canvas.getBoundingClientRect()

type ME = dom.MouseEvent
val mousemove =
  new Channel[ME](canvas.onmousemove = _)
val mouseup =
  new Channel[ME](canvas.onmouseup = _)
val mousedown =
  new Channel[ME](canvas.onmousedown = _)

// Disabled due to scala-js#1469
async{
  while(true){
    val start = await(mousedown())
    renderer.beginPath()
    renderer.moveTo(
      start.clientX - rect.left,
      start.clientY - rect.top
    )

    var res = await(mousemove | mouseup)
    while(res.`type` == &quot;mousemove&quot;){
      renderer.lineTo(
        res.clientX - rect.left,
        res.clientY - rect.top
      )
      renderer.stroke()
      res = await(mousemove | mouseup)
    }

    renderer.fill()
    await(mouseup())
    renderer.clearRect(0, 0, 1000, 1000)
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Async.scala#L27-L63" target="_blank"><i class="fa fa-link "></i></a></pre>
</div>
        <div class="pure-u-1 pure-u-md-11-24">
          <canvas id="example21" style="display: block;overflow: scroll;"></canvas><script>advanced.Async().main(document.getElementById('example21'))</script>
</div></div>
      <p>
        We have an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">async</code> block, which contains a while loop. Each round around the loop, we wait for the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">mousedown</code> channel to start the path, waiting for either <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">mousemove</code> or <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">mouseup</code> (which continues the path or ends it respectively), fill the shape, and then wait for another <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">mousedown</code> before clearing the canvas and going again.
</p>
      <p>
        Hopefully you'd agree that this code is much simpler to read and understand than the previous version. In particular, the control-flow of the code goes from top to bottom in a &quot;natural&quot; fashion, rather than jumping around ad-hoc like in the previous callback-based design.</p>
      <p>
        You may be wondering what these <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Channel</code> things are, and where they are coming from. Although these are not provided by Scala, they are pretty straightforward to define ourselves:
</p>
      <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">class Channel[T](init: (T =&gt; Unit) =&gt; Unit){
  init(update)
  private[this] var value: Promise[T] = null
  def apply(): Future[T] = {
    value = Promise[T]()
    value.future
  }
  def update(t: T): Unit = {
    if (value != null &amp;&amp; !value.isCompleted) value.success(t)
  }
  def |(other: Channel[T]): Future[T] = {
    val p = Promise[T]()
    for{
      f &lt;- Seq(other(), this())
      t &lt;- f
    } p.trySuccess(t)
    p.future
  }
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/lihaoyi/hands-on-scala-js/blob/master/examples/demos/src/main/scala/advanced/Async.scala#L103-L122" target="_blank"><i class="fa fa-link "></i></a></pre>

      <p>
        The point of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Channel</code> is to allow us to turn event-callbacks (like those provided by the DOM's <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">onmouseXXX</code> properties) into some kind of event-stream, that we can listen to asynchronously (via <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">apply</code> that returns a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Future</code>) or merge via <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">|</code>. This is a minimal implementation for what we need now, but it would be easy to provide more functionality (filter, map, etc.) as necessary.
</p>
    <hr />

    <p>
      Scala-Async is a Macro; that means that it is both more flexible and more limited than normal Scala, e.g. you cannot put the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">await</code> call inside a lambda or higher-order-function like <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">.map</code>. Like Futures, it doesn't provide any fundamentally new capabilities, but is a tool that can be used to simplify otherwise messy asynchronous workflows.</p>


  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="DeviationsfromScala-JVM" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="DeviationsfromScala-JVM">Deviations from Scala-JVM<a class=" scalatex-site-Styles-headerLink" href="#DeviationsfromScala-JVM" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    
<p>
  Although Scala.js tries very hard to maintain compatibility with Scala-JVM, there are some parts where the two platforms differs. This can be roughly grouped into two things: differences in the libraries available, and differences in the language itself. This chapter will cover both of these facets.
</p>
<h1 id="LanguageDifferences" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#LanguageDifferences" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Language Differences</h1>

  <h2 id="Primitivedatatypes" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Primitivedatatypes" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Primitive data types</h2>
    <p>
      All primitive data types work exactly as on the JVM, with the three following
      exceptions.
</p>
    <h3 id="FloatscanbehaveasDoublesbydefault" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#FloatscanbehaveasDoublesbydefault" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Floats can behave as Doubles by default</h3>
      <p>
        Scala.js underspecifies the behavior of <code>Float</code>s by default. Any <code>Float</code> value can be stored as a <code>Double</code> instead, and any operation on <code>Float</code>s can be computed with double precision. The choice of whether or not to behave as such, when and where, is left to the
        implementation.</p>
      <p>
        If exact single precision operations are important to your application, you can enable strict-floats semantics in Scala.js, with the following sbt setting:</p>
      <pre><code class="scala scalatex-site-Styles-highlightMe">scalaJSSemantics ~= { _.withStrictFloats(true) }</code></pre>
      <p>
        Note that this can have a major impact on performance of your application on JS interpreters that do not support <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/fround">the Math.fround function</a>.
</p>
    <h3 id="toStringofFloat,DoubleandUnit" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#toStringofFloat,DoubleandUnit" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>toString of Float, Double and Unit</h3>
      <p>
        <code>x.toString()</code> returns slightly different results for floating point numbers and <code>()</code> (<code>Unit</code>).
</p>
      <div class="pure-g">
        <div class="pure-u-1 pure-u-md-1-2">
          <pre><code class="scala scalatex-site-Styles-highlightMe">// Scala-JVM
&gt; println(())
()
&gt; println(1.0)
1.0
&gt; println(1.4f)
1.4
</code></pre></div>
        <div class="pure-u-1 pure-u-md-1-2">
          <pre><code class="scala scalatex-site-Styles-highlightMe">// Scala.js
&gt; println(())
undefined
&gt; println(1.0)
1
&gt; println(1.4f)
1.399999976158142
</code></pre></div></div>
      <p>
        In general, a trailing <code>.0</code> is omitted. Floats print in a weird way because they are printed as if they were Doubles, which means their lack of precision shows up.</p>
      <p>
        To get sensible and portable string representation of floating point numbers, use <code>String.format()</code> or related methods.
</p>
    <h3 id="Runtimetypetestsarebasedonvalues" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Runtimetypetestsarebasedonvalues" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Runtime type tests are based on values</h3>
      <p>
        Instance tests (and consequently pattern matching) on any of <code>Byte</code>, <code>Short</code>, <code>Int</code>, <code>Float</code>, <code>Double</code> are based on the value and not the type they were created with. The following are examples:</p>
      <ul>
        <li>
          1 matches <code>Byte</code>, <code>Short</code>, <code>Int</code>, <code>Float</code>, <code>Double</code></li>
        <li>
          128 (<code>&gt; Byte.MaxValue</code>) matches <code>Short</code>, <code>Int</code>, <code>Float</code>, <code>Double</code></li>
        <li>
          32768 (<code>&gt; Short.MaxValue</code>) matches <code>Int</code>, <code>Float</code>, <code>Double</code></li>
        <li>
          2147483647 matches <code>Int</code>, <code>Double</code> if strict-floats are enabled, otherwise <code>Float</code> as well</li>
        <li>
          2147483648 (<code>&gt; Int.MaxValue</code>) matches <code>Float</code>, <code>Double</code></li>
        <li>
          1.5 matches <code>Float</code>, <code>Double</code></li>
        <li>
          1.4 matches <code>Double</code> only if strict-floats are enabled, otherwise <code>Float</code> and <code>Double</code></li>
        <li>
          <code>NaN</code>, <code>Infinity</code>, <code>-Infinity</code> and <code>-0.0</code> match <code>Float</code>, <code>Double</code></li></ul>
      <p>
        As a consequence, the following apparent subtyping relationships hold:</p>
      <pre><code class="scala scalatex-site-Styles-highlightMe">Byte &lt;:&lt; Short &lt;:&lt;  Int  &lt;:&lt; Double
               &lt;:&lt; Float &lt;:&lt;</code></pre>
      <p>
        if strict-floats are enabled, or</p>
      <pre><code class="scala scalatex-site-Styles-highlightMe">Byte &lt;:&lt; Short &lt;:&lt; Int &lt;:&lt; Float =:= Double</code></pre>
      <p>
        otherwise.
</p>
  <h2 id="Undefinedbehaviors" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Undefinedbehaviors" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Undefined behaviors</h2>
    <p>
      The JVM is a very well specified environment, which even specifies how some bugs are reported as exceptions. Some examples are:</p>
    <ul>
      <li>
        <code>NullPointerException</code></li>
      <li>
        <code>ArrayIndexOutOfBoundsException</code> and <code>StringIndexOutOfBoundsException</code></li>
      <li>
        <code>ClassCastException</code></li>
      <li>
        <code>ArithmeticException</code> (such as integer division by 0)</li>
      <li>
        <code>StackOverflowError</code> and other <code>VirtualMachineError</code>s</li></ul>
    <p>
      Because Scala.js does not receive VM support to detect such erroneous conditions, checking them is typically too expensive.</p>
    <p>
      Therefore, all of these are considered <a href="http://en.wikipedia.org/wiki/Undefined_behavior">undefined behavior</a>.</p>
    <p>
      Some of these, however, can be configured to be compliant with sbt settings. Currently, only <code>ClassCastException</code>s (thrown by invalid <code>asInstanceOf</code> calls) are configurable, but the list will probably expand in future versions.</p>
    <p>
      Every configurable undefined behavior has 3 possible modes:</p>
    <ul>
      <li>
        <b>Compliant</b>: behaves as specified on a JVM</li>
      <li>
        <b>Unchecked</b>: completely unchecked and undefined</li>
      <li>
        <b>Fatal</b>: checked, but throws <a href="http://www.scala-js.org/api/scalajs-library/0.6.0/#scala.scalajs.runtime.UndefinedBehaviorError">UndefinedBehaviorError</a>s instead of the specified exception.</li></ul>
    <p>
      By default, undefined behaviors are in Fatal mode for fastOptJS and in Unchecked mode for fullOptJS. This is so that bugs can be detected more easily during development, with predictable exceptions and stack traces. In production code (fullOptJS), the checks are removed for maximum efficiency.</p>
    <p>
      <code>UndefinedBehaviorError</code>s are <i>fatal</i> in the sense that they are not matched by <code>case NonFatal(e)</code> handlers. This makes sure that they always crash your program as early as possible, so that you can detect and fix the bug. It is <i>never</i> OK to catch an <code>UndefinedBehaviorError</code> (other than in a testing framework), since that means your program will behave differently in fullOpt stage than in fastOpt.</p>
    <p>
      If you need a particular kind of exception to be thrown in compliance with the JVM semantics, you can do so with an sbt setting. For example, this setting enables compliant <code>asInstanceOf</code>s:</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">scalaJSSemantics ~= { _.withAsInstanceOfs(
  org.scalajs.core.tools.sem.CheckedBehavior.Compliant) }</code></pre>
    <p>
      Note that this will have (potentially major) performance impacts.</p>
    <p>
      For a more detailed rationale, see the section <a href="#Whydoeserrorbehaviordiffer?">Why does error behavior differ?</a>.
</p>
  <h2 id="Reflection" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Reflection" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Reflection</h2>
    <p>
      Java reflection and, a fortiori, Scala reflection, are not supported. There is limited support for <code>java.lang.Class</code>, e.g., <code>obj.getClass.getName</code> will work for any Scala.js object (not for objects that come from JavaScript interop). Reflection makes it difficult to perform the optimizations that Scala.js heavily relies on. For a more detailed discussion on this topic, take a look at the section <a href="#WhyNoReflection?">Why No Reflection?</a>.
</p>
  <h2 id="Regularexpressions" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Regularexpressions" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Regular expressions</h2>
    <p>
      <a href="http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Guide:Regular_Expressions">JavaScript regular expressions</a> are slightly different from <a href="http://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html">Java regular expressions</a>. The support for regular expressions in Scala.js is implemented on top of JavaScript regexes.</p>
    <p>
      This sometimes has an impact on functions in the Scala library that use regular expressions themselves. A list of known functions that are
      affected is given here:</p>
    <ul>
      <li>
        <code>StringLike.split(x: Array[Char])</code>
</li></ul>
  <h2 id="Symbols" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Symbols" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Symbols</h2>
    <p>
      <code>scala.Symbol</code> is supported, but is a potential source of memory leaks in applications that make heavy use of symbols. The main reason is that
      JavaScript does not support weak references, causing all symbols created by Scala.js to remain in memory throughout the lifetime of the application.
</p>
  <h2 id="Enumerations" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Enumerations" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Enumerations</h2>
    <p>
      The methods <code>Value()</code> and <code>Value(i: Int)</code> on <code>scala.Enumeration</code> use reflection to retrieve a string representation of the member name and are therefore -- in principle -- unsupported. However, since Enumerations are an integral part of the Scala library, Scala.js adds limited support for these two methods:</p>
    <p>
      Calls to either of these two methods of the forms:</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">val &lt;ident&gt; = Value
val &lt;ident&gt; = Value(&lt;num&gt;)</code></pre>
    <p>
      are statically rewritten to (a slightly more complicated version of):</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">val &lt;ident&gt; = Value(&quot;&lt;ident&gt;&quot;)
val &lt;ident&gt; = Value(&lt;num&gt;, &quot;&lt;ident&gt;&quot;)</code></pre>
    <p>
      Note that this also includes calls like</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">val A, B, C, D = Value</code></pre>
    <p>
      since they are desugared into separate <code>val</code> definitions.</p>
    <p>
      Calls to either of these two methods which could not be rewritten, or calls to constructors of the protected &lt;code&gt;Val&lt;/code&gt; class without an explicit name as parameter, will issue a warning.</p>
    <p>
      Note that the name rewriting honors the <code>nextName</code> iterator. Therefore, the full rewrite is:</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">val &lt;ident&gt; = Value(
  if (nextName != null &amp;&amp; nextName.hasNext)
    nextName.next()
  else
    &quot;&lt;ident&gt;&quot;
)</code></pre>
    <p>
      We believe that this covers most use cases of <code>scala.Enumeration</code>. Please let us know if another (generalized) rewrite would make your life easier.
</p>
<h1 id="LibraryDifferences" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#LibraryDifferences" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Library Differences</h1>
  

  <p>
    Scala.js differs from Scala-JVM not just in the corner-cases of the language, but also in the libraries available. Scala-JVM has access to JVM APIs and the wealth of the Java libraries, while Scala.js has access to Javascript APIs and Javascript libraries. It's also possible to write pure-Scala libraries that run on both Scala.js and Scala-JVM, as detailed <a>here</a>.</p>
  <p>
    This table gives a quick overview of the sorts of libraries you can and can't use when working on Scala.js:
</p>
  

  <table class="pure-table pure-table-horizontal half-table"><thead><th>Can Use</th><th>Can't Use</th></thead><tbody>
    
      <tr>
        <td>Most of java.lang.*</td><td>java.lang.Thread, java.lang.Runtime, ...</td>
</tr>
      <tr>
        <td>Almost all of scala.*</td><td>scala.collection.parallel, scala.tools.nsc</td>
</tr>
      <tr>
        <td>Some of java.util.*</td><td>org.omg.CORBA, sun.misc.*</td>
</tr>
      <tr>
        <td>Macros: uPickle, Scala-Async, Scalaxy, etc</td><td>Reflection: Scala-Pickling, Scala-Reflect</td>
</tr>
      <tr>
        <td>Shapeless, Scalaz, Scalatags, uTest</td><td>Scalatest, Scalate</td>
</tr>
      <tr>
        <td>XMLHttpRequest, Websockets. Localstorage</td><td>Netty, Akka, Spray, File IO, JNI</td>
</tr>
      <tr>
        <td>HTML DOM, Canvas, WebGL</td><td>AWT, Swing, SWT, OpenGL</td>
</tr>
      <tr>
        <td>Chipmunk.js, Hand.js, React.js, jQuery</td><td>Guice, JUnit, Apache-Commons, log4j</td>
</tr>
      <tr>
        <td>IntelliJ, Eclipse, SBT, Chrome console, Firebug</td><td>Scala REPL, Yourkit, VisualVM, JProfiler</td>
</tr></tbody></table>
  <p>
    We'll go into each section bit by bit
</p>
  <h2 id="StandardLibrary" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#StandardLibrary" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Standard Library</h2>
    <table class="pure-table pure-table-horizontal half-table"><thead><th>Can Use</th><th>Can't Use</th></thead><tbody>
      
        <tr>
          <td>Most of java.lang.*</td><td>java.lang.Thread, java.lang.Runtime, ...</td>
</tr>
        <tr>
          <td>Almost all of scala.*</td><td>scala.collection.parallel, scala.tools.nsc</td>
</tr>
        <tr>
          <td>Some of java.util.*</td><td>org.omg.CORBA, sun.misc.*</td>
</tr></tbody></table>
    <p>
      You can use more-or-less the whole Scala standard library in Scala.js, sans some more esoteric components like the parallel collections or the tools. Furthermore, we've ported some subset of the Java standard library that many common Scala libraries depends on, including most of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">java.lang.*</code> and some of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">java.util.*</code>.</p>
    <p>
      There isn't a full list of standard library library APIs which are available from Scala.js, but it should be enough to give you a rough idea of what is supported. The full list of classes that have been ported to Scala.js is available under <a href="#AvailableJavaAPIs">Available Java APIs</a>
</p>
  <h2 id="Macrosv.s.Reflection" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Macrosv.s.Reflection" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Macros v.s. Reflection</h2>
    <table class="pure-table pure-table-horizontal half-table"><thead><th>Can Use</th><th>Can't Use</th></thead><tbody>
      
        <tr>
          <td>Macros: uPickle, Scala-Async, Scalaxy, etc</td><td>Reflection: Scala-Pickling, Scala-Reflect</td>
</tr></tbody></table>
    <p>
      As described <a href="#WhyNoReflection?">here</a>, Reflection is not supported in Scala.js, due to the way it inhibits optimization. This doesn't just mean you can't use reflection yourself: many third-party libraries also use reflection, and you won't be able to use them either.
</p>
    <p>
      On the other hand, Scala.js does support Macros, and macros can in many ways substitute many of the use cases that people have traditionally used reflection for (see <a href="#Macros">here</a>). For example, instead of using a reflection-based serialization library like <a href="https://github.com/scala/pickling">scala-pickling</a>, you can use a macro-based library such as <a href="https://github.com/lihaoyi/upickle">uPickle</a>.
</p>
  <h2 id="Pure-Scalav.s.JavaLibraries" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Pure-Scalav.s.JavaLibraries" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Pure-Scala v.s. Java Libraries</h2>
    <table class="pure-table pure-table-horizontal half-table"><thead><th>Can Use</th><th>Can't Use</th></thead><tbody>
      
        <tr>
          <td>Shapeless, Scalaz, Scalatags, uTest</td><td>Scalatest, Scalate</td></tr></tbody></table>
    <p>
      Scala.js has access to any pure-Scala libraries that you have cross-compiled to Scala.js, and cross-compiling a pure-Scala library with no dependencies is straightforward. Many of them, such as the ones listed above, have already been cross-compiled and can be used via their maven coordinates.</p>
    <p>
      You cannot use any libraries which have a Java dependency. This means libraries like <a href="http://www.scalatest.org/">ScalaTest</a> or <a href="https://github.com/scalate/scalate">Scalate</a>, which depend on a number of external Java libraries or source files, cannot be used from Scala.js. You can only use libraries which have no dependency on Java libraries or sources.
</p>
  <h2 id="JavascriptAPIsv.s.JVMAPIs" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#JavascriptAPIsv.s.JVMAPIs" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Javascript APIs v.s. JVM APIs</h2>
    <table class="pure-table pure-table-horizontal half-table"><thead><th>Can Use</th><th>Can't Use</th></thead><tbody>
      
        <tr>
          <td>XMLHttpRequest, Websockets. Localstorage</td><td>Netty, Akka, Spray, File IO, JNI</td>
</tr>
        <tr>
          <td>HTML DOM, Canvas, WebGL</td><td>AWT, Swing, SWT, OpenGL</td>
</tr></tbody></table>
    <p>
      Apart from depending on Java sources, the other thing that you can't use in Scala.js are JVM-specific APIs. This means that anything which goes down to the underlying operating system, filesystem, GUI or network are unavailable in Scala.js. This makes sense when you consider that these capabilities are no provided by the browser which Scala.js runs in, and it's impossible to re-implement them ourselves.</p>
    <p>
      In exchange for this, Scala.js provides you access to Browser APIs that do related things. Although you can't set up a HTTP server to take in-bound requests, you can make out-bound requests using <a href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a> to other servers. You can't write to the filesystem or databases directly, but you can write to the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">dom.localStorage</code> provided by the browser. You can't use Swing or AWT or WebGL but instead work with the DOM and Canvas and WebGL.</p>
    <p>
      Naturally, none of these are an exact replacement, as the browser environment is fundamentally different from that of a desktop application running on the JVM. Nonetheless, there are many analogues, and if so desired you can write code to abstract away these differences and run on both Scala.js and Scala-JVM

</p>
  <h2 id="Scala/Browsertoolingv.s.Javatooling" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Scala/Browsertoolingv.s.Javatooling" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Scala/Browser tooling v.s. Java tooling</h2>
    <table class="pure-table pure-table-horizontal half-table"><thead><th>Can Use</th><th>Can't Use</th></thead><tbody>
      
        <tr>
          <td>Chipmunk.js, Hand.js, React.js, jQuery</td><td>Guice, JUnit, Apache-Commons, log4j</td>

</tr></tbody></table>
    <p>
      Lastly, there is the matter of tools. Naturally, all the Scala tools which depend on the JVM are out. This means things like the <a href="http://www.yourkit.com/">Yourkit</a>, <a href="http://visualvm.java.net/">VisualVM</a> and <a href="https://www.ej-technologies.com/products/jprofiler/overview.html">JProfiler</a> profilers, as well as things like the Scala command-line REPL which relies on classloaders and other such things to run on the JVM</p>
    <p>
      On the other hand, you do get to keep and continue using many tools which are build for Scala but JVM-agnostic. For example, IDEs such a <a href="http://blog.jetbrains.com/scala/">IntelliJ</a> and <a href="http://scala-ide.org/">Eclipse</a> work great with Scala.js; from their point of view, it's just Scala, and things like code-navigation, refactoring and error-highlighting all work out of the box. SBT works with Scala.js too, and you see the same compile-erorrs in the command-line as you would in vanilla Scala, and even things like incremental compilation work un-changed.</p>
    <p>
      Lastly, you gain access to browser tools that don't work with normal Scala: you can use the Chrome or Firefox consoles to poke at your Scala.js application from the command line, or their profilers/debuggers. With source maps set up, you can even step-through debug your Scala.js application directly in Chrome.</p>


  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="TheCompilationPipeline" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="TheCompilationPipeline">The Compilation Pipeline<a class=" scalatex-site-Styles-headerLink" href="#TheCompilationPipeline" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    

<p>
  Scala.js is implemented as a compiler plugin in the Scala compiler. Despite this, the overall process looks very different from that of a normal Scala application. This is because Scala.js optimizes for the size of the compiled executable, which is something that Scala-JVM does not usually do.
</p>
<h1 id="WholeProgramOptimizaton" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#WholeProgramOptimizaton" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Whole Program Optimizaton</h1>
  <p>
    At a first approximation, Scala.js achieves its tiny executables by using whole-program optimization. Scala-JVM, like Java, allows for separate compilation: this means that after compilation, you can combine your compiled code with code compiled separately, which can interact with the code you already compiled in an ad-hoc basis: code from both sides can call each others methods, instantiate each others classes, etc. without any limits.
</p>
  <p>
    Even things like package-private do not help you: Java packages are separate-compile-able too, and multiple compilation runs can dump things in the same package! You may think that private members and methods may be some salvation, but the Java ecosystem typically relies heavily on reflection, which depends on the fact that these private things remain exactly as-they-are.
</p>
  <p>
    Overall, this makes it difficult to do any meaningful optimization: you never know whether or not you can eliminate a class, method or field. Even if it's not used anywhere you can see, it could easily be used by some other code compiled separately, or accessed through reflection.
</p>
  <p>
    With Scala.js, we have decided to forgo reflection, and forgo separate compilation, in exchange for smaller executables. This is made easier by the fact that the pure-Scala ecosystem makes little use of reflection overall. Thus, at the right before shipping your Scala.js app to your users, the Scala.js optimizer gathers up all your Scala.js code, determines which things are used and which are not, and eliminates all the un-used classes/methods/variables. This allows us to achieve a much smaller code size than is possible with reflection/separate-compilation support. Furthermore, because we forgo these two things, we can perform much more aggressive inlining and other compile-time optimizations than is possible with Scala-JVM, further reducing code size and improving performance.
</p>
  <p>
    It's worth noting that such optimizations exist as an option on the JVM aswell: <a href="http://proguard.sourceforge.net/">Proguard</a> is a well known library for doing similar DCE/optimization for Java/Scala applications, and is extensively used in developing mobile applications which face similar &quot;minimize-code-size&quot; constraints that web-apps do. However, the bulk of Scala code which runs on the server does not use these tools.
</p>
<h1 id="HowCompilationWorks" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#HowCompilationWorks" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>How Compilation Works</h1>
  <p>
    The Scala.js compilation pipeline is roughly split into multiple stages:
</p>
  <ul>
    <li>
      <b>Initial Compilation</b>: <code>.scala</code> files to <code>.class</code> and <code>.sjsir</code> files</li>
    <li>
      <b>Fast Optimization</b>: <code>.sjsir</code> files to one smallish/fast <code>.js</code> file, or</li>
    <li>
      <b>Full Optimization</b>: <code>.sjsir</code> files to one smaller/faster <code>.js</code> file
</li></ul>
  <p>
    <code>.scala</code> files are the source code you're familiar with. <code>.class</code> files are the JVM-targetted artifacts which aren't used for actually producing <code>.js</code> files, but are kept around for pretty much everything else: the compiler uses them for separate compilation and macros, and tools such as <a href="http://blog.jetbrains.com/scala/">IntelliJ</a> or <a href="http://scala-ide.org/">Eclipse</a> use these files to provide IDE support for Scala.js code. <code>.js</code> files are the output Javascript, which we can execute in a web browser.</p>
  <p>
    <code>.sjsir</code> files are worth calling out: the name stands for &quot;ScalaJS Intermediate Representation&quot;, and these files contain compiled code half-way between Scala and Javascript: most Scala features have by this point been replaced by their Java/Javascript equivalents, but it still contains Types (which have all been inferred) that can aid in analysis. Many Scala.js specific optimizations take place on this IR.
</p>
  <p>
    Each stage has a purpose, and together the stages do bring benefits to offset their cost in complexity. The original compilation pipeline was much more simple:
</p>
  <ul>
    <li>
      <b>Compilation</b>: <code>.scala</code> files to <code>.js</code> files
</li></ul>
  <p>
    But produced far larger (20mb) and slower executables. This section will explore each stage and we'll learn what these stages do, starting with a small example program:
</p>
  <pre><code class="scala scalatex-site-Styles-highlightMe">def main() = {
  var x = 0
  while(x &lt; 999){
    x = x + &quot;2&quot;.toInt
  }
  println(x)
}
</code></pre>
  <h2 id="Compilation" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Compilation" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Compilation</h2>
    <p>
      As described earlier, the Scala.js compiler is implemented as a Scala compiler plugin, and lives in the main repository in <a href="https://github.com/scala-js/scala-js/tree/master/compiler">compiler/</a>. The bulk of the plugin runs after the <code>mixin</code> phase in the <a href="http://stackoverflow.com/a/4528092/871202">Scala compilation pipeline</a>. By this point:
</p>
    <ul>
      <li>
        Types and implicits have all been inferred</li>
      <li>
        Pattern-matches have been compiled to imperative code</li>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@tailrec</code> functions have been translated to while-loops, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">lazy val</code>s have been replaced by <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">var</code>s.</li>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">trait</code>s have been <a href="http://stackoverflow.com/a/2558317/871202">replaced by interfaces and classes</a>
</li></ul>
    <p>
      Overall, by the time the Scala.js compiler plugin takes action, most of the high-level features of the Scala language have already been removed. Compared to a hypothetical, alternative &quot;from scratch&quot; implementation, this approach has several advantages:
</p>
    <ul>
      <li>
        It helps ensure that the semantics of these features always, 100% match that of Scala-JVM</li>
      <li>
        It reduces the amount of implementation work required by re-using the existing compilation phases
</li></ul>
    <p>
      This first phase is mostly a translation from the Scala compiler's internal AST to the Scala.js Intermediate Representation, and does not contain very many interesting optimizations. At the end of the initial compilation, the Scala compiler with Scala.js plugin results in two sets of files:
</p>
    <ul>
      <li>
        The original <code>.class</code> files, <i>almost</i> as if they were compiled on the JVM, but not quite. They are sufficiently valid that the compiler can execute macros defined in them, but they should not be used to actually run.</li>
      <li>
        The <code>.sjsir</code> files, destined for further compilation in the Scala.js pipeline.
</li></ul>
    <p>
      The ASTs defined in the <code>.sjsir</code> files is at about the same level of abstraction as the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Tree</code>s that the Scala compiler is working with at this stage. However, the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Tree</code>s within the Scala compiler contain a lot of cruft related to the compiler internals, and are also not easily serializable. This phase cleans them up into a &quot;purer&quot; format, (defined in the <a href="https://github.com/scala-js/scala-js/blob/master/ir/src/main/scala/scala/scalajs/ir/Trees.scala">ir/</a> folder) which is also serializable.
</p>
    <p>
      This is the only phase in the Scala.js compilation pipeline that separate compilation is possible: you can compile many different sets of Scala.js <code>.scala</code> files separately, only to combine them later. This is used e.g. for distributing Scala.js libraries as Maven Jars, which are compiled separately by library authors to be combined into a final executable later.
</p>
  <h2 id="FastOptimization" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#FastOptimization" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Fast Optimization</h2>
    <p>
      Without optimizations, the actual JavaScript code emitted for the above snippet would look like this:</p>
    <pre><code class="javascript scalatex-site-Styles-highlightMe">ScalaJS.c.Lexample_ScalaJSExample$.prototype.main__V = (function() {
  var x = 0;
  while ((x &lt; 999)) {
    x = ((x + new ScalaJS.c.sci_StringOps().init___T(
      ScalaJS.m.s_Predef$().augmentString__T__T(&quot;2&quot;)).toInt__I()) | 0)
  };
  ScalaJS.m.s_Predef$().println__O__V(x)
});</code></pre>
    <p>
      This is a pretty straightforward translation from the intermediate reprensentation into vanilla JavaScript code:
</p>
    <ul>
      <li>
        Scala-style method <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">def</code>s become Javascript-style prototype-function-assignment</li>
      <li>
        Scala <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">val</code>s and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">var</code>s become Javascript <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">var</code>s</li>
      <li>
        Scala <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">while</code>s become Javascript <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">while</code>s</li>
      <li>
        Implicits are materialized, hence all the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">StringOps</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">augmentString</code> extensions are present in the output</li>
      <li>
        Classes and methods are fully-qualified, e.g. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">println</code> becomes <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Predef().println</code></li>
      <li>
        Method names are qualified by their types, e.g. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">__O__V</code> means that <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">println</code> takes <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Object</code> and returns <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">void</code>
</li></ul>
    <p>
      This is an incomplete description of the translation, but it should give a good sense of how the translation from Scala to Javascript looks like. In general, the output is verbose but straightforward.
</p>
    <p>
      In addition to this superficial translation, the optimizer does a number of things which are more subtle and vary from case to case. Without diving into too much detail, here are a few optimizations that are performed:
</p>
    <ul>
      <li>
        <b>Dead-code elimination</b>: entry-points to the program such as <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@JSExport</code>ed methods/classes are kept, as are any methods/classes that these reference. All others are removed. This reduces the potentially 20mb of Javascript generated by a naive compilation to a more manageable 400kb-1mb for a typical application</li>
      <li>
        <b>Inlining</b>: under some circumstances, the optimizer inlines the implementation of methods at call sites. For example, it does so for all &quot;small enough&quot; methods. This typically reduces the code size by a small amount, but offers a several-times speedup of the generated code by inlining away much of the overhead from the abstractions (implicit-conversions, higher-order-functions, etc.) in Scala's standard library.</li>
      <li>
        <b>Constant-folding</b>: due to inlining and other optimizations, some variables that could have arbitrary values are known to contain a constant. These variables are replaced by their respective constants, which, in turn, can trigger more optimizations.</li>
      <li>
        <b>Closure elimination</b>: probably one of the most important optimizations. When inlining a higher-order method such as <code>map</code>, the optimizer can in turn inline the anonymous function inside the body of the loop, effectively turning polymorphic dispatch with closures into bare-metal loops.</li></ul>
    <p>
      Applying these optimizations on our examples results in the following JavaScript code instead, which is what you typically execute in fastOpt stage:
</p>
    <pre><code class="javascript scalatex-site-Styles-highlightMe">ScalaJS.c.Lexample_ScalaJSExample$.prototype.main__V = (function() {
  var x = 0;
  while ((x &lt; 999)) {
    var jsx$1 = x;
    var this$2 = new ScalaJS.c.sci_StringOps().init___T(&quot;2&quot;);
    var this$4 = ScalaJS.m.jl_Integer$();
    var s = this$2.repr$1;
    x = ((jsx$1 + this$4.parseInt__T__I__I(s, 10)) | 0)
  };
  var x$1 = x;
  var this$6 = ScalaJS.m.s_Console$();
  var this$7 = this$6.outVar$2;
  ScalaJS.as.Ljava_io_PrintStream(this$7.tl$1.get__O()).println__O__V(x$1)
});
</code></pre>
    <p>
      As a whole-program optimization, it tightly ties together the code it is compiling and does not let you e.g. inject additional classes later. This does not mean you cannot interact with external code at all: you can, but it has to go through explicitly <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@JSExport</code>ed methods and classes via Javascript Interop, and not on ad-hoc classes/methods within the module. Thus it's entirely possible to have multiple &quot;whole-programs&quot; running in the same browser; they just will likely have duplicate copies of e.g. standard library classes inside of them, since they cannot share the code as it's not exported.
</p>
    <p>
      While the input for this phase is the aggregate <code>.sjsir</code> files from your project and all your dependencies, the output is executable Javascript. This phase usually runs in less than a second, outputs a Javascript blob in the 400kb-1mb range, and is suitable for repeated use during development. This corresponds to the <code>fastOptJS</code> command in SBT.
</p>
  <h2 id="FullOptimization" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#FullOptimization" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Full Optimization</h2>
    <pre><code class="javascript scalatex-site-Styles-highlightMe">Fd.prototype.main = function() {
  for(var a = 0;999 &gt; a;) {
    var b = (new D).j(&quot;2&quot;);
    E();
    a = a + Ja(0, b.R) | 0
  }
  b = Xa(ed().pc.Sb);
  fd(b, gd(s(), a));
  fd(b, &quot;\n&quot;);
};
</code></pre>
    <p>
      The <a href="https://developers.google.com/closure/compiler/">Google Closure Compiler</a> (GCC) is a set of tools that work with Javascript. It has multiple <a href="https://developers.google.com/closure/compiler/docs/compilation_levels">levels of optimization</a>, doing everything from basic whitespace-removal to heavy optimization. It is an old, relatively mature project that is relied on both inside and outside Google to optimize the delivery of Javascript to the browser.
</p>
    <p>
      Scala.js uses GCC in its most aggressive mode: <a href="https://developers.google.com/closure/compiler/docs/api-tutorial3">Advanced Optimization</a>. GCC spits out a compressed, minified version of the Javascript (above) that <a href="#FastOptimization">Fast Optimization</a> spits out: e.g. in the example above, all identifiers have been renamed to short strings, the <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">while</code>-loop has been replaced by a <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">for</code>-loop, and the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">println</code> function has been inlined.
</p>
    <p>
      As described in the linked documentation, GCC performs optimizations such as:
</p>
    <ul>
      <li>
        Whitespace removal</li>
      <li>
        Variable and property renaming</li>
      <li>
        Dead code elimination</li>
      <li>
        Inlining
</li></ul>
    <p>
      Notably, GCC <i>does not preserve the semantics of arbitrary Javascript</i>! In particular, it only works for a subset of Javascript that it understands and can properly analyze. This is an issue when hand-writing Javascript for GCC since it's very easy to step outside that subset and have GCC break your code, but is not a worry when using Scala.js: the Scala.js optimizer (the previous phase in the pipeline) automatically outputs Javascript which GCC understands and can work with.</p>
    <p>
      There is some overlap between the optimizations performed by the Scala.js optimizer and GCC. For example, both apply DCE and inlining in some form. However, there are also a lot of optimizations specific to each tool. In general, the Scala.js optimizer is more concerned about producing very efficient JavaScript code, while GCC shines at making that JavaScript as small as possible (in terms of the number of characters).</p>
    <p>
      The combination of both these tools produces small and fast output blobs: ~100-400kb. This takes 5-10 seconds to run, which makes it somewhat slow for iterative development, so it's typically only run right before final testing and deployment. This corresponds to the <code>fullOptJS</code> command in SBT.
</p>
<hr />

<p>
  This hopefully has given a good overview of how the Scala.js compilation pipeline works. The pipeline and optimizer is a work-in-progress, and is changing all the time in an attempt to achieve ever-smaller executables and ever-faster code.
</p>
<p>
  This whole chapter has been focused on the <i>what</i> but not the <i>why</i>. The chapter on <a href="#Scala.js'DesignSpace">Scala.js' Design Space</a> contains a section which talks about <a href="#SmallExecutables">why we care so much about small executables</a>.</p>

  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="Scala.js'DesignSpace" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="Scala.js'DesignSpace">Scala.js' Design Space<a class=" scalatex-site-Styles-headerLink" href="#Scala.js'DesignSpace" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    

<p>
    Scala.js is a relatively large project, and is the result of both an enormous amount of hard work as well as a number of decisions that craft what it's like to program in Scala.js today. Many of these decisions result in marked differences from the behavior of the same code running on the JVM. This chapter explores the reasoning and rationale behind these decisions.

</p>
<h1 id="WhyNoReflection?" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#WhyNoReflection?" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Why No Reflection?</h1>
  <p>
    Scala.js prohibits reflection as it makes dead-code elimination difficult, and the compiler relies heavily on dead-code elimination to generate reasonably-sized executables. The chapter on <a href="#TheCompilationPipeline">The Compilation Pipeline</a> goes into more detail of why, but a rough estimate of the effect of various optimizations on a small application is:
</p>
  <ul>
    <li>
      <b>Full Output</b> - ~20mb</li>
    <li>
      <b>Naive Dead-Code-Elimnation</b> - ~800kb</li>
    <li>
      <b>Inlining Dead-Code-Elimnation</b> - ~600kb</li>
    <li>
      <b>Minified by Google Closure Compiler</b> - ~200kb
</li></ul>
  <p>
    The default output size of 20mb makes the executables difficult to work with. Even though browsers can deal with 20mb Javascript blobs, it takes the browser several seconds to even load it, and up to a minute after that for the JIT to optimize the whole thing.
</p>
  <h2 id="DeadCodeElimination" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#DeadCodeElimination" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Dead Code Elimination</h2>
    <p>
      To illustrate why reflection makes things difficult, consider a tiny application:
</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">@JSExport
object App extends js.JSApp{
  @JSExport
  def main() = {
    println(foo())
  }
  def foo() = 10
  def bar = &quot;i am a cow&quot;
}
object Dead{
  def complexFunction() = ...
}
</code></pre>
    <p>
      When the <a href="#FastOptimization">Scala.js optimizer</a>,  looks at this application, it is able to deduce certain things immediately:
</p>
    <ul>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.main</code> are exported via <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@JSExport</code>, and thus can't be considered dead code.</li>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.foo</code> is called from <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.main</code>, and so has to be kept around</li>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.bar</code> is never called from <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.main</code> or <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.foo</code>, and so can be eliminated</li>
      <li>
        <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Dead</code>, including <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Dead.complexFunction</code>, are not called from any live code, and can be eliminated.
</li></ul>
    <p>
      The actual process is a bit more involved than this, but this is a first-approximation of how the dead-code-elimination works: you start with a small set of live code (e.g. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@JSExport</code>ed things), search out to find the things which are recursively reachable from that set, and eliminate all the rest. This means that the Scala.js compiler can eliminate, e.g., parts of the Scala standard library that you are not using. The standard library is not small, and makes up the bulk of the 20mb of the uncompressed blob.
</p>
  <h2 id="WhitherReflection?" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#WhitherReflection?" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Whither Reflection?</h2>
    <p>
      To imagine why reflection makes this difficult, imagine a slightly modified program which includes some reflective calls in <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.main</code>
</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">@JSExport
object App extends js.JSApp{
  @JSExport
  def main() = {
    Class.forName(userInput()).getMethod(userInput()).invoke()
  }
  def foo() = 10
  def bar = &quot;i am a cow&quot;
}
object Dead{
  def complexFunction() = ...
}
</code></pre>
    <p>
      Here, we're assuming <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">userInput()</code> is some method which returns a <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">String</code> that was input by the user or otherwise somehow decided at runtime.</p>
    <p>
      We can start the same process: <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.main</code> is live since we <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@JSExport</code>ed it, but what objects or methods are reachable from <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.main</code>? The answer is: it depends on the values of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">userInput()</code>, which we don't know. And hence we don't know which classes or methods are reachable! Depending on what <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">userInput()</code> returns, any or all methods and classes could be used by <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">App.main()</code>.</p>
    <p>
      This leaves us a few options:
</p>
    <ul>
      <li>
        Keep every method or class around at runtime. This severely hampers the compiler's ability to optimize, and results in massive 20mb executables.</li>
      <li>
        Ignore reflection, and go ahead and eliminate/optimize things assuming reflection did not exist.</li>
      <li>
        Allow the user to annotate methods/classes that should be kept, and eliminate the rest.
</li></ul>
    <p>
      All three are possible options: Scala.js started off with #1. #3 is the approach used by <a href="http://proguard.sourceforge.net/manual/examples.html#annotated">Proguard</a>, which lets you annotate things e.g. <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">@KeepApplication</code> to preserve things for reflection and preventing Proguard from eliminating them as dead code.
</p>
    <p>
      In the end, Scala.js chose #2. This is helped by the fact that overall, Scala code tends not to use reflection as heavily as Java, or dynamic languages which use it heavily. Scala uses techniques such as <a href="http://docs.scala-lang.org/tutorials/tour/anonymous-function-syntax.html">lambdas</a> or <a href="http://docs.scala-lang.org/tutorials/tour/implicit-parameters.html">implicits</a> to satisfy many use cases which Java has traditionally used reflection for, while friendly to the optimizer.
</p>
    <p>
      There are a range of use-cases for reflection where you want to inspect an object's structure or methods, where lambdas or implicits don't help. People use reflection to <a href="http://jackson.codehaus.org/DataBindingDeepDive">serialize objects</a>, or for <a href="https://access.redhat.com/documentation/en-US/Fuse_ESB_Enterprise/7.1/html/Implementing_Enterprise_Integration_Patterns/files/BasicPrinciples-BeanIntegration.html">routing messages to methods</a>. However, both these cases can be satisfied by...
</p>
  <h2 id="Macros" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Macros" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Macros</h2>

    <p>
      The Scala programming language, since the 2.10.x series, has support for <a href="http://docs.scala-lang.org/overviews/macros/overview.html">Macros</a> in the language. Although experimental, these are heavily used in many projects such as Play and Slick and Akka, and allow a developer to perform compile-time computations and generate code where-ever the macros are used.
</p>
    <p>
      People typically think of macros as AST-transformers: you pass in an AST and get a modified AST out. However, in Scala, these ASTs are strongly-typed, and the macro is able to inspect the types involved in generating the output AST. This leads to a lot of <a href="http://docs.scala-lang.org/overviews/macros/implicits.html">interesting techniques</a> around macros where you synthesize ASTs based on the type (explicit or inferred) of the macro callsite, something that is impossible in dynamic languages.
</p>
    <p>
      Practically, this means that you can use macros to do things such as inspecting the methods, fields and other type-level properties of a typed value. This allows us to do things like <a href="https://github.com/lihaoyi/upickle">serialize objects with no boilerplate</a>:
</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">import upickle._

case class Thing(a: Int, b: String)
write(Thing(1, &quot;gg&quot;))
// res23: String = {&quot;a&quot;: 1, &quot;b&quot;: &quot;gg&quot;}
</code></pre>
    <p>
      Or to <a href="https://github.com/lihaoyi/autowire">route messages to the appropiate methods</a> without boilerplate, and <i>without</i> using reflection!
</p>
    <p>
      The fact that you can satisfy these use cases with macros is non-obvious: in dynamic languages, macros only get an AST, which is basically opaque when you're only passing a single value to it. With Scala, you get the value <i>together with it's type</i>, which lets you inspect the type and generate the proper serialization/routing code that is impossible to do in a dynamic language with macros.
</p>
    <p>
      Using macros here also plays well with the Scala.js optimizer: the macros are fully expanded before the optimizer is run, so by the time the optimizer sees the code, there is no more magic left: it is then free to do dead-code-elimination/inlining/other-optimizations without worrying about reflection causing the code to do weird things at runtime. Thus, we've managed to substitute most of the main use-cases of reflection, and so can do without it.
</p>
<h1 id="Whydoeserrorbehaviordiffer?" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Whydoeserrorbehaviordiffer?" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Why does error behavior differ?</h1>
  <p>
    Scala.js deviates from the semantics of Scala-JVM in several ways. Many of these ways revolve around the edge-conditions of a program: what happens when something goes wrong? An array index is out of bounds? An integer is divided-by-zero? These differences cause some amount of annoyance when debugging, since when you mess up an array index, you expect an exception, not silently-invalid-data!
</p>
  <p>
    In most of these cases, it was a trade-off between performance and correctness. These are situations where the default semantics of Scala deviate from that of Javascript, and Scala.js would have to perform extra work to emulate the desired behavior. For example, compare the division behavior of the JVM and Javascript.</p>
  <h2 id="Divide-by-zero:acasestudy" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#Divide-by-zero:acasestudy" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Divide-by-zero: a case study</h2>
    <pre><code class="scala scalatex-site-Styles-highlightMe">/*JVM*/
15 / 4              // 3</code></pre>
    <pre><code class="javascript scalatex-site-Styles-highlightMe">/*JS*/
15 / 4              // 3.25</code></pre>
    <p>
      On the JVM, integer division is a primitive, and dividing <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">15 / 4</code> gives <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">3</code>. However, in Javascript, it gives <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">3.25</code>, since all numbers of double-precision floating points.
</p>
    <p>
      Scala.js works around this in the general case by adding a <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">| 0</code> to the translation, e.g.
</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">/*JVM*/
15 / 4              // 3</code></pre>
    <pre><code class="javascript scalatex-site-Styles-highlightMe">/*JS*/
(15 / 4) | 0        // 3
</code></pre>
    <p>
      This gives the correct result for most numbers, and is reasonably efficient (actually, it tends to be <i>more</i> efficient on modern VMs). However, what about dividing-by-zero?
</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">/*JVM*/
15 / 0              // ArithmeticException</code></pre>
    <pre><code class="javascript scalatex-site-Styles-highlightMe">/*JS*/
15 / 0              // Infinity
(15 / 0) | 0        // 0
</code></pre>
    <p>
      On the JVM, the JVM is kind enough to throw an exception for you. However, in Javascript, the integer simply wraps around to <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">Infinity</code>, which then gets truncated down to zero.</p>
    <p>
      So that's the current behavior of integers in Scala.js. One may ask: can we fix it? And the answer is, we can:</p>
    <pre><code class="scala scalatex-site-Styles-highlightMe">/*JVM*/
1 / 0               // ArithmeticException</code></pre>
    <pre><code class="javascript scalatex-site-Styles-highlightMe">/*JS*/
function intDivide(x, y){
  var z = x / y
  if (z == Infinity) throw new ArithmeticException(&quot;Divide by Zero&quot;)
  else return z
}
intDivide(1, 0)     // ArithmeticException</code></pre>
    <p>
      This translation fixes the problem, and enforces that the <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">ArithmeticException</code> is thrown at the correct time. However, this approach causes some overhead: what was previously two primitive operations is now a function call, a local variable assignment, and a conditional. That is a lot more expensive than two primitive operations!
</p>
  <h2 id="ThePerformance/CorrectnessTradeoff" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#ThePerformance/CorrectnessTradeoff" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>The Performance/Correctness Tradeoff</h2>
    <p>
      In the end, a lot of the semantic differences listed here come down to the same tradeoff: we could make the code behave more-like-Scala, but at a cost of adding overhead via function calls and other checks. Furthermore, the cost is paid regardless of whether the &quot;exceptional case&quot; is triggered or not: in the example above, every division in the program pays the cost!</p>
    <p>
      The decision to not support these exceptional cases comes down to a value judgement: how often do people actually depend on an exception being thrown as part of their program semantics, e.g. by catching it and performing actions? And how often are they just a way of indicating bugs? It turns out that very few <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">ArithmeticException</code>s, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">ArrayIndexOutOfBoundsException</code>s, or similar are actually a necessary part of the program! They exist during debugging, but after that, these code paths are never relied upon &quot;in production&quot;.</p>
    <p>
      Thus Scala.js goes for a compromise: in the Fast Optimization mode, we run the code with all these checks in place (this is work in progress; currently only <code>asInstanceOf</code>s are thus checked), so as to catch cases where these errors occur close-to-the-source and make it easy for you to debug them. In Full Optimization mode, on the other hand, we remove these checks, assuming you've already ran through these cases and found any bugs during development.</p>
    <p>
      This is a common pattern in situations where there's a tradeoff between debuggability and speed. In Scala.js' case, it allows us to get good debuggability in development, as well as good performance in production. There's some loss in debuggability in development, sacrificed in exchange for greater performance.
</p>
<h1 id="SmallExecutables" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#SmallExecutables" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Small Executables</h1>
  Why do we care so much about how big our executables are in Scala.js? Why don't we care about how big they are on Scala-JVM? This is mostly due to three reasons:

  <ul>
    <li>
      When cross-compiling Scala to Javascript, the end-result tends to be much more verbose than when cross-compiled to Java Bytecode.</li>
    <li>
      Scala.js typically is run in web browsers, which typically do not work well with large executables compared to e.g. the JVM</li>
    <li>
      Scala.js often is delivered to many users over the network, and long download times force users to wait, degrading the user experience
</li></ul>
  <p>
    These factors combined means that Scala.js has to put in extra effort to optimize the code to reduce it's size at compile-time.
</p>
  <h2 id="RawVerbosity" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#RawVerbosity" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Raw Verbosity</h2>
    <p>
      Scala.js compiles to Javascript source code, while Scala-JVM compiles to Java bytecode. Java bytecode is a binary format and thus somewhat optimized for size, while Javascript is textual and is designed to be easy to read and write by hand.</p>
    <p>
      What does these mean, concretely? This means that a symbol marking something, e.g. the start of a function, is often a single byte in Java bytecode. Even more, it may not have any delimiter at all, instead the meaning of the binary data being inferred from its position in the file! On the other hand, in Javascript, declaring a function takes a long-and-verbose <code class="javascript scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">function</code> keyword, which together with peripheral punctuation (<code>.</code>, <code> = </code>, etc.) often adds up to tens of bytes to express a single idea.</p>
    <p>
      What does this mean concretely? This means that expressing the same meaning in Javascript usually takes more &quot;raw code&quot; than expressing the same meaning in Java bytecode. Even though Java bytecode is relatively verbose for a binary format, it still is significantly more concise the Javascript, and it shows: the Scala standard library weighs in at a cool 6mb on Scala-JVM, while it weighs 20mb on Scala.js.</p>
    <p>
      All things being equal, this would mean that Scala.js would have to work harder to keep down code-size than Scala-JVM would have to. Alas, not all other things are equal.
</p>
  <h2 id="BrowsersPerformance" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#BrowsersPerformance" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Browsers Performance</h2>
    <p>
      Without any optimization, a naive compilation to Scala.js results in an executable (Including the standard library) weighing around 20mb. On the surface, this isn't a problem: runtimes like the JVM have no issue with loading 20mb of Java bytecode to execute; many large desktop applications weigh in the 100s of megabytes while still loading and executing fine.</p>
    <p>
      However, the web browser isn't a native execution environment; loading 20mb of Javascript is sufficient to heavily tax even the most modern web browsers such as Chrome and Firefox. Even though most of the code comprises class and method definitions that never have their contents executed, loading such a heavy load into e.g. Chrome makes it freeze for 5-10 seconds initially. Even after that, even after the code has all been parsed and isn't been actively executed, having all this Javascript makes the browser sluggish for up to a minute before the JIT compiler can speed things up.</p>
    <p>
      Overall, this means that you probably do not want to work with un-optimized Scala.js executables. Even for development, the slow load times and initial sluggishness make testing the results of your hard-work in the browser a frustrating experience. But that's not all...
</p>
  <h2 id="DeploymentSize" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#DeploymentSize" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Deployment Size</h2>
    <p>
      Scala.js applications often run in the browser. Not just any browser, but the browsers of your users, who had come to your website or web-app to try and accomplish some task. This is in stark contrast the Scala-JVM applications, which most often run on servers: servers that you own and control, and can deploy code to at your leisure.
</p>
    <p>
      When running code on your own servers in some data center, you often do not care how big the compiled code is: the Scala standard library is several (6-7) megabytes, which added to your own code and any third-party libraries you're using, may add up to tens of megabytes, maybe a hundred or two if it's a relatively large application. Even that pales in comparison to the size of the JVM, which weighs in the 100s of megabytes.</p>
    <p>
      Even so, you are deploying your code on an machine (virtual or real) which has several gigabytes of memory and 100s of gigabytes of disk space. Even if the size of the code makes deployment slower, you only deploy fresh code a handful of times a day at most, and the size of your executable typically does not worry you.</p>
    <p>
      Scala.js is different: it runs in the browsers of your users. Before it can run in their browser, it first has to be downloaded, probably over a connection that is much slower than the one used to deploy your code to your servers or data-center. It probably is downloaded thousands of times per day, and every user which downloads it must pay the cost of waiting for it to finish downloading before they can take any actions on your website.
</p>
    <p>
      A typical website loads ~100kb-1mb of Javascript, and 1mb is on the heavy side. Most Javascript libraries weigh in on the order of 50-100kb. For Scala.js to be useful in the browser, it has to be able to compare favorably with these numbers.
</p>
  <hr />

  <p>
    Thus, while on Scala-JVM you typically have executables that (including dependencies) end up weighing 10s to 100s of megabytes, Scala.js has a much tighter budget. A hello world Scala.js application weighs in at around 100kb, and as you write more code and use more libraries (and parts of the standard library) this number rises to the 100s of kb. This isn't tiny, especially compared to the many small Javascript libraries out there, but it definitely is much smaller than what you'd be used to on the JVM.</p>


  <div style="margin: 0px;color: #333;text-align: center;padding: 2.5em 2em 0;border-bottom: 1px solid #eee;display: block;" id="JavaAPIs" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><h1 style="margin: 0.2em 0;font-size: 3em;font-weight: 300;" id="JavaAPIs">Java APIs<a class=" scalatex-site-Styles-headerLink" href="#JavaAPIs" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a></h1><br /></div>
    

<p>
  Below is a list of classes from the Java Standard Library that are available from Scala.js. In general, much of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">java.lang</code>, and parts of <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">java.io</code>, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">java.util</code> and <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">java.net</code> have been ported over. This means that all these classes are available for use in Scala.js applications despite being part of the Java standard library.</p>
<p>
  There are many reasons you may want to port a Java class to Scala.js: you want to use it directly, you may be trying to port a library which uses it. In general, we haven't been porting things &quot;for fun&quot;, and obscure classes like <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">org.omg.corba</code> will likely never be ported: we've been porting things as the need arises in order to support libraries (e.g. <a href="https://github.com/lihaoyi/scala.rx">Scala.Rx</a> that need them.
</p>
<h1 id="AvailableJavaAPIs" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#AvailableJavaAPIs" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Available Java APIs</h1>

  <ul>
    
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Appendable.html">java.lang.Appendable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/AutoCloseable.html">java.lang.AutoCloseable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html">java.lang.Boolean</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Byte.html">java.lang.Byte</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Character.html">java.lang.Character</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/CharSequence.html">java.lang.CharSequence</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html">java.lang.Class</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ClassLoader.html">java.lang.ClassLoader</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Cloneable.html">java.lang.Cloneable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html">java.lang.Comparable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Double.html">java.lang.Double</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Float.html">java.lang.Float</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/InheritableThreadLocal.html">java.lang.InheritableThreadLocal</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html">java.lang.Integer</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Long.html">java.lang.Long</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Math.html">java.lang.Math</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Number.html">java.lang.Number</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Readable.html">java.lang.Readable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html">java.lang.Runnable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html">java.lang.Runtime</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Short.html">java.lang.Short</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/StackTraceElement.html">java.lang.StackTraceElement</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuffer.html">java.lang.StringBuffer</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/StringBuilder.html">java.lang.StringBuilder</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/System.html">java.lang.System</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html">java.lang.Thread</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ThreadLocal.html">java.lang.ThreadLocal</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Throwables.html">java.lang.Throwables</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Void.html">java.lang.Void</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ref/PhantomReference.html">java.lang.ref.PhantomReference</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ref/Reference.html">java.lang.ref.Reference</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ref/ReferenceQueue.html">java.lang.ref.ReferenceQueue</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ref/SoftReference.html">java.lang.ref.SoftReference</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/ref/WeakReference.html">java.lang.ref.WeakReference</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/reflect/Array.html">java.lang.reflect.Array</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html">java.io.BufferedReader</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayInputStream.html">java.io.ByteArrayInputStream</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/ByteArrayOutputStream.html">java.io.ByteArrayOutputStream</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Closeable.html">java.io.Closeable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/DataInput.html">java.io.DataInput</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/FilterInputStream.html">java.io.FilterInputStream</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/FilterOutputStream.html">java.io.FilterOutputStream</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Flushable.html">java.io.Flushable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html">java.io.InputStream</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/InputStreamReader.html">java.io.InputStreamReader</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/OutputStream.html">java.io.OutputStream</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/OutputStreamWriter.html">java.io.OutputStreamWriter</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/PrintStream.html">java.io.PrintStream</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html">java.io.PrintWriter</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Reader.html">java.io.Reader</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html">java.io.Serializable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/StringReader.html">java.io.StringReader</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/StringWriter.html">java.io.StringWriter</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Throwables.html">java.io.Throwables</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html">java.io.Writer</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/net/URI.html">java.net.URI</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/net/URISyntaxException.html">java.net.URISyntaxException</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/Buffer.html">java.nio.Buffer</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/BufferOverflowException.html">java.nio.BufferOverflowException</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/BufferUnderflowException.html">java.nio.BufferUnderflowException</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/ByteBuffer.html">java.nio.ByteBuffer</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/ByteOrder.html">java.nio.ByteOrder</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/CharBuffer.html">java.nio.CharBuffer</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/HeapByteBuffer.html">java.nio.HeapByteBuffer</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/HeapCharBuffer.html">java.nio.HeapCharBuffer</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/InvalidMarkException.html">java.nio.InvalidMarkException</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/ReadOnlyBufferException.html">java.nio.ReadOnlyBufferException</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/StringCharBuffer.html">java.nio.StringCharBuffer</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/CharacterCodingException.html">java.nio.charset.CharacterCodingException</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html">java.nio.charset.Charset</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/CharsetDecoder.html">java.nio.charset.CharsetDecoder</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/CharsetEncoder.html">java.nio.charset.CharsetEncoder</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/CoderMalfunctionError.html">java.nio.charset.CoderMalfunctionError</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/CoderResult.html">java.nio.charset.CoderResult</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/CodingErrorAction.html">java.nio.charset.CodingErrorAction</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/MalformedInputException.html">java.nio.charset.MalformedInputException</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html">java.nio.charset.StandardCharsets</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/UnmappableCharacterException.html">java.nio.charset.UnmappableCharacterException</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/nio/charset/UnsupportedCharsetException.html">java.nio.charset.UnsupportedCharsetException</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html">java.util.Arrays</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html">java.util.Comparator</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Date.html">java.util.Date</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Formattable.html">java.util.Formattable</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/FormattableFlags.html">java.util.FormattableFlags</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html">java.util.Formatter</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Random.html">java.util.Random</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/Throwables.html">java.util.Throwables</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html">java.util.UUID</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Executor.html">java.util.concurrent.Executor</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/Throwables.html">java.util.concurrent.Throwables</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/TimeUnit.html">java.util.concurrent.TimeUnit</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicBoolean.html">java.util.concurrent.atomic.AtomicBoolean</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicInteger.html">java.util.concurrent.atomic.AtomicInteger</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicLong.html">java.util.concurrent.atomic.AtomicLong</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/AtomicReference.html">java.util.concurrent.atomic.AtomicReference</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html">java.util.regex.Matcher</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/regex/MatchResult.html">java.util.regex.MatchResult</a>
</li>
      <li>
        <a href="https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html">java.util.regex.Pattern</a>
</li></ul>
<h1 id="PortingJavaAPIs" style="display: block;" class=" scalatex-site-Styles-hoverContainer scalatex-site-Styles-headerTag"><a class=" scalatex-site-Styles-headerLink" href="#PortingJavaAPIs" style="position: absolute;right: 0px;"><i class="fa fa-link"></i></a>Porting Java APIs</h1>
  <p>
    The process for making Java library classes available in Scala.js is relatively straightforward:</p>
  <ul>
    <li>
      Find a class that you want to use in Scala.js, but is not implemented.</li>
    <li>
      Write a clean-room implementation in Scala, without looking at the source code of <a href="http://openjdk.java.net/">OpenJDK</a>. This is due to legal-software-license incompatibility between OpenJDK and Scala.js. Reading the docs or specification are fine, as is looking at the source of alternate implementations such as <a href="http://harmony.apache.org/">Harmony</a></li>
    <li>
      Submit a pull-request to the <a href="https://github.com/scala-js/scala-js">Scala.js repository</a>, including your implementation, together with tests. See the <a href="https://github.com/scala-js/scala-js/tree/master/test-suite/src/test/scala/org/scalajs/testsuite/javalib">existing tests</a> in the repository if you need examples of how to write your own.
</li></ul>
  <p>
    In general, this is a simple process, for &quot;pure-Java&quot; classes which do not use any special JVM/Java-specific APIs. However, this will not be possible for classes which do! This means that classes that make use of Java-specific things like:
</p>
  <ul>
    <li>
      Threads</li>
    <li>
      Filesystem APIs</li>
    <li>
      Network APIs</li>
    <li>
      <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">sun.misc.Unsafe</code>
</li></ul>
  <p>
    And other similar APIs will either need to be rewritten to not-use them. For example, <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">AtomicXXXs</code> can be written without threading/unsafe APIs because Javascript is single-threaded, making the implementation for e.g. an <code class="scala scalatex-site-Styles-highlightMe" style="display: inline;padding: 0px;margin: 0px;">AtomicBoolean</code> pretty trivial:
</p>
  <pre class=" scalatex-site-Styles-hoverContainer"><code class="scala scalatex-site-Styles-highlightMe">package java.util.concurrent.atomic

class AtomicBoolean(private[this] var value: Boolean) extends Serializable {
  def this() = this(false)

  final def get(): Boolean = value

  final def compareAndSet(expect: Boolean, update: Boolean): Boolean = {
    if (expect != value) false else {
      value = update
      true
    }
  }

  // For some reason, this method is not final
  def weakCompareAndSet(expect: Boolean, update: Boolean): Boolean =
    compareAndSet(expect, update)

  final def set(newValue: Boolean): Unit =
    value = newValue

  final def lazySet(newValue: Boolean): Unit =
    set(newValue)

  final def getAndSet(newValue: Boolean): Boolean = {
    val old = value
    value = newValue
    old
  }

  override def toString(): String =
    value.toString()
}</code><a class=" scalatex-site-Styles-headerLink" style="position: absolute;right: 0.5em;top: 0.5em;display: block;font-size: 24px;" href="https://github.com/scala-js/scala-js/blob/master/javalib/src/main/scala/java/util/concurrent/atomic/AtomicBoolean.scala#L0-L33" target="_blank"><i class="fa fa-link "></i></a></pre>

  <p>
    Others can't be ported at all (e.g. <code>java.io.File</code>) simply because the API capabilities they provide (blocking reads &amp; writes to files) do not exist in the Javascript runtime.
</p>
</div>
</div><script>
    scalatex.scrollspy.Controller().main(
      [{"value":"Hands-on Scala.js","children":[]},{"value":"Intro to Scala.js","children":[{"value":"About Javascript","children":[{"value":"Javascript-the-language","children":[]},{"value":"Javascript-the-platform","children":[]}]},{"value":"About Scala.js","children":[{"value":"The Language","children":[]},{"value":"Sharing Code","children":[]},{"value":"Client-Server Integration","children":[]}]}]},{"value":"Hands On","children":[{"value":"Getting Started","children":[{"value":"Opening up the Project","children":[]},{"value":"The Application Code","children":[]},{"value":"The Project Code","children":[{"value":"project/build.sbt","children":[]},{"value":"build.sbt","children":[]},{"value":"src/main/resources/index-dev.html","children":[]}]},{"value":"Publishing","children":[{"value":"Optimization","children":[]},{"value":"Blob Size","children":[]}]},{"value":"Recap","children":[]}]},{"value":"Making a Canvas App","children":[{"value":"Making a Sketchpad using Mouse Input","children":[]},{"value":"Making a Clock using setInterval","children":[]},{"value":"Tying it together: Flappy Box","children":[{"value":"Setting Up the Canvas","children":[]},{"value":"Defining our State","children":[]},{"value":"Game Logic","children":[]},{"value":"A Working Product","children":[]}]},{"value":"Canvas Recap","children":[{"value":"Development Speed","children":[]},{"value":"Full Scala","children":[]},{"value":"Seamless Javascript Interop","children":[]}]}]},{"value":"Interactive Web Pages","children":[{"value":"Hello World: HTML","children":[]},{"value":"Scalatags","children":[{"value":"User Input","children":[]},{"value":"Re-rendering","children":[]}]},{"value":"Using Web Services","children":[{"value":"Raw Javascript","children":[]},{"value":"dom.extensions","children":[]},{"value":"Parsing the Data","children":[]}]},{"value":"Tying it together: Weather Search","children":[]},{"value":"Interactive Web Pages Recap","children":[]}]},{"value":"The Command Line","children":[{"value":"Commands","children":[{"value":"The compile Command","children":[]},{"value":"The package Command","children":[]},{"value":"The fastOptJS Command","children":[]},{"value":"The fullOptJS Command","children":[]},{"value":"The run Command","children":[]},{"value":"The test Command","children":[]}]},{"value":"Headless Runtimes","children":[]},{"value":"Stages","children":[]}]},{"value":"Cross Publishing Libraries","children":[{"value":"A Simple Cross-Built Library","children":[{"value":"Build Configuration","children":[]},{"value":"Source Files","children":[]},{"value":"Running the Module","children":[]}]},{"value":"Further Work","children":[]},{"value":"Other Testing Libraries","children":[]}]},{"value":"Integrating Client-Server","children":[{"value":"A Client-Server Setup","children":[]},{"value":"Client-Server Reflections","children":[{"value":"Shared Templating","children":[]},{"value":"Shared Code","children":[]},{"value":"Boilerplate-free Serialization","children":[]}]},{"value":"What's Left?","children":[]},{"value":"Autowire","children":[{"value":"Setting up Autowire","children":[]},{"value":"Why Autowire?","children":[]}]}]}]},{"value":"In Depth","children":[{"value":"Advanced Techniques","children":[{"value":"Functional-Reactive UIs","children":[{"value":"Why FRP","children":[]},{"value":"FRP with Scala.Rx","children":[]},{"value":"More Rx","children":[]}]},{"value":"Asynchronous Workflows","children":[{"value":"Futures & Promises","children":[{"value":"Direct Use of XMLHttpRequest","children":[]},{"value":"Using dom.extensions.Ajax","children":[]},{"value":"Future Combinators","children":[]}]},{"value":"Scala-Async","children":[{"value":"Traditional Asynchrony","children":[]},{"value":"Using Scala-Async","children":[]}]}]}]},{"value":"Deviations from Scala-JVM","children":[{"value":"Language Differences","children":[{"value":"Primitive data types","children":[{"value":"Floats can behave as Doubles by default","children":[]},{"value":"toString of Float, Double and Unit","children":[]},{"value":"Runtime type tests are based on values","children":[]}]},{"value":"Undefined behaviors","children":[]},{"value":"Reflection","children":[]},{"value":"Regular expressions","children":[]},{"value":"Symbols","children":[]},{"value":"Enumerations","children":[]}]},{"value":"Library Differences","children":[{"value":"Standard Library","children":[]},{"value":"Macros v.s. Reflection","children":[]},{"value":"Pure-Scala v.s. Java Libraries","children":[]},{"value":"Javascript APIs v.s. JVM APIs","children":[]},{"value":"Scala/Browser tooling v.s. Java tooling","children":[]}]}]},{"value":"The Compilation Pipeline","children":[{"value":"Whole Program Optimizaton","children":[]},{"value":"How Compilation Works","children":[{"value":"Compilation","children":[]},{"value":"Fast Optimization","children":[]},{"value":"Full Optimization","children":[]}]}]},{"value":"Scala.js' Design Space","children":[{"value":"Why No Reflection?","children":[{"value":"Dead Code Elimination","children":[]},{"value":"Whither Reflection?","children":[]},{"value":"Macros","children":[]}]},{"value":"Why does error behavior differ?","children":[{"value":"Divide-by-zero: a case study","children":[]},{"value":"The Performance/Correctness Tradeoff","children":[]}]},{"value":"Small Executables","children":[{"value":"Raw Verbosity","children":[]},{"value":"Browsers Performance","children":[]},{"value":"Deployment Size","children":[]}]}]},{"value":"Java APIs","children":[{"value":"Available Java APIs","children":[]},{"value":"Porting Java APIs","children":[]}]}]}]
  )</script><script>
    ['DOMContentLoaded', 'load'].forEach(function(ev){
      addEventListener(ev, function(){
        Array.prototype.forEach.call(
          document.getElementsByClassName('scalatex-site-Styles-highlightMe'),
          hljs.highlightBlock
        );
      })
    })
  </script></body></body></html>