There are times when you want to kill an Elm program good and proper. A reason for this is that Elm programs don’t always clean themselves up how you would expect. Especially if you are using Elm in a fairly custom way like with a framework.
Djelm, a framework I built for seamlessly using Elm in the Django web framework, does a few tricks and sleight of hand to achieve its goal of hydrating Elm programs client side from server generated html Django pumps out.
If you have a simple MPA, there are no issues at all, you load a page, the page resets the state, djelm runtime hydrates any included Elm programs, happy days!
If however you use a slightly more modern approach like HTMX to get that sweet SPA experience then things kinda start hanging around. You load a page, but now HTMX gets involved and instead of a fresh new page, you get the same page you were on, just with the new html spliced in and the url changed to reflect the new route. It’s wonderful but here be dragons.
What happened to the Elm programs from the previous page? Well, there was no fresh page loaded so those programs are actually still alive and holding on to memory, it’s just that they aren’t connected to DOM. If one of those programs was fetching data from the server every 5 seconds then the chances are, it still is!
Frameworks like elm-pages and Lamdera almost certainly have to deal with this scenario, as does djelm.
Djelm works around this by patching compiler output at bundle time. Internally djelm uses Parcel so I wrote @confidenceman02/parcel-transformer-djelm to do the job. Parcel simply calls my transformer when it sees Elm code then the transformer handles the compilation and patching. This was massively inspired by the very excellent @parcel/transformer-elm
What it does is adds a ‘die’ hook, an idea I stole from this gist with some modifications. Now, the program’s internal references can be nulled out and memory garbage collected. You can read more about it in djelm’s JS interop section in the README.
Oddly enough it’s been a real treat working on this. It takes you in to the parts of Elm that are less visible but so very interesting.