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