on 9cda2b2 help sign in
elk/runtime/Init.js
279 lines 8.6 kB history raw
2(function() {
3'use strict';
5Elm.fullscreen = function(module, ports) {
6 var style = document.createElement('style');
7 style.type = 'text/css';
8 style.innerHTML = "html,head,body { padding:0; margin:0; }" +
9 "body { font-family: calibri, helvetica, arial, sans-serif; }";
10 document.head.appendChild(style);
11 var container = document.createElement('div');
12 document.body.appendChild(container);
13 return init(ElmRuntime.Display.FULLSCREEN, container, module, ports || {});
14};
16Elm.embed = function(module, container, ports) {
17 var tag = container.tagName;
18 if (tag !== 'DIV') {
19 throw new Error('Elm.node must be given a DIV, not a ' + tag + '.');
20 } else if (container.hasChildNodes()) {
21 throw new Error('Elm.node must be given an empty DIV. No children allowed!');
22 }
23 return init(ElmRuntime.Display.COMPONENT, container, module, ports || {});
24};
26Elm.worker = function(module, ports) {
27 return init(ElmRuntime.Display.NONE, {}, module, ports || {});
28};
30function init(display, container, module, ports, moduleToReplace) {
31 // defining state needed for an instance of the Elm RTS
32 var inputs = [];
34 /* OFFSET
35 * Elm's time traveling debugger lets you interrupt the smooth flow of time
36 * by pausing and continuing program execution. To ensure the user sees a
37 * program that moves smoothly through the pause/continue time gap,
38 * we need to adjsut the value of Date.now().
39 */
40 var timer = function() {
41 var inducedDelay = 0;
43 var now = function() {
44 return Date.now() - inducedDelay;
45 };
47 var addDelay = function(d) {
48 inducedDelay += d;
49 return inducedDelay;
50 };
52 return { now : now
53 , addDelay : addDelay
54 }
55 }();
57 var updateInProgress = false;
58 function notify(id, v) {
59 if (updateInProgress) {
60 throw new Error(
61 'The notify function has been called synchronously!\n' +
62 'This can lead to frames being dropped.\n' +
63 'Definitely report this to <https://github.com/elm-lang/Elm/issues>\n');
64 }
65 updateInProgress = true;
66 var timestep = timer.now();
67 for (var i = inputs.length; i--; ) {
68 inputs[i].recv(timestep, id, v);
69 }
70 updateInProgress = false;
71 }
72 function setTimeout(func, delay) {
73 window.setTimeout(func, delay);
74 }
76 var listeners = [];
77 function addListener(relevantInputs, domNode, eventName, func) {
78 domNode.addEventListener(eventName, func);
79 var listener = {
80 relevantInputs: relevantInputs,
81 domNode: domNode,
82 eventName: eventName,
83 func: func
84 };
85 listeners.push(listener);
86 }
88 var portUses = {}
89 for (var key in ports) {
90 portUses[key] = 0;
91 }
92 // create the actual RTS. Any impure modules will attach themselves to this
93 // object. This permits many Elm programs to be embedded per document.
94 var elm = {
95 notify:notify,
96 setTimeout:setTimeout,
97 node:container,
98 display:display,
99 id:ElmRuntime.guid(),
100 addListener:addListener,
101 inputs:inputs,
102 timer:timer,
103 ports: { incoming:ports, outgoing:{}, uses:portUses }
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 = ElmRuntime.filterDeadInputs(inputs);
131 filterListeners(inputs, listeners);
132 addReceivers(elm.ports.outgoing);
133 if (display !== ElmRuntime.Display.NONE) {
134 var graphicsNode = initGraphics(elm, Module);
135 }
136 if (typeof moduleToReplace !== 'undefined') {
137 ElmRuntime.swap(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 }
171function filterListeners(inputs, listeners) {
172 loop:
173 for (var i = listeners.length; i--; ) {
174 var listener = listeners[i];
175 for (var j = inputs.length; j--; ) {
176 if (listener.relevantInputs.indexOf(inputs[j].id) >= 0) {
177 continue loop;
178 }
179 }
180 listener.domNode.removeEventListener(listener.eventName, listener.func);
181 }
184function removeListeners(listeners) {
185 for (var i = listeners.length; i--; ) {
186 var listener = listeners[i];
187 listener.domNode.removeEventListener(listener.eventName, listener.func);
188 }
191// add receivers for built-in ports if they are defined
192function addReceivers(ports) {
193 if ('log' in ports) {
194 ports.log.subscribe(function(v) { console.log(v) });
195 }
196 if ('stdout' in ports) {
197 var process = process || {};
198 var handler = process.stdout
199 ? function(v) { process.stdout.write(v); }
200 : function(v) { console.log(v); };
201 ports.stdout.subscribe(handler);
202 }
203 if ('stderr' in ports) {
204 var process = process || {};
205 var handler = process.stderr
206 ? function(v) { process.stderr.write(v); }
207 : function(v) { console.log('Error:' + v); };
208 ports.stderr.subscribe(handler);
209 }
210 if ('title' in ports) {
211 if (typeof ports.title === 'string') {
212 document.title = ports.title;
213 } else {
214 ports.title.subscribe(function(v) { document.title = v; });
215 }
216 }
217 if ('redirect' in ports) {
218 ports.redirect.subscribe(function(v) {
219 if (v.length > 0) window.location = v;
220 });
221 }
222 if ('favicon' in ports) {
223 if (typeof ports.favicon === 'string') {
224 changeFavicon(ports.favicon);
225 } else {
226 ports.favicon.subscribe(changeFavicon);
227 }
228 }
229 function changeFavicon(src) {
230 var link = document.createElement('link');
231 var oldLink = document.getElementById('elm-favicon');
232 link.id = 'elm-favicon';
233 link.rel = 'shortcut icon';
234 link.href = src;
235 if (oldLink) {
236 document.head.removeChild(oldLink);
237 }
238 document.head.appendChild(link);
239 }
242function initGraphics(elm, Module) {
243 if (!('main' in Module)) {
244 throw new Error("'main' is missing! What do I display?!");
245 }
247 var signalGraph = Module.main;
249 // make sure the signal graph is actually a signal & extract the visual model
250 var Signal = Elm.Signal.make(elm);
251 if (!('recv' in signalGraph)) {
252 signalGraph = Signal.constant(signalGraph);
253 }
254 var currentScene = signalGraph.value;
256 // Add the currentScene to the DOM
257 var Render = ElmRuntime.use(ElmRuntime.Render.Element);
258 elm.node.appendChild(Render.render(currentScene));
260 // set up updates so that the DOM is adjusted as necessary.
261 var savedScene = currentScene;
262 var previousDrawId = 0;
263 function domUpdate(newScene) {
264 previousDrawId = ElmRuntime.draw(previousDrawId, function(_) {
265 Render.update(elm.node.firstChild, savedScene, newScene);
266 if (elm.Native.Window) elm.Native.Window.values.resizeIfNeeded();
267 savedScene = newScene;
268 });
269 }
270 var renderer = A2(Signal.lift, domUpdate, signalGraph);
272 // must check for resize after 'renderer' is created so
273 // that changes show up.
274 if (elm.Native.Window) elm.Native.Window.values.resizeIfNeeded();
276 return renderer;
279}());