on ab1ba45 help sign in
elk/runtime/Init.js
281 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 var setDelay = function(d) {
53 inducedDelay = d;
54 return inducedDelay;
55 }
57 return { now : now
58 , addDelay : addDelay
59 , setDelay : setDelay
60 }
61 }();
63 var updateInProgress = false;
64 function notify(id, v) {
65 if (updateInProgress) {
66 throw new Error(
67 'The notify function has been called synchronously!\n' +
68 'This can lead to frames being dropped.\n' +
69 'Definitely report this to <https://github.com/elm-lang/Elm/issues>\n');
70 }
71 updateInProgress = true;
72 var timestep = timer.now();
73 for (var i = inputs.length; i--; ) {
74 inputs[i].recv(timestep, id, v);
75 }
76 updateInProgress = false;
77 }
79 var listeners = [];
80 function addListener(relevantInputs, domNode, eventName, func) {
81 domNode.addEventListener(eventName, func);
82 var listener = {
83 relevantInputs: relevantInputs,
84 domNode: domNode,
85 eventName: eventName,
86 func: func
87 };
88 listeners.push(listener);
89 }
91 var portUses = {}
92 for (var key in ports) {
93 portUses[key] = 0;
94 }
95 // create the actual RTS. Any impure modules will attach themselves to this
96 // object. This permits many Elm programs to be embedded per document.
97 var elm = {
98 notify:notify,
99 node:container,
100 display:display,
101 id:ElmRuntime.guid(),
102 addListener:addListener,
103 inputs:inputs,
104 timer:timer,
105 ports: { incoming:ports, outgoing:{}, uses:portUses }
106 };
108 function swap(newModule) {
109 removeListeners(listeners);
110 var div = document.createElement('div');
111 var newElm = init(display, div, newModule, ports, elm);
112 inputs = [];
113 // elm.swap = newElm.swap;
114 return newElm;
115 }
117 function dispose() {
118 removeListeners(listeners);
119 inputs = [];
120 }
122 var Module = {};
123 var reportAnyErrors = function() {};
124 try {
125 Module = module.make(elm);
126 checkPorts(elm);
127 } catch(e) {
128 var directions = "<br/>&nbsp; &nbsp; Open the developer console for more details."
129 Module.main = Elm.Text.make(elm).leftAligned('<code>' + e.message + directions + '</code>');
130 reportAnyErrors = function() { throw e; }
131 }
132 inputs = ElmRuntime.filterDeadInputs(inputs);
133 filterListeners(inputs, listeners);
134 addReceivers(elm.ports.outgoing);
135 if (display !== ElmRuntime.Display.NONE) {
136 var graphicsNode = initGraphics(elm, Module);
137 }
138 if (typeof moduleToReplace !== 'undefined') {
139 ElmRuntime.swap(moduleToReplace, elm);
141 // rerender scene if graphics are enabled.
142 if (typeof graphicsNode !== 'undefined') {
143 graphicsNode.recv(0, true, 0);
144 }
145 }
147 reportAnyErrors();
148 return {
149 swap:swap,
150 ports:elm.ports.outgoing,
151 dispose:dispose
152 };
153};
155function checkPorts(elm) {
156 var portUses = elm.ports.uses;
157 for (var key in portUses) {
158 var uses = portUses[key]
159 if (uses === 0) {
160 throw new Error(
161 "Initialization Error: provided port '" + key +
162 "' to a module that does not take it as in input.\n" +
163 "Remove '" + key + "' from the module initialization code.");
164 } else if (uses > 1) {
165 throw new Error(
166 "Initialization Error: port '" + key +
167 "' has been declared multiple times in the Elm code.\n" +
168 "Remove declarations until there is exactly one.");
169 }
170 }
173function filterListeners(inputs, listeners) {
174 loop:
175 for (var i = listeners.length; i--; ) {
176 var listener = listeners[i];
177 for (var j = inputs.length; j--; ) {
178 if (listener.relevantInputs.indexOf(inputs[j].id) >= 0) {
179 continue loop;
180 }
181 }
182 listener.domNode.removeEventListener(listener.eventName, listener.func);
183 }
186function removeListeners(listeners) {
187 for (var i = listeners.length; i--; ) {
188 var listener = listeners[i];
189 listener.domNode.removeEventListener(listener.eventName, listener.func);
190 }
193// add receivers for built-in ports if they are defined
194function addReceivers(ports) {
195 if ('log' in ports) {
196 ports.log.subscribe(function(v) { console.log(v) });
197 }
198 if ('stdout' in ports) {
199 var process = process || {};
200 var handler = process.stdout
201 ? function(v) { process.stdout.write(v); }
202 : function(v) { console.log(v); };
203 ports.stdout.subscribe(handler);
204 }
205 if ('stderr' in ports) {
206 var process = process || {};
207 var handler = process.stderr
208 ? function(v) { process.stderr.write(v); }
209 : function(v) { console.log('Error:' + v); };
210 ports.stderr.subscribe(handler);
211 }
212 if ('title' in ports) {
213 if (typeof ports.title === 'string') {
214 document.title = ports.title;
215 } else {
216 ports.title.subscribe(function(v) { document.title = v; });
217 }
218 }
219 if ('redirect' in ports) {
220 ports.redirect.subscribe(function(v) {
221 if (v.length > 0) window.location = v;
222 });
223 }
224 if ('favicon' in ports) {
225 if (typeof ports.favicon === 'string') {
226 changeFavicon(ports.favicon);
227 } else {
228 ports.favicon.subscribe(changeFavicon);
229 }
230 }
231 function changeFavicon(src) {
232 var link = document.createElement('link');
233 var oldLink = document.getElementById('elm-favicon');
234 link.id = 'elm-favicon';
235 link.rel = 'shortcut icon';
236 link.href = src;
237 if (oldLink) {
238 document.head.removeChild(oldLink);
239 }
240 document.head.appendChild(link);
241 }
244function initGraphics(elm, Module) {
245 if (!('main' in Module)) {
246 throw new Error("'main' is missing! What do I display?!");
247 }
249 var signalGraph = Module.main;
251 // make sure the signal graph is actually a signal & extract the visual model
252 var Signal = Elm.Signal.make(elm);
253 if (!('recv' in signalGraph)) {
254 signalGraph = Signal.constant(signalGraph);
255 }
256 var currentScene = signalGraph.value;
258 // Add the currentScene to the DOM
259 var Render = ElmRuntime.use(ElmRuntime.Render.Element);
260 elm.node.appendChild(Render.render(currentScene));
262 // set up updates so that the DOM is adjusted as necessary.
263 var savedScene = currentScene;
264 var previousDrawId = 0;
265 function domUpdate(newScene) {
266 previousDrawId = ElmRuntime.draw(previousDrawId, function(_) {
267 Render.update(elm.node.firstChild, savedScene, newScene);
268 if (elm.Native.Window) elm.Native.Window.values.resizeIfNeeded();
269 savedScene = newScene;
270 });
271 }
272 var renderer = A2(Signal.lift, domUpdate, signalGraph);
274 // must check for resize after 'renderer' is created so
275 // that changes show up.
276 if (elm.Native.Window) elm.Native.Window.values.resizeIfNeeded();
278 return renderer;
281}());