-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathhmr.js
444 lines (395 loc) · 18 KB
/
hmr.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//////////////////// HMR BEGIN ////////////////////
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Original Author: Flux Xu @fluxxu
*/
/*
A note about the environment that this code runs in...
assumed globals:
- `module` (from Node.js module system and webpack)
assumed in scope after injection into the Elm IIFE:
- `scope` (has an 'Elm' property which contains the public Elm API)
- various functions defined by Elm which we have to hook such as `_Platform_initialize` and `_Scheduler_binding`
*/
if (module.hot) {
(function () {
"use strict";
//polyfill for IE: https://github.com/fluxxu/elm-hot-loader/issues/16
if (typeof Object.assign != 'function') {
Object.assign = function (target) {
'use strict';
if (target == null) {
throw new TypeError('Cannot convert undefined or null to object');
}
target = Object(target);
for (var index = 1; index < arguments.length; index++) {
var source = arguments[index];
if (source != null) {
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
}
return target;
};
}
var instances = module.hot.data
? module.hot.data.instances || {}
: {};
var uid = module.hot.data
? module.hot.data.uid || 0
: 0;
if (Object.keys(instances).length === 0) {
console.log("[elm-hot] Enabled");
}
var cancellers = [];
// These 2 variables act as dynamically-scoped variables which are set only when the
// Elm module's hooked init function is called.
var initializingInstance = null;
var swappingInstance = null;
module.hot.accept();
module.hot.dispose(function (data) {
data.instances = instances;
data.uid = uid;
// Cleanup pending async tasks
// First, make sure that no new tasks can be started until we finish replacing the code
_Scheduler_binding = function () {
return _Scheduler_fail(new Error('[elm-hot] Inactive Elm instance.'))
};
// Second, kill pending tasks belonging to the old instance
if (cancellers.length) {
console.log('[elm-hot] Killing ' + cancellers.length + ' running processes...');
try {
cancellers.forEach(function (cancel) {
cancel();
});
} catch (e) {
console.warn('[elm-hot] Kill process error: ' + e.message);
}
}
});
function getId() {
return ++uid;
}
function findPublicModules(parent, path) {
var modules = [];
for (var key in parent) {
var child = parent[key];
var currentPath = path ? path + '.' + key : key;
if ('init' in child) {
modules.push({
path: currentPath,
module: child
});
} else {
modules = modules.concat(findPublicModules(child, currentPath));
}
}
return modules;
}
function getPublicModule(Elm, path) {
var parts = path.split('.');
var parent = Elm;
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
if (part in parent) {
parent = parent[part]
}
if (!parent) {
return null;
}
}
return parent
}
function registerInstance(domNode, flags, path, portSubscribes, portSends) {
var id = getId();
var instance = {
id: id,
path: path,
domNode: domNode,
flags: flags,
portSubscribes: portSubscribes,
portSends: portSends,
lastState: null // last Elm app state (root model)
};
return instances[id] = instance
}
function wrapDomNode(node) {
// When embedding an Elm app into a specific DOM node, Elm will replace the provided
// DOM node with the Elm app's content. When the Elm app is compiled normally, the
// original DOM node is reused (its attributes and content changes, but the object
// in memory remains the same). But when compiled using `--debug`, Elm will completely
// destroy the original DOM node and instead replace it with 2 brand new nodes: one
// for your Elm app's content and the other for the Elm debugger UI. In this case,
// if you held a reference to the DOM node provided for embedding, it would be orphaned
// after Elm module initialization.
//
// So in order to make both cases consistent and isolate us from changes in how Elm
// does this, we will insert a dummy node to wrap the node for embedding and hold
// a reference to the dummy node.
//
// We will also put a tag on the dummy node so that the Elm developer knows who went
// behind their back and rudely put stuff in their DOM.
var dummyNode = document.createElement("div");
dummyNode.setAttribute("data-elm-hot", "true");
var parentNode = node.parentNode;
parentNode.replaceChild(dummyNode, node);
dummyNode.appendChild(node);
return dummyNode;
}
function wrapPublicModule(path, module) {
var originalInit = module.init;
if (originalInit) {
module.init = function (args) {
var elm;
var portSubscribes = {};
var portSends = {};
var domNode = args['node'] ? wrapDomNode(args['node']) : document.body;
initializingInstance = registerInstance(domNode, args['flags'], path, portSubscribes, portSends);
elm = originalInit(args);
wrapPorts(elm, portSubscribes, portSends);
initializingInstance = null;
return elm;
};
} else {
console.error("Could not find a public module to wrap at path " + path)
}
}
function swap(Elm, instance) {
console.log('[elm-hot] Hot-swapping module: ' + instance.path);
swappingInstance = instance;
// remove from the DOM everything that had been created by the old Elm app
var containerNode = instance.domNode;
while (containerNode.lastChild) {
containerNode.removeChild(containerNode.lastChild);
}
var m = getPublicModule(Elm, instance.path);
var elm;
if (m) {
// prepare to initialize the new Elm module
var args = {flags: instance.flags};
if (containerNode === document.body) {
// fullscreen case: no additional args needed
} else {
// embed case: provide a new node for Elm to use
var nodeForEmbed = document.createElement("div");
containerNode.appendChild(nodeForEmbed);
args['node'] = nodeForEmbed;
}
elm = m.init(args);
Object.keys(instance.portSubscribes).forEach(function (portName) {
if (portName in elm.ports && 'subscribe' in elm.ports[portName]) {
var handlers = instance.portSubscribes[portName];
if (!handlers.length) {
return;
}
console.log('[elm-hot] Reconnect ' + handlers.length + ' handler(s) to port \''
+ portName + '\' (' + instance.path + ').');
handlers.forEach(function (handler) {
elm.ports[portName].subscribe(handler);
});
} else {
delete instance.portSubscribes[portName];
console.log('[elm-hot] Port was removed: ' + portName);
}
});
Object.keys(instance.portSends).forEach(function (portName) {
if (portName in elm.ports && 'send' in elm.ports[portName]) {
console.log('[elm-hot] Replace old port send with the new send');
instance.portSends[portName] = elm.ports[portName].send;
} else {
delete instance.portSends[portName];
console.log('[elm-hot] Port was removed: ' + portName);
}
});
} else {
console.log('[elm-hot] Module was removed: ' + instance.path);
}
swappingInstance = null;
}
function wrapPorts(elm, portSubscribes, portSends) {
var portNames = Object.keys(elm.ports || {});
//hook ports
if (portNames.length) {
// hook outgoing ports
portNames
.filter(function (name) {
return 'subscribe' in elm.ports[name];
})
.forEach(function (portName) {
var port = elm.ports[portName];
var subscribe = port.subscribe;
var unsubscribe = port.unsubscribe;
elm.ports[portName] = Object.assign(port, {
subscribe: function (handler) {
console.log('[elm-hot] ports.' + portName + '.subscribe called.');
if (!portSubscribes[portName]) {
portSubscribes[portName] = [handler];
} else {
//TODO handle subscribing to single handler more than once?
portSubscribes[portName].push(handler);
}
return subscribe.call(port, handler);
},
unsubscribe: function (handler) {
console.log('[elm-hot] ports.' + portName + '.unsubscribe called.');
var list = portSubscribes[portName];
if (list && list.indexOf(handler) !== -1) {
list.splice(list.lastIndexOf(handler), 1);
} else {
console.warn('[elm-hot] ports.' + portName + '.unsubscribe: handler not subscribed');
}
return unsubscribe.call(port, handler);
}
});
});
// hook incoming ports
portNames
.filter(function (name) {
return 'send' in elm.ports[name];
})
.forEach(function (portName) {
var port = elm.ports[portName];
portSends[portName] = port.send;
elm.ports[portName] = Object.assign(port, {
send: function (val) {
return portSends[portName].call(port, val);
}
});
});
}
return portSubscribes;
}
function isDebuggerModel(model) {
return model && model.hasOwnProperty("expando") && model.hasOwnProperty("state");
}
function findNavKey(model) {
for (var propName in model) {
if (!model.hasOwnProperty(propName)) continue;
var prop = model[propName];
if (prop.hasOwnProperty("elm-hot-nav-key")) {
return {name: propName, value: prop};
}
}
return null;
}
function removeNavKeyListeners(model) {
var navKey = null;
if (isDebuggerModel(model)) {
navKey = findNavKey(model['state']['a']);
} else {
navKey = findNavKey(model);
}
if (navKey) {
window.removeEventListener('popstate', navKey.value);
window.navigator.userAgent.indexOf('Trident') < 0 || window.removeEventListener('hashchange', navKey.value);
}
}
// hook program creation
var initialize = _Platform_initialize;
_Platform_initialize = function (flagDecoder, args, init, update, subscriptions, stepperBuilder) {
var instance = initializingInstance || swappingInstance;
var tryFirstRender = !!swappingInstance;
var hookedInit = function (args) {
var initialStateTuple = init(args);
if (swappingInstance) {
var oldModel = swappingInstance.lastState;
var newModel = initialStateTuple.a;
if (typeof elm$browser$Browser$application !== 'undefined') {
// remove old navigation listeners
removeNavKeyListeners(oldModel);
// attempt to find the Browser.Navigation.Key in the newly-constructed model
// and bring it along with the rest of the old data.
var newKey = null;
if (isDebuggerModel(newModel)) {
newKey = findNavKey(newModel['state']['a']);
if (newKey) {
oldModel['state']['a'][newKey.name] = newKey.value;
}
} else {
newKey = findNavKey(newModel);
if (newKey) {
oldModel[newKey.name] = newKey.value;
}
}
if (!newKey) {
console.error("[elm-hot] Hot-swapping " + instance.path + " not possible. "
+ "You can fix this error by storing the Browser.Navigation.Key at the root "
+ "of your app's model.");
oldModel = newModel;
}
}
// the heart of the app state hot-swap
initialStateTuple.a = oldModel;
} else {
// capture the initial state for later
initializingInstance.lastState = initialStateTuple.a;
}
return initialStateTuple
};
var hookedStepperBuilder = function (sendToApp, model) {
var result;
// first render may fail if shape of model changed too much
if (tryFirstRender) {
tryFirstRender = false;
try {
result = stepperBuilder(sendToApp, model)
} catch (e) {
throw new Error('[elm-hot] Hot-swapping ' + instance.path +
' is not possible, please reload page. Error: ' + e.message)
}
} else {
result = stepperBuilder(sendToApp, model)
}
return function (nextModel, isSync) {
if (instance) {
// capture the state after every step so that later we can restore from it during a hot-swap
instance.lastState = nextModel
}
return result(nextModel, isSync)
}
};
return initialize(flagDecoder, args, hookedInit, update, subscriptions, hookedStepperBuilder)
};
// hook process creation
var originalBinding = _Scheduler_binding;
_Scheduler_binding = function (originalCallback) {
return originalBinding(function () {
// start the scheduled process, which may return a cancellation function.
var cancel = originalCallback.apply(this, arguments);
if (cancel) {
cancellers.push(cancel);
return function () {
cancellers.splice(cancellers.indexOf(cancel), 1);
return cancel();
};
}
return cancel;
});
};
scope['_elm_hot_loader_init'] = function (Elm) {
// swap instances
var removedInstances = [];
for (var id in instances) {
var instance = instances[id];
if (instance.domNode.parentNode) {
swap(Elm, instance);
} else {
removedInstances.push(id);
}
}
removedInstances.forEach(function (id) {
delete instance[id];
});
// wrap all public modules
var publicModules = findPublicModules(Elm);
publicModules.forEach(function (m) {
wrapPublicModule(m.path, m.module);
});
}
})();
}
//////////////////// HMR END ////////////////////
scope['_elm_hot_loader_init'](scope['Elm']);