on bc9b539 help sign in
elk/runtime/core.js
382 lines 12 kB history raw
2(function() {
3'use strict';
5var Display = { FULLSCREEN: 0, COMPONENT: 1, NONE: 2 };
8Elm.fullscreen = function(module, ports) {
9 var container = document.createElement('div');
10 document.body.appendChild(container);
11 return init(Display.FULLSCREEN, container, module, ports || {});
12};
14Elm.embed = function(module, container, ports) {
15 var tag = container.tagName;
16 if (tag !== 'DIV') {
17 throw new Error('Elm.node must be given a DIV, not a ' + tag + '.');
18 } else if (container.hasChildNodes()) {
19 throw new Error('Elm.node must be given an empty DIV. No children allowed!');
20 }
21 return init(Display.COMPONENT, container, module, ports || {});
22};
24Elm.worker = function(module, ports) {
25 return init(Display.NONE, {}, module, ports || {});
26};
28function init(display, container, module, ports, moduleToReplace) {
29 // defining state needed for an instance of the Elm RTS
30 var inputs = [];
32 /* OFFSET
33 * Elm's time traveling debugger lets you interrupt the smooth flow of time
34 * by pausing and continuing program execution. To ensure the user sees a
35 * program that moves smoothly through the pause/continue time gap,
36 * we need to adjsut the value of Date.now().
37 */
38 var timer = function() {
39 var inducedDelay = 0;
41 var now = function() {
42 return Date.now() - inducedDelay;
43 };
45 var addDelay = function(d) {
46 inducedDelay += d;
47 return inducedDelay;
48 };
50 return { now : now
51 , addDelay : addDelay
52 }
53 }();
55 var updateInProgress = false;
56 function notify(id, v) {
57 if (updateInProgress) {
58 throw new Error(
59 'The notify function has been called synchronously!\n' +
60 'This can lead to frames being dropped.\n' +
61 'Definitely report this to <https://github.com/elm-lang/Elm/issues>\n');
62 }
63 updateInProgress = true;
64 var timestep = timer.now();
65 for (var i = inputs.length; i--; ) {
66 inputs[i].recv(timestep, id, v);
67 }
68 updateInProgress = false;
69 }
70 function setTimeout(func, delay) {
71 window.setTimeout(func, delay);
72 }
74 var listeners = [];
75 function addListener(relevantInputs, domNode, eventName, func) {
76 domNode.addEventListener(eventName, func);
77 var listener = {
78 relevantInputs: relevantInputs,
79 domNode: domNode,
80 eventName: eventName,
81 func: func
82 };
83 listeners.push(listener);
84 }
86 var portUses = {}
87 for (var key in ports) {
88 portUses[key] = 0;
89 }
90 // create the actual RTS. Any impure modules will attach themselves to this
91 // object. This permits many Elm programs to be embedded per document.
92 var elm = {
93 notify: notify,
94 setTimeout: setTimeout,
95 node: container,
96 addListener: addListener,
97 inputs: inputs,
98 timer: timer,
99 ports: { incoming:ports, outgoing:{}, uses:portUses },
101 isFullscreen: function() { return display === Display.FULLSCREEN; },
102 isEmbed: function() { return display === Display.COMPONENT; },
103 isWorker: function() { return display === Display.NONE; }
104 };
106 function swap(newModule) {
107 removeListeners(listeners);
108 var div = document.createElement('div');
109 var newElm = init(display, div, newModule, ports, elm);
110 inputs = [];
111 // elm.swap = newElm.swap;
112 return newElm;
113 }
115 function dispose() {
116 removeListeners(listeners);
117 inputs = [];
118 }
120 var Module = {};
121 var reportAnyErrors = function() {};
122 try {
123 Module = module.make(elm);
124 checkPorts(elm);
125 } catch(e) {
126 var directions = "<br/>&nbsp; &nbsp; Open the developer console for more details."
127 Module.main = Elm.Text.make(elm).leftAligned('<code>' + e.message + directions + '</code>');
128 reportAnyErrors = function() { throw e; }
129 }
130 inputs = filterDeadInputs(inputs);
131 filterListeners(inputs, listeners);
132 addReceivers(elm.ports.outgoing);
133 if (display !== Display.NONE) {
134 var graphicsNode = initGraphics(elm, Module);
135 }
136 if (typeof moduleToReplace !== 'undefined') {
137 hotSwap(moduleToReplace, elm);
139 // rerender scene if graphics are enabled.
140 if (typeof graphicsNode !== 'undefined') {
141 graphicsNode.recv(0, true, 0);
142 }
143 }
145 reportAnyErrors();
146 return {
147 swap:swap,
148 ports:elm.ports.outgoing,
149 dispose:dispose
150 };
151};
153function checkPorts(elm) {
154 var portUses = elm.ports.uses;
155 for (var key in portUses) {
156 var uses = portUses[key]
157 if (uses === 0) {
158 throw new Error(
159 "Initialization Error: provided port '" + key +
160 "' to a module that does not take it as in input.\n" +
161 "Remove '" + key + "' from the module initialization code.");
162 } else if (uses > 1) {
163 throw new Error(
164 "Initialization Error: port '" + key +
165 "' has been declared multiple times in the Elm code.\n" +
166 "Remove declarations until there is exactly one.");
167 }
168 }
172//// FILTER SIGNALS ////
174// TODO: move this code into the signal module and create a function
175// Signal.initializeGraph that actually instantiates everything.
177function filterListeners(inputs, listeners) {
178 loop:
179 for (var i = listeners.length; i--; ) {
180 var listener = listeners[i];
181 for (var j = inputs.length; j--; ) {
182 if (listener.relevantInputs.indexOf(inputs[j].id) >= 0) {
183 continue loop;
184 }
185 }
186 listener.domNode.removeEventListener(listener.eventName, listener.func);
187 }
190function removeListeners(listeners) {
191 for (var i = listeners.length; i--; ) {
192 var listener = listeners[i];
193 listener.domNode.removeEventListener(listener.eventName, listener.func);
194 }
197// add receivers for built-in ports if they are defined
198function addReceivers(ports) {
199 if ('log' in ports) {
200 ports.log.subscribe(function(v) { console.log(v) });
201 }
202 if ('stdout' in ports) {
203 var process = process || {};
204 var handler = process.stdout
205 ? function(v) { process.stdout.write(v); }
206 : function(v) { console.log(v); };
207 ports.stdout.subscribe(handler);
208 }
209 if ('stderr' in ports) {
210 var process = process || {};
211 var handler = process.stderr
212 ? function(v) { process.stderr.write(v); }
213 : function(v) { console.log('Error:' + v); };
214 ports.stderr.subscribe(handler);
215 }
216 if ('title' in ports) {
217 if (typeof ports.title === 'string') {
218 document.title = ports.title;
219 } else {
220 ports.title.subscribe(function(v) { document.title = v; });
221 }
222 }
223 if ('redirect' in ports) {
224 ports.redirect.subscribe(function(v) {
225 if (v.length > 0) window.location = v;
226 });
227 }
228 if ('favicon' in ports) {
229 if (typeof ports.favicon === 'string') {
230 changeFavicon(ports.favicon);
231 } else {
232 ports.favicon.subscribe(changeFavicon);
233 }
234 }
235 function changeFavicon(src) {
236 var link = document.createElement('link');
237 var oldLink = document.getElementById('elm-favicon');
238 link.id = 'elm-favicon';
239 link.rel = 'shortcut icon';
240 link.href = src;
241 if (oldLink) {
242 document.head.removeChild(oldLink);
243 }
244 document.head.appendChild(link);
245 }
249function filterDeadInputs(inputs) {
250 var temp = [];
251 for (var i = inputs.length; i--; ) {
252 if (isAlive(inputs[i])) temp.push(inputs[i]);
253 }
254 return temp;
258function isAlive(input) {
259 if (!('defaultNumberOfKids' in input)) return true;
260 var len = input.kids.length;
261 if (len === 0) return false;
262 if (len > input.defaultNumberOfKids) return true;
263 var alive = false;
264 for (var i = len; i--; ) {
265 alive = alive || isAlive(input.kids[i]);
266 }
267 return alive;
271//// RENDERING ////
273function initGraphics(elm, Module) {
274 if (!('main' in Module)) {
275 throw new Error("'main' is missing! What do I display?!");
276 }
278 var signalGraph = Module.main;
280 // make sure the signal graph is actually a signal & extract the visual model
281 var Signal = Elm.Signal.make(elm);
282 if (!('recv' in signalGraph)) {
283 signalGraph = Signal.constant(signalGraph);
284 }
285 var currentScene = signalGraph.value;
287 // Add the currentScene to the DOM
288 var Element = Elm.Native.Graphics.Element.make(elm);
289 elm.node.appendChild(Element.render(currentScene));
291 // set up updates so that the DOM is adjusted as necessary.
292 var savedScene = currentScene;
293 var previousDrawId = 0;
294 function domUpdate(newScene) {
295 previousDrawId = draw(previousDrawId, function(_) {
296 Element.update(elm.node.firstChild, savedScene, newScene);
297 if (elm.Native.Window) elm.Native.Window.values.resizeIfNeeded();
298 savedScene = newScene;
299 });
300 }
301 var renderer = A2(Signal.lift, domUpdate, signalGraph);
303 // must check for resize after 'renderer' is created so
304 // that changes show up.
305 if (elm.Native.Window) elm.Native.Window.values.resizeIfNeeded();
307 return renderer;
311// define function for drawing efficiently
312//
313// draw : RequestID -> (() -> ()) -> RequestID
314//
315// Takes a "RequestID" allowing you to cancel old requests if possible.
316// Returns a "RequestID" so you can refer to past requests.
317//
318function draw(previousRequestID, callback) {
319 callback();
320 return previousRequestID;
323var vendors = ['ms', 'moz', 'webkit', 'o'];
324var win = typeof window !== 'undefined' ? window : {};
325for (var i = 0; i < vendors.length && !win.requestAnimationFrame; ++i) {
326 win.requestAnimationFrame = win[vendors[i]+'RequestAnimationFrame'];
327 win.cancelAnimationFrame = win[vendors[i]+'CancelAnimationFrame'] ||
328 win[vendors[i]+'CancelRequestAnimationFrame'];
330if (win.requestAnimationFrame && win.cancelAnimationFrame) {
331 draw = function(previousRequestID, callback) {
332 win.cancelAnimationFrame(previousRequestID);
333 return win.requestAnimationFrame(callback);
334 };
338//// HOT SWAPPING ////
340// Returns boolean indicating if the swap was successful.
341// Requires that the two signal graphs have exactly the same
342// structure.
343function hotSwap(from, to) {
344 function similar(nodeOld,nodeNew) {
345 var idOkay = nodeOld.id === nodeNew.id;
346 var lengthOkay = nodeOld.kids.length === nodeNew.kids.length;
347 return idOkay && lengthOkay;
348 }
349 function swap(nodeOld,nodeNew) {
350 nodeNew.value = nodeOld.value;
351 return true;
352 }
353 var canSwap = depthFirstTraversals(similar, from.inputs, to.inputs);
354 if (canSwap) {
355 depthFirstTraversals(swap, from.inputs, to.inputs);
356 }
357 from.node.parentNode.replaceChild(to.node, from.node);
359 return canSwap;
362// Returns false if the node operation f ever fails.
363function depthFirstTraversals(f, queueOld, queueNew) {
364 if (queueOld.length !== queueNew.length) return false;
365 queueOld = queueOld.slice(0);
366 queueNew = queueNew.slice(0);
368 var seen = [];
369 while (queueOld.length > 0 && queueNew.length > 0) {
370 var nodeOld = queueOld.pop();
371 var nodeNew = queueNew.pop();
372 if (seen.indexOf(nodeOld.id) < 0) {
373 if (!f(nodeOld, nodeNew)) return false;
374 queueOld = queueOld.concat(nodeOld.kids);
375 queueNew = queueNew.concat(nodeNew.kids);
376 seen.push(nodeOld.id);
377 }
378 }
379 return true;
382}());