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