Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Make hot reloading work with Elm 0.19.1 #87

Draft
wants to merge 2 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 58 additions & 22 deletions resources/hmr.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
- various functions defined by Elm which we have to hook such as `_Platform_initialize` and `_Scheduler_binding`
*/

if (moduleHot.hot) {
if (module.hot) {
(function () {
"use strict";

Expand All @@ -43,15 +43,44 @@ if (moduleHot.hot) {
};
}

var instances = moduleHot.hot.data
? moduleHot.hot.data.instances || {}
// Elm 0.19.1 introduced a '$' prefix at the beginning of the symbols it emits,
// and we check for `List.map` because we expect it to be present in all Elm programs.
var elmVersion;
if (typeof elm$core$List$map !== 'undefined')
elmVersion = '0.19.0';
else if (typeof $elm$core$List$map !== 'undefined')
elmVersion = '0.19.1';
else
throw new Error("Could not determine Elm version");

function elmSymbol(symbol) {
try {
switch (elmVersion) {
case '0.19.0':
return eval(symbol);
case '0.19.1':
return eval('$' + symbol);
default:
throw new Error('Cannot resolve ' + symbol + '. Elm version unknown!')
}
} catch (e) {
if (e instanceof ReferenceError) {
return undefined;
} else {
throw e;
}
}
}

var instances = module.hot.data
? module.hot.data.instances || {}
: {};
var uid = moduleHot.hot.data
? moduleHot.hot.data.uid || 0
var uid = module.hot.data
? module.hot.data.uid || 0
: 0;

if (Object.keys(instances).length === 0) {
console.log("[elm-hot] Enabled");
log("[elm-hot] Enabled");
}

var cancellers = [];
Expand All @@ -61,8 +90,8 @@ if (moduleHot.hot) {
var initializingInstance = null;
var swappingInstance = null;

moduleHot.hot.accept();
moduleHot.hot.dispose(function (data) {
module.hot.accept();
module.hot.dispose(function (data) {
data.instances = instances;
data.uid = uid;

Expand All @@ -75,7 +104,7 @@ if (moduleHot.hot) {

// Second, kill pending tasks belonging to the old instance
if (cancellers.length) {
console.log('[elm-hot] Killing ' + cancellers.length + ' running processes...');
log('[elm-hot] Killing ' + cancellers.length + ' running processes...');
try {
cancellers.forEach(function (cancel) {
cancel();
Expand All @@ -86,6 +115,12 @@ if (moduleHot.hot) {
}
});

function log(message) {
if (module.hot.verbose) {
console.log(message)
}
}

function getId() {
return ++uid;
}
Expand Down Expand Up @@ -126,8 +161,8 @@ if (moduleHot.hot) {

function isFullscreenApp() {
// Returns true if the Elm app will take over the entire DOM body.
return typeof elm$browser$Browser$application !== 'undefined'
|| typeof elm$browser$Browser$document !== 'undefined';
return typeof elmSymbol("elm$browser$Browser$application") !== 'undefined'
|| typeof elmSymbol("elm$browser$Browser$document") !== 'undefined';
}

function wrapDomNode(node) {
Expand All @@ -148,6 +183,7 @@ if (moduleHot.hot) {
// behind their back and rudely put stuff in their DOM.
var dummyNode = document.createElement("div");
dummyNode.setAttribute("data-elm-hot", "true");
dummyNode.style.height = "inherit";
var parentNode = node.parentNode;
parentNode.replaceChild(dummyNode, node);
dummyNode.appendChild(node);
Expand Down Expand Up @@ -186,7 +222,7 @@ if (moduleHot.hot) {
}

function swap(Elm, instance) {
console.log('[elm-hot] Hot-swapping module: ' + instance.path);
log('[elm-hot] Hot-swapping module: ' + instance.path);

swappingInstance = instance;

Expand Down Expand Up @@ -218,28 +254,28 @@ if (moduleHot.hot) {
if (!handlers.length) {
return;
}
console.log('[elm-hot] Reconnect ' + handlers.length + ' handler(s) to port \''
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);
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');
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);
log('[elm-hot] Port was removed: ' + portName);
}
});
} else {
console.log('[elm-hot] Module was removed: ' + instance.path);
log('[elm-hot] Module was removed: ' + instance.path);
}

swappingInstance = null;
Expand All @@ -260,7 +296,7 @@ if (moduleHot.hot) {
var unsubscribe = port.unsubscribe;
elm.ports[portName] = Object.assign(port, {
subscribe: function (handler) {
console.log('[elm-hot] ports.' + portName + '.subscribe called.');
log('[elm-hot] ports.' + portName + '.subscribe called.');
if (!portSubscribes[portName]) {
portSubscribes[portName] = [handler];
} else {
Expand All @@ -270,7 +306,7 @@ if (moduleHot.hot) {
return subscribe.call(port, handler);
},
unsubscribe: function (handler) {
console.log('[elm-hot] ports.' + portName + '.unsubscribe called.');
log('[elm-hot] ports.' + portName + '.unsubscribe called.');
var list = portSubscribes[portName];
if (list && list.indexOf(handler) !== -1) {
list.splice(list.lastIndexOf(handler), 1);
Expand Down Expand Up @@ -369,7 +405,7 @@ if (moduleHot.hot) {
var oldModel = swappingInstance.lastState;
var newModel = initialStateTuple.a;

if (typeof elm$browser$Browser$application !== 'undefined') {
if (typeof elmSymbol("elm$browser$Browser$application") !== 'undefined') {
// attempt to find the Browser.Navigation.Key in the newly-constructed model
// and bring it along with the rest of the old data.
var newKeyLoc = findNavKey(newModel);
Expand Down Expand Up @@ -406,13 +442,13 @@ if (moduleHot.hot) {
initialStateTuple.a = oldModel;

// ignore any Cmds returned by the init during hot-swap
initialStateTuple.b = elm$core$Platform$Cmd$none;
initialStateTuple.b = elmSymbol("elm$core$Platform$Cmd$none");
} else {
// capture the initial state for later
initializingInstance.lastState = initialStateTuple.a;

// capture Browser.application's navigation key for later
if (typeof elm$browser$Browser$application !== 'undefined') {
if (typeof elmSymbol("elm$browser$Browser$application") !== 'undefined') {
var navKeyLoc = findNavKey(initializingInstance.lastState);
if (!navKeyLoc) {
console.error("[elm-hot] Hot-swapping disabled for " + instance.path
Expand Down
6 changes: 3 additions & 3 deletions src/HotReload.hs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ wrap hotReloadingPort (a, content) =
[ "// Expose the Webpack HMR API"
, "var myDisposeCallback = function() {};"
, "// simulate the HMR api exposed by webpack"
, "var moduleHot = {"
, "var module = {"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm worried that something else is called module and we overwrite that.

Copy link
Contributor Author

@asterite asterite Aug 12, 2019

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@stoeffel Great idea! I tried using moduleHot as before and now it seems to work! Well, it automatically reloads the page. I still get the renameFile error... but it's a big progress!

, " hot: {"
, " accept: function () {"
, " },"
Expand All @@ -35,7 +35,7 @@ wrap hotReloadingPort (a, content) =
, " apply: function () {"
, " var newData = {};"
, " myDisposeCallback(newData);"
, " moduleHot.hot.data = newData"
, " module.hot.data = newData"
, " }"
, " }"
, "};"
Expand All @@ -46,7 +46,7 @@ wrap hotReloadingPort (a, content) =
"');"
, "socketHotReloading.onmessage = function(event) {"
, " console.warn('Jetpack reloading...');"
, " moduleHot.hot.apply();"
, " module.hot.apply();"
, " delete window.Elm;"
, " try {"
, " eval(event.data);"
Expand Down