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