Commit b25d4e26 authored by Pascal Hartig's avatar Pascal Hartig

Merge branch 'slegrand45-js_of_ocaml'

Close #1339
parents 3684cb8b d4453387
......@@ -30,6 +30,7 @@
"examples/duel/www/**",
"examples/duel/src/main/webapp/js/lib/**",
"examples/polymer/elements/elements.build.js",
"examples/js_of_ocaml/js/*.js",
"**/generated/**"
],
"requireSpaceBeforeBlockStatements": true,
......
#!/bin/sh
# Compile OCaml source file to OCaml bytecode
ocamlbuild -use-ocamlfind \
-tags "warn(-40)" \
-pkgs lwt.syntax,js_of_ocaml,js_of_ocaml.syntax,js_of_ocaml.tyxml,tyxml,js_of_ocaml.deriving,js_of_ocaml.deriving.syntax,deriving \
-syntax camlp4o \
todomvc.byte ;
# Build JS code from the OCaml bytecode
js_of_ocaml +weak.js --opt 3 -o js/todomvc.js todomvc.byte
<!doctype html>
<html lang="en" data-framework="js_of_ocaml">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Js_of_ocaml • TodoMVC</title>
<link rel="stylesheet" href="node_modules/todomvc-common/base.css">
<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
</head>
<body>
<div id="todomvc"></div>
<script src="js/todomvc.js"></script>
<script src="node_modules/todomvc-common/base.js"></script>
</body>
</html>
This source diff could not be displayed because it is too large. You can view the blob instead.
html,
body {
margin: 0;
padding: 0;
}
button {
margin: 0;
padding: 0;
border: 0;
background: none;
font-size: 100%;
vertical-align: baseline;
font-family: inherit;
font-weight: inherit;
color: inherit;
-webkit-appearance: none;
appearance: none;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
font-smoothing: antialiased;
}
body {
font: 14px 'Helvetica Neue', Helvetica, Arial, sans-serif;
line-height: 1.4em;
background: #f5f5f5;
color: #4d4d4d;
min-width: 230px;
max-width: 550px;
margin: 0 auto;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
font-smoothing: antialiased;
font-weight: 300;
}
button,
input[type="checkbox"] {
outline: none;
}
.hidden {
display: none;
}
.todoapp {
background: #fff;
margin: 130px 0 40px 0;
position: relative;
box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2),
0 25px 50px 0 rgba(0, 0, 0, 0.1);
}
.todoapp input::-webkit-input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::-moz-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp input::input-placeholder {
font-style: italic;
font-weight: 300;
color: #e6e6e6;
}
.todoapp h1 {
position: absolute;
top: -155px;
width: 100%;
font-size: 100px;
font-weight: 100;
text-align: center;
color: rgba(175, 47, 47, 0.15);
-webkit-text-rendering: optimizeLegibility;
-moz-text-rendering: optimizeLegibility;
text-rendering: optimizeLegibility;
}
.new-todo,
.edit {
position: relative;
margin: 0;
width: 100%;
font-size: 24px;
font-family: inherit;
font-weight: inherit;
line-height: 1.4em;
border: 0;
outline: none;
color: inherit;
padding: 6px;
border: 1px solid #999;
box-shadow: inset 0 -1px 5px 0 rgba(0, 0, 0, 0.2);
box-sizing: border-box;
-webkit-font-smoothing: antialiased;
-moz-font-smoothing: antialiased;
font-smoothing: antialiased;
}
.new-todo {
padding: 16px 16px 16px 60px;
border: none;
background: rgba(0, 0, 0, 0.003);
box-shadow: inset 0 -2px 1px rgba(0,0,0,0.03);
}
.main {
position: relative;
z-index: 2;
border-top: 1px solid #e6e6e6;
}
label[for='toggle-all'] {
display: none;
}
.toggle-all {
position: absolute;
top: -55px;
left: -12px;
width: 60px;
height: 34px;
text-align: center;
border: none; /* Mobile Safari */
}
.toggle-all:before {
content: '❯';
font-size: 22px;
color: #e6e6e6;
padding: 10px 27px 10px 27px;
}
.toggle-all:checked:before {
color: #737373;
}
.todo-list {
margin: 0;
padding: 0;
list-style: none;
}
.todo-list li {
position: relative;
font-size: 24px;
border-bottom: 1px solid #ededed;
}
.todo-list li:last-child {
border-bottom: none;
}
.todo-list li.editing {
border-bottom: none;
padding: 0;
}
.todo-list li.editing .edit {
display: block;
width: 506px;
padding: 13px 17px 12px 17px;
margin: 0 0 0 43px;
}
.todo-list li.editing .view {
display: none;
}
.todo-list li .toggle {
text-align: center;
width: 40px;
/* auto, since non-WebKit browsers doesn't support input styling */
height: auto;
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
border: none; /* Mobile Safari */
-webkit-appearance: none;
appearance: none;
}
.todo-list li .toggle:after {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#ededed" stroke-width="3"/></svg>');
}
.todo-list li .toggle:checked:after {
content: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="40" height="40" viewBox="-10 -18 100 135"><circle cx="50" cy="50" r="50" fill="none" stroke="#bddad5" stroke-width="3"/><path fill="#5dc2af" d="M72 25L42 71 27 56l-4 4 20 20 34-52z"/></svg>');
}
.todo-list li label {
white-space: pre;
word-break: break-word;
padding: 15px 60px 15px 15px;
margin-left: 45px;
display: block;
line-height: 1.2;
transition: color 0.4s;
}
.todo-list li.completed label {
color: #d9d9d9;
text-decoration: line-through;
}
.todo-list li .destroy {
display: none;
position: absolute;
top: 0;
right: 10px;
bottom: 0;
width: 40px;
height: 40px;
margin: auto 0;
font-size: 30px;
color: #cc9a9a;
margin-bottom: 11px;
transition: color 0.2s ease-out;
}
.todo-list li .destroy:hover {
color: #af5b5e;
}
.todo-list li .destroy:after {
content: '×';
}
.todo-list li:hover .destroy {
display: block;
}
.todo-list li .edit {
display: none;
}
.todo-list li.editing:last-child {
margin-bottom: -1px;
}
.footer {
color: #777;
padding: 10px 15px;
height: 20px;
text-align: center;
border-top: 1px solid #e6e6e6;
}
.footer:before {
content: '';
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 50px;
overflow: hidden;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2),
0 8px 0 -3px #f6f6f6,
0 9px 1px -3px rgba(0, 0, 0, 0.2),
0 16px 0 -6px #f6f6f6,
0 17px 2px -6px rgba(0, 0, 0, 0.2);
}
.todo-count {
float: left;
text-align: left;
}
.todo-count strong {
font-weight: 300;
}
.filters {
margin: 0;
padding: 0;
list-style: none;
position: absolute;
right: 0;
left: 0;
}
.filters li {
display: inline;
}
.filters li a {
color: inherit;
margin: 3px;
padding: 3px 7px;
text-decoration: none;
border: 1px solid transparent;
border-radius: 3px;
}
.filters li a.selected,
.filters li a:hover {
border-color: rgba(175, 47, 47, 0.1);
}
.filters li a.selected {
border-color: rgba(175, 47, 47, 0.2);
}
.clear-completed,
html .clear-completed:active {
float: right;
position: relative;
line-height: 20px;
text-decoration: none;
cursor: pointer;
position: relative;
}
.clear-completed:hover {
text-decoration: underline;
}
.info {
margin: 65px auto 0;
color: #bfbfbf;
font-size: 10px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.5);
text-align: center;
}
.info p {
line-height: 1;
}
.info a {
color: inherit;
text-decoration: none;
font-weight: 400;
}
.info a:hover {
text-decoration: underline;
}
/*
Hack to remove background from Mobile Safari.
Can't use it globally since it destroys checkboxes in Firefox
*/
@media screen and (-webkit-min-device-pixel-ratio:0) {
.toggle-all,
.todo-list li .toggle {
background: none;
}
.todo-list li .toggle {
height: 40px;
}
.toggle-all {
-webkit-transform: rotate(90deg);
transform: rotate(90deg);
-webkit-appearance: none;
appearance: none;
}
}
@media (max-width: 430px) {
.footer {
height: 50px;
}
.filters {
bottom: 10px;
}
}
{
"name": "todomvc-app-css",
"version": "2.0.1",
"description": "CSS for TodoMVC apps",
"license": "CC-BY-4.0",
"repository": {
"type": "git",
"url": "https://github.com/tastejs/todomvc-app-css"
},
"author": {
"name": "Sindre Sorhus",
"email": "sindresorhus@gmail.com",
"url": "sindresorhus.com"
},
"files": [
"index.css"
],
"keywords": [
"todomvc",
"tastejs",
"app",
"todo",
"template",
"css",
"style",
"stylesheet"
],
"gitHead": "f1bb1aa9b19888f339055418374a9b3a2d4c6fc5",
"bugs": {
"url": "https://github.com/tastejs/todomvc-app-css/issues"
},
"homepage": "https://github.com/tastejs/todomvc-app-css",
"_id": "todomvc-app-css@2.0.1",
"scripts": {},
"_shasum": "f64d50b744a8a83c1151a08055b88f3aa5ccb052",
"_from": "todomvc-app-css@>=2.0.0 <3.0.0",
"_npmVersion": "2.5.1",
"_nodeVersion": "0.12.0",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
{
"name": "addyosmani",
"email": "addyosmani@gmail.com"
},
{
"name": "passy",
"email": "phartig@rdrei.net"
},
{
"name": "stephenplusplus",
"email": "sawchuk@gmail.com"
}
],
"dist": {
"shasum": "f64d50b744a8a83c1151a08055b88f3aa5ccb052",
"tarball": "http://registry.npmjs.org/todomvc-app-css/-/todomvc-app-css-2.0.1.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/todomvc-app-css/-/todomvc-app-css-2.0.1.tgz"
}
# todomvc-app-css
> CSS for TodoMVC apps
![](screenshot.png)
## Install
```
$ npm install --save todomvc-app-css
```
## Getting started
```html
<link rel="stylesheet" href="node_modules/todomvc-app-css/index.css">
```
See the [TodoMVC app template](https://github.com/tastejs/todomvc-app-template).
## License
<a rel="license" href="http://creativecommons.org/licenses/by/4.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by/4.0/80x15.png" /></a><br />This <span xmlns:dct="http://purl.org/dc/terms/" href="http://purl.org/dc/dcmitype/InteractiveResource" rel="dct:type">work</span> by <a xmlns:cc="http://creativecommons.org/ns#" href="http://sindresorhus.com" property="cc:attributionName" rel="cc:attributionURL">Sindre Sorhus</a> is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/4.0/deed.en_US">Creative Commons Attribution 4.0 International License</a>.
hr {
margin: 20px 0;
border: 0;
border-top: 1px dashed #c5c5c5;
border-bottom: 1px dashed #f7f7f7;
}
.learn a {
font-weight: normal;
text-decoration: none;
color: #b83f45;
}
.learn a:hover {
text-decoration: underline;
color: #787e7e;
}
.learn h3,
.learn h4,
.learn h5 {
margin: 10px 0;
font-weight: 500;
line-height: 1.2;
color: #000;
}
.learn h3 {
font-size: 24px;
}
.learn h4 {
font-size: 18px;
}
.learn h5 {
margin-bottom: 0;
font-size: 14px;
}
.learn ul {
padding: 0;
margin: 0 0 30px 25px;
}
.learn li {
line-height: 20px;
}
.learn p {
font-size: 15px;
font-weight: 300;
line-height: 1.3;
margin-top: 0;
margin-bottom: 0;
}
#issue-count {
display: none;
}
.quote {
border: none;
margin: 20px 0 60px 0;
}
.quote p {
font-style: italic;
}
.quote p:before {
content: '“';
font-size: 50px;
opacity: .15;
position: absolute;
top: -20px;
left: 3px;
}
.quote p:after {
content: '”';
font-size: 50px;
opacity: .15;
position: absolute;
bottom: -42px;
right: 3px;
}
.quote footer {
position: absolute;
bottom: -40px;
right: 0;
}
.quote footer img {
border-radius: 3px;
}
.quote footer a {
margin-left: 5px;
vertical-align: middle;
}
.speech-bubble {
position: relative;
padding: 10px;
background: rgba(0, 0, 0, .04);
border-radius: 5px;
}
.speech-bubble:after {
content: '';
position: absolute;
top: 100%;
right: 30px;
border: 13px solid transparent;
border-top-color: rgba(0, 0, 0, .04);
}
.learn-bar > .learn {
position: absolute;
width: 272px;
top: 8px;
left: -300px;
padding: 10px;
border-radius: 5px;
background-color: rgba(255, 255, 255, .6);
transition-property: left;
transition-duration: 500ms;
}
@media (min-width: 899px) {
.learn-bar {
width: auto;
padding-left: 300px;
}
.learn-bar > .learn {
left: 8px;
}
}
/* global _ */
(function () {
'use strict';
/* jshint ignore:start */
// Underscore's Template Module
// Courtesy of underscorejs.org
var _ = (function (_) {
_.defaults = function (object) {
if (!object) {
return object;
}
for (var argsIndex = 1, argsLength = arguments.length; argsIndex < argsLength; argsIndex++) {
var iterable = arguments[argsIndex];
if (iterable) {
for (var key in iterable) {
if (object[key] == null) {
object[key] = iterable[key];
}
}
}
}
return object;
}
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g,
escape : /<%-([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(text, data, settings) {
var render;
settings = _.defaults({}, settings, _.templateSettings);
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n";
try {
render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
return _;
})({});
if (location.hostname === 'todomvc.com') {
window._gaq = [['_setAccount','UA-31081062-1'],['_trackPageview']];(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];g.src='//www.google-analytics.com/ga.js';s.parentNode.insertBefore(g,s)}(document,'script'));
}
/* jshint ignore:end */
function redirect() {
if (location.hostname === 'tastejs.github.io') {
location.href = location.href.replace('tastejs.github.io/todomvc', 'todomvc.com');
}
}
function findRoot() {
var base = location.href.indexOf('examples/');
return location.href.substr(0, base);
}
function getFile(file, callback) {
if (!location.host) {
return console.info('Miss the info bar? Run TodoMVC from a server to avoid a cross-origin error.');
}
var xhr = new XMLHttpRequest();
xhr.open('GET', findRoot() + file, true);
xhr.send();
xhr.onload = function () {
if (xhr.status === 200 && callback) {
callback(xhr.responseText);
}
};
}
function Learn(learnJSON, config) {
if (!(this instanceof Learn)) {
return new Learn(learnJSON, config);
}
var template, framework;
if (typeof learnJSON !== 'object') {
try {
learnJSON = JSON.parse(learnJSON);
} catch (e) {
return;
}
}
if (config) {
template = config.template;
framework = config.framework;
}
if (!template && learnJSON.templates) {
template = learnJSON.templates.todomvc;
}
if (!framework && document.querySelector('[data-framework]')) {
framework = document.querySelector('[data-framework]').dataset.framework;
}
this.template = template;
if (learnJSON.backend) {
this.frameworkJSON = learnJSON.backend;
this.frameworkJSON.issueLabel = framework;
this.append({
backend: true
});
} else if (learnJSON[framework]) {
this.frameworkJSON = learnJSON[framework];
this.frameworkJSON.issueLabel = framework;
this.append();
}
this.fetchIssueCount();
}
Learn.prototype.append = function (opts) {
var aside = document.createElement('aside');
aside.innerHTML = _.template(this.template, this.frameworkJSON);
aside.className = 'learn';
if (opts && opts.backend) {
// Remove demo link
var sourceLinks = aside.querySelector('.source-links');
var heading = sourceLinks.firstElementChild;
var sourceLink = sourceLinks.lastElementChild;
// Correct link path
var href = sourceLink.getAttribute('href');
sourceLink.setAttribute('href', href.substr(href.lastIndexOf('http')));
sourceLinks.innerHTML = heading.outerHTML + sourceLink.outerHTML;
} else {
// Localize demo links
var demoLinks = aside.querySelectorAll('.demo-link');
Array.prototype.forEach.call(demoLinks, function (demoLink) {
if (demoLink.getAttribute('href').substr(0, 4) !== 'http') {
demoLink.setAttribute('href', findRoot() + demoLink.getAttribute('href'));
}
});
}
document.body.className = (document.body.className + ' learn-bar').trim();
document.body.insertAdjacentHTML('afterBegin', aside.outerHTML);
};
Learn.prototype.fetchIssueCount = function () {
var issueLink = document.getElementById('issue-count-link');
if (issueLink) {
var url = issueLink.href.replace('https://github.com', 'https://api.github.com/repos');
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
var parsedResponse = JSON.parse(e.target.responseText);
if (parsedResponse instanceof Array) {
var count = parsedResponse.length
if (count !== 0) {
issueLink.innerHTML = 'This app has ' + count + ' open issues';
document.getElementById('issue-count').style.display = 'inline';
}
}
};
xhr.send();
}
};
redirect();
getFile('learn.json', Learn);
})();
{
"name": "todomvc-common",
"version": "1.0.1",
"description": "Common TodoMVC utilities used by our apps",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/tastejs/todomvc-common"
},
"author": {
"name": "TasteJS"
},
"main": "base.js",
"files": [
"base.js",
"base.css"
],
"keywords": [
"todomvc",
"tastejs",
"util",
"utilities"
],
"gitHead": "a5e821ea0bd6974a827834eeae0e5e6e05538abd",
"bugs": {
"url": "https://github.com/tastejs/todomvc-common/issues"
},
"homepage": "https://github.com/tastejs/todomvc-common",
"_id": "todomvc-common@1.0.1",
"scripts": {},
"_shasum": "547af687c3152bb57eb2d3f7c527a0ef44e3c831",
"_from": "todomvc-common@>=1.0.0 <2.0.0",
"_npmVersion": "1.4.28",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
"maintainers": [
{
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
},
{
"name": "addyosmani",
"email": "addyosmani@gmail.com"
},
{
"name": "passy",
"email": "phartig@rdrei.net"
},
{
"name": "stephenplusplus",
"email": "sawchuk@gmail.com"
}
],
"dist": {
"shasum": "547af687c3152bb57eb2d3f7c527a0ef44e3c831",
"tarball": "http://registry.npmjs.org/todomvc-common/-/todomvc-common-1.0.1.tgz"
},
"directories": {},
"_resolved": "https://registry.npmjs.org/todomvc-common/-/todomvc-common-1.0.1.tgz"
}
# todomvc-common
> Common TodoMVC utilities used by our apps
## Install
```
$ npm install --save todomvc-common
```
## License
MIT © [TasteJS](http://tastejs.com)
{
"private": true,
"dependencies": {
"todomvc-app-css": "^2.0.0",
"todomvc-common": "^1.0.0"
}
}
# Js_of_ocaml TodoMVC Example
> Js_of_ocaml is a compiler of OCaml bytecode to Javascript.
## Resources
- [Website](http://ocsigen.org/js_of_ocaml/)
- [GitHub](https://github.com/ocsigen/js_of_ocaml)
- [Try Js_of_ocaml](http://try.ocamlpro.com/js_of_ocaml/)
## Support
Js_of_ocaml is part of [Ocsigen project](http://ocsigen.org/).
- [Mailing list](https://sympa.inria.fr/sympa/subscribe/ocsigen)
- IRC : #ocsigen on irc.freenode.net
## Implementation
Open `index.html` in your browser to try the application.
If you want to build the application on your own:
1. Install Js_of_ocaml and the required dependencies. An easy way is to use [opam](https://opam.ocaml.org/). After having installed `opam`, follow these steps:
- If you use `opam` for the first time, you have to initialize it:
```sh
> opam init
> eval `opam config env`
```
This will create a `.opam` directory in your home.
- You need a very recent version of OCaml compiler. First check the current version used by `opam`:
```sh
> opam switch
-- -- 3.11.2 Official 3.11.2 release
-- -- 3.12.1 Official 3.12.1 release
-- -- 4.00.0 Official 4.00.0 release
-- -- 4.00.1 Official 4.00.1 release
-- -- 4.01.0 Official 4.01.0 release
-- -- 4.02.0 Official 4.02.0 release
-- -- 4.02.1 Official 4.02.1 release
-- -- 4.02.2 Official 4.02.2 release
system C system System compiler (4.02.1)
```
The `C` letter shows the current compiler. Here it's a 4.02.1 version installed at a system level (ie in `/usr/local/bin/` for instance). We can see that a more recent version is available (4.02.2). So we will install it with `opam switch 4.02.2`. This won't remove the system compiler as `opam` will install the files in your `.opam` directory.
```sh
> opam switch 4.02.2
> eval `opam config env`
```
You can use again `opam switch` to check that the current compiler is now OCaml 4.02.2:
```sh
> opam switch
-- -- 3.11.2 Official 3.11.2 release
-- -- 3.12.1 Official 3.12.1 release
-- -- 4.00.0 Official 4.00.0 release
-- -- 4.00.1 Official 4.00.1 release
-- -- 4.01.0 Official 4.01.0 release
-- -- 4.02.0 Official 4.02.0 release
-- -- 4.02.1 Official 4.02.1 release
4.02.2 C 4.02.2 Official 4.02.2 release
system I system System compiler (4.02.1)
```
- Let's now install Js_of_ocaml and all the required dependencies. As Js_of_ocaml is a part of a larger project named Eliom, we will simply install this package:
```sh
> opam install eliom
```
- The final and important step is to be sure to have the latest version of Eliom and its dependencies. So ask to `opam` to upgrade the packages if needed:
```sh
> opam update
> opam upgrade
````
Congratulations, you now have all the required packages! We can now build the application.
2. Compile the `todomvc.ml` file to OCaml bytecode with the `ocamlbuild` command:
```sh
> ocamlbuild -use-ocamlfind \
-tags "warn(-40)" \
-pkgs lwt.syntax,js_of_ocaml,js_of_ocaml.syntax,js_of_ocaml.tyxml,tyxml,js_of_ocaml.deriving,js_of_ocaml.deriving.syntax,deriving \
-syntax camlp4o \
todomvc.byte ;
```
The command options are:
- `-use-ocamlfind` and `-pkgs ...` to use the necessary `ocamlfind` packages.
- `-tags "warn(-40)"` to avoid harmless warnings about constructor or label name used out of scope.
- `-syntax camlp4o` for the syntax extension support.
3. Build the Javascript file from the `todomvc.byte` file with the `js_of_ocaml` command:
```sh
> js_of_ocaml +weak.js --opt 3 -o js/todomvc.js todomvc.byte
```
The command options are:
- `+weak.js` to include the necessary `weak` package.
- `--opt 3` to set optimization profile.
- `-o js/todomvc.js` to set output file name.
Please note that for the second and third step, you can also use the `build.sh` script:
```sh
> /bin/sh build.sh
```
## Credit
Created by [Stéphane Legrand](https://github.com/slegrand45).
Various code improvements from [Gabriel Radanne](https://github.com/Drup).
Based on Elm implementation by [Evan Czaplicki](https://github.com/evancz).
open Lwt.Infix
(** Utility module for local storage. *)
module Storage = struct
open Js
let storage =
Optdef.case (Dom_html.window##localStorage)
(fun () -> failwith "Storage is not supported by this browser")
(fun v -> v)
let key = string "jsoo-todo-state"
let find () =
let r = storage##getItem(key) in
Opt.to_option @@ Opt.map r to_string
let set v = storage##setItem(key, string v)
let init default = match find () with
| None -> set default ; default
| Some v -> v
end
(** Application data *)
module Model = struct
type visibility =
Completed | Active | All
deriving (Json)
type task = {
description : string;
(* backup field keep the previous description to restore it when ESC key is pressed *)
backup : string;
completed : bool;
editing : bool;
id : int;
} deriving (Json)
type t = {
tasks : task list;
field : string;
uid : int;
visibility : visibility;
} deriving (Json) (* to save/restore the state in JSON *)
let empty = {
tasks = [];
field = "";
uid = 0;
visibility = All;
}
let new_task desc id = {
description = desc;
backup = desc;
completed = false;
editing = false;
id = id
}
let string_of_visibility v =
match v with
| Completed -> "Completed"
| Active -> "Active"
| All -> "All"
let from_json s =
Json.from_string<t> s
let to_json m =
Json.to_string<t> m
end
(** Utility module for routing *)
module Route = struct
let visibility_from_url url =
let fragment =
match url with
| Url.Http h
| Url.Https h -> h.hu_fragment
| Url.File f -> f.fu_fragment
in
match fragment with
| "/" -> Model.All
| "/active" -> Model.Active
| "/completed" -> Model.Completed
| _ -> Model.All
end
(** User interface actions *)
module Action = struct
type action =
| Update_field of Js.js_string Js.t
| Editing_task of (int * bool)
| Update_task of (int * Js.js_string Js.t)
| Add of Js.js_string Js.t
| Delete of int
| Delete_complete
| Check of (int * bool)
| Check_all of bool
| Change_visibility of Model.visibility
| Escape of int
end
(** The user actions are sent in this stream *)
let stream, (send_in_stream : Action.action option -> unit) = Lwt_stream.create ()
let send_some x = send_in_stream (Some x)
(** Build HTML and send user actions *)
module View = struct
open Action
open Tyxml_js
module Ev = Lwt_js_events
let bind_event ev elem handler =
let handler evt _ = handler evt in
Ev.(async @@ (fun () -> ev elem handler))
let task_input =
Html5.(input ~a:[
a_class ["new-todo"] ;
a_placeholder "What needs to be done?" ;
a_autofocus `Autofocus ;
] ())
let task_input_dom = To_dom.of_input task_input
(* New task input field *)
let task_entry =
bind_event Ev.inputs task_input_dom (fun _ ->
Lwt.return @@ send_some (Update_field task_input_dom##value)) ;
bind_event Ev.keypresses task_input_dom (fun evt ->
Lwt.return @@ if evt##keyCode = 13 then send_some (Add task_input_dom##value)) ;
Html5.(header ~a:[a_class ["header"]] [
h1 [ pcdata "todos" ];
task_input
])
let set_task_input v =
task_input_dom##value <- Js.string v
let focus_task_input () =
task_input_dom##focus ()
(** One item in the tasks list *)
let todo_item (todo:Model.task) =
let input_check =
Html5.(input ~a:(
let l = [
a_input_type `Checkbox ;
a_class ["toggle"] ;
a_onclick (fun _ ->
send_some (Check (todo.id, (not todo.completed))); true
)]
in if todo.completed then a_checked `Checked :: l else l
) ())
in
let input_edit =
Html5.(input ~a:[
a_input_type `Text ;
a_class ["edit"] ;
a_value todo.description ;
a_id (Printf.sprintf "todo-%u" todo.id) ;
a_onblur (fun _ ->
send_some (Editing_task (todo.Model.id, false)); true ) ;
] ())
in
let input_edit_dom = To_dom.of_input input_edit in
bind_event Ev.inputs input_edit_dom (fun _ ->
Lwt.return @@ send_some (Update_task (todo.id, input_edit_dom##value))) ;
let key_handler evt =
if evt##keyCode = 13 then
send_some (Editing_task (todo.id, false))
else if evt##keyCode = 27 then
send_some (Action.Escape todo.id)
else () ;
Lwt.return_unit
in
bind_event Ev.keypresses input_edit_dom key_handler ;
(* keydown needed to catch ESC key on Chrome *)
bind_event Ev.keydowns input_edit_dom key_handler ;
let css_class l =
let l = if todo.completed then "completed"::l else l in
if todo.editing then "editing"::l else l
in
Html5.(li ~a:[a_class (css_class [])] [
div ~a:[a_class ["view"]] [
input_check;
label ~a:[a_ondblclick (
fun evt -> send_some (Editing_task (todo.id, true)); true;
)] [pcdata todo.Model.description];
button ~a:[a_class ["destroy"]; a_onclick (
fun evt -> send_some (Delete todo.Model.id); true;
)] []
];
input_edit;
])
let focus_todo_item id =
let e = Dom_html.getElementById(Printf.sprintf "todo-%u" id) in
Js.Opt.case (Dom_html.CoerceTo.input e)
(fun e -> ()) (fun e -> e##focus ())
(** Build the tasks list *)
let task_list visibility tasks =
let is_visible todo =
match visibility with
| Model.Completed -> todo.Model.completed
| Active -> not todo.completed
| All -> true
in
let all_completed = List.for_all (fun e -> e.Model.completed) tasks in
let css_visibility =
match tasks with
| [] -> "visibility: hidden;"
| _ -> "visibility: visible;"
in
let toggle_input =
Html5.(input ~a:(
let l = [
a_input_type `Checkbox ;
a_class ["toggle-all"] ;
a_onclick (fun _ ->
send_some (Check_all (not all_completed)) ; true) ;
] in
if all_completed then a_checked `Checked :: l else l
) ())
in
Html5.(section ~a:[a_class ["main"]; a_style css_visibility] [
toggle_input;
label ~a:[a_for "toggle-all"] [pcdata "Mark all as complete"];
ul ~a:[a_class ["todo-list"]]
(List.rev_map todo_item (List.filter is_visible tasks))
])
let visibility_swap uri visibility actual_visibility =
let css =
if visibility = actual_visibility then ["selected"] else []
in
Html5.(li ~a:[a_onclick (fun evt ->
send_some (Change_visibility visibility); true;
)] [
a ~a:[a_href uri; a_class css]
[pcdata (Model.string_of_visibility visibility)]
])
let controls visibility tasks =
let open Html5 in
let tasks_completed, tasks_left = List.partition (fun e -> e.Model.completed) tasks in
let item = if (List.length tasks_left = 1) then " item" else " items" in
let a_footer = [a_class ["footer"]] in
let a_footer =
match tasks with
| [] -> (a_hidden `Hidden) :: a_footer
| _ -> a_footer
in
let a_button = [a_class ["clear-completed"]; a_onclick (
fun evt -> send_in_stream (Some(Delete_complete)); true;
)] in
let a_button =
match tasks_completed with
| [] -> (a_hidden `Hidden) :: a_button
| _ -> a_button
in
let html =
footer ~a:a_footer [
span ~a:[a_class ["todo-count"]] [
strong ~a:[] [pcdata (string_of_int (List.length tasks_left))];
pcdata (item ^ " left")
];
ul ~a:[a_class ["filters"]] [
visibility_swap "#/" Model.All visibility;
visibility_swap "#/active" Model.Active visibility;
visibility_swap "#/completed" Model.Completed visibility;
];
button ~a:a_button [
pcdata "Clear completed"
]
]
in
html
let info_footer =
Html5.(footer ~a:[a_class ["info"]] [
p [pcdata "Double-click to edit a todo"];
p [
pcdata "Written by ";
a ~a:[a_href "https://stephanelegrand.wordpress.com/"] [pcdata "Stéphane Legrand"]
];
p [
pcdata "Various code improvements from ";
a ~a:[a_href "https://github.com/Drup"] [pcdata "Gabriel Radanne"]
];
p [
pcdata "Based on ";
a ~a:[a_href "https://github.com/evancz"] [pcdata "Elm implementation by Evan Czaplicki"]
];
p [
pcdata "Part of ";
a ~a:[a_href "http://todomvc.com"] [pcdata "TodoMVC"]
]
])
(** Build the HTML for the application *)
let view m =
Html5.(
div ~a:[a_class ["todomvc-wrapper"]] [
section ~a:[a_class ["todoapp"]] [
task_entry ;
task_list m.Model.visibility m.Model.tasks ;
controls m.Model.visibility m.Model.tasks
];
info_footer
])
let refresh parent m =
let rec remove_children () =
Js.Opt.iter (parent##firstChild)
(fun e -> Dom.removeChild parent e; remove_children ())
in
remove_children () ;
Dom.appendChild parent (Tyxml_js.To_dom.of_div (view m))
end
(** Manage actions, refresh view if needed and save the state in local storage *)
module Controler =
struct
let update parent a m =
let open Action in
let open Model in
let m = match a with
| Add field ->
let field = Js.to_string field in
let uid = m.uid + 1 in
let tasks =
let v = String.trim field in
if v = "" then m.tasks
else (new_task v m.uid) :: m.tasks
in
{ m with uid = uid; field = ""; tasks = tasks }
| Update_field field ->
{ m with field = Js.to_string field }
| Editing_task (id, is_edit) ->
let update_task t =
if (t.id = id) then
let v = String.trim t.description in
{ t with editing = is_edit; description = v; backup = v }
else { t with editing = false }
in
let l = List.map update_task m.tasks in
let l = List.filter (fun e -> e.description <> "") l in
{ m with tasks = l }
| Update_task (id, task) ->
let update_task t =
if (t.id = id) then { t with description = Js.to_string task }
else t
in
{ m with tasks = List.map update_task m.tasks }
| Delete id ->
{ m with tasks = List.filter (fun e -> e.id <> id) m.tasks }
| Delete_complete ->
{ m with tasks = List.filter (fun e -> not e.completed) m.tasks }
| Check (id, is_compl) ->
let update_task t =
if (t.id = id) then { t with completed = is_compl }
else t
in
{ m with tasks = List.map update_task m.tasks }
| Check_all is_compl ->
let update_task t =
{ t with completed = is_compl }
in
{ m with tasks = List.map update_task m.tasks }
| Change_visibility visibility ->
{ m with visibility = visibility }
| Escape id ->
let unedit_task t =
if (t.id = id) then { t with editing = false; description = t.backup }
else t
in
{ m with tasks = List.map unedit_task m.tasks }
in
begin match a with
| Add _ -> View.set_task_input "" ;
| _ -> ()
end ;
begin match a with
| Update_field _
| Update_task _ -> ()
| _ -> View.refresh parent m
end ;
begin match a with
| Update_field _
| Update_task _ -> ()
| Editing_task (_, is_edit) ->
if not is_edit then View.focus_task_input ()
| _ -> View.focus_task_input () ;
end ;
begin match a with
| Editing_task (id, is_edit) ->
if is_edit then View.focus_todo_item id
| _ -> ();
end ;
Storage.set @@ Model.to_json m ;
m
end
let main _ =
let doc = Dom_html.document in
let parent =
Js.Opt.get (doc##getElementById(Js.string "todomvc"))
(fun () -> assert false)
in
(* restore the saved state or empty state if not found *)
let m =
try
Model.from_json @@ Storage.init @@ Model.to_json Model.empty
with
| _ -> Model.empty
in
(* set the visibility by looking at the current url *)
let m =
match Url.Current.get() with
| None -> m
| Some u ->
let v = Route.visibility_from_url u in
{ m with Model.visibility = v }
in
(* init the view *)
View.refresh parent m ;
View.set_task_input m.Model.field ;
View.focus_task_input () ;
(* main loop *)
let rec run m =
try_lwt
lwt a = Lwt_stream.next stream in
let m = Controler.update parent a m in
run m
with
| Lwt_stream.Empty -> run m
in
run m
let onhashchanges evt _ =
let url = evt##newURL in
let url = Url.url_of_string (Js.to_string url) in
match url with
| None -> Lwt.return()
| Some u ->
let v = Route.visibility_from_url u in
send_some (Change_visibility v);
Lwt.return()
let _ = Lwt_js_events.onhashchanges onhashchanges
let _ = Lwt_js_events.onload () >>= main
......@@ -167,6 +167,9 @@
<li class="routing">
<a href="examples/scalajs-react/" data-source="https://github.com/japgolly/scalajs-react" data-content="Facebook's React on Scala.js.">Scala.js + React</a>
</li>
<li class="routing">
<a href="examples/js_of_ocaml/" data-source="http://ocsigen.org/js_of_ocaml/" data-content="Js_of_ocaml is a compiler of OCaml bytecode to Javascript.">js_of_ocaml</a>
</li>
</ul>
</div>
<div class="js-app-list" data-app-list="labs">
......
......@@ -1101,6 +1101,28 @@
"url": "examples/vanillajs"
}]
},
"js_of_ocaml": {
"name": "js_of_ocaml",
"description": "Js_of_ocaml is a compiler of OCaml bytecode to Javascript. It makes it possible to run Ocaml programs in a Web browser.",
"homepage": "ocsigen.org/js_of_ocaml/",
"examples": [{
"name": "Example",
"url": "examples/js_of_ocaml"
}],
"link_groups": [{
"heading": "Resources",
"links": [{
"name": "Manual",
"url": "https://ocsigen.org/js_of_ocaml/manual/"
}, {
"name": "GitHub",
"url": "https://github.com/ocsigen/js_of_ocaml"
}, {
"name": "StackOverflow",
"url": "https://stackoverflow.com/questions/tagged/js-of-ocaml"
}]
}]
},
"jquery": {
"name": "jQuery",
"description": "jQuery is a fast, small, and feature-rich JavaScript library. It makes things like HTML document traversal and manipulation, event handling, animation, and Ajax much simpler with an easy-to-use API that works across a multitude of browsers. With a combination of versatility and extensibility, jQuery has changed the way that millions of people write JavaScript.",
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment