marc walter

Updating code for Elm 0.19

2018-09-02

This site contains a couple of examples in the Elm language. Recently, the version Elm 0.19 was released which introduced quite a few breaking changes.
But fortunately upgrading was made easy thanks to the official upgrade docs and the tool elm-upgrade.

I updated the following posts for Elm 0.19:

Note: Upgrading each post took between 15 and 90 minutes.

Elm Oauth integration (1 of 2 - GitHub)

2018-06-16 (Last updated on 2018-09-07)

Example app animation

Background

I am working on a web service that a user may access without registration, but where she may invite other people via email.
To mitigate misuse of the service for spam, I decided to require a validated email address before the user may invite someone else. One simple way is to send a registration email to the user to activate the feature.
But I also want the possibility to add the email feature without requiring the user to wait for an email.
To achieve this, I decided to use OAuth 2.0 integration, and first use GitHub.

TLDR: Example code written in JavaScript with koa for the server and in elm for the client is available for download and on github.

read more

New major version of folder-hash (2.0)

2018-04-14

A while ago I released a library that creates checksums over folders and files for node.js. Now I prepared a new major version, which adds the possibility to specify more sophisticated include and exclude rules. I also added CircleCI configuration build

Example usage:

const { hashElement } = require('folder-hash');

const options = {
    folders: { exclude: ['.*', 'node_modules', 'test_coverage'] },
    files: { include: ['*.js', '*.json'] }
};

console.log('Creating a hash over the current folder:');
hashElement('.', options)
    .then(hash => {
        console.log(hash.toString());
    })
    .catch(error => {
        console.error('hashing failed: ', error);
    });
read more

Mouse scroll events in Elm (using JSON decoders)

2018-03-29 (Last updated on 2018-09-01)

Handling scroll events in Elm is not perfect, but on the elm discourse channel the user @ilias pointed out a nice way:

In Elm 0.18 and 0.19:

Use a port to send wheel events from JavaScript to the Elm app

const app = Elm.Main.init({ node: document.querySelector('main') })
document.addEventListener("wheel", app.ports.onWheel.send);

and decode them into an Elm Msg type

type Msg
    = NoOp
    | Wheel { deltaX : Float, deltaY : Float }

port onWheel : (Json.Decode.Value -> msg) -> Sub msg

subscriptions : model -> Sub Msg
subscriptions _ =
    onWheel Wheel
        (\val ->
            case Decode.decodeValue wheelDecoder val of
                Ok model ->
                    Wheel model

                Err _ ->
                    NoOp
        )

wheelDecoder : Json.Decoder Model
wheelDecoder =
    Json.Decode.map2 Model
        (Json.Decode.field "deltaX" Decode.float)
        (Json.Decode.field "deltaY" Decode.float)

...

In the future

Remove the port, and use the new onWindow or onDocument functions:

subscriptions : model -> Sub Msg
subscriptions _ =
    onDocument "wheel" (Json.Decode.map Wheel wheelDecoder)

This was proposed for Elm 0.19, but unfortunately it did not make it into the final release.

read more

Elm Filedrop example

2018-02-11 (Last updated on 2018-09-01)

A simple example that uses the HTML Drag&Drop API to generate dataURI strings when dropping files onto an HTML element.

demo

This is a good example to show how it is possible to use Browser APIs that are not available to elm. Elm does not support the file list that is emitted in the drop event, but when passing the event data through a port to JavaScript code it is still possible to use the API.
No need to listen to the API events in JS, just use elm and pass the result.

read more

Focusing elements in Elm

2018-01-31 (Last updated on 2018-09-01)

A reminder how to focus input elements using Elm without I want to add elements to a list and automatically focus on them.

A nice solution on stackoverflow from robertjlooby is this:

The focus function in the elm-lang/dom package is used to set focus with a Task (without using any ports or JavaScript).

Internally it uses requestAnimationFrame to ensure any new DOM updates are rendered before it tries to find the DOM node to focus on.

type Msg
    = FocusOn String
    | FocusResult (Result Dom.Error ())

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
    case msg of
        FocusOn id ->
            ( model, Dom.focus id |> Task.attempt FocusResult )

        FocusResult result ->
            -- handle success or failure here
            case result of
                Err (Dom.NotFound id) ->
                    -- unable to find dom 'id'
                Ok () ->
                    -- successfully focus the dom

He also created a fully working ellie example for Elm 0.18, which I converted to Elm 0.19.

read more

Decoding models from a JSON formatted string

2018-01-17 (Last updated on 2018-09-01)

A small snippet useful if one Elm program consists of two very different components.

How to use it:

  1. Pass data to the instantiation of the elm program as a String
  2. Try different decoders on the data (Json.Decode.oneOf)
  3. Display the SPA that can handle the data or an error page
If this iframe is not displayed, try opening the [file directly](./example.html). read more

Cross-browser copy-to-clipboard support

2017-10-22

Recently I needed to add a copy-to-clipboard functionality to a project. Usually, clipboard.js is an awesome tool to add support for it with great browser support and nice fallback handling for unsupported browsers.

Because the program is written in elm I wanted to keep the number of JavaScript dependencies to a minimum and decided to write this code on my own.

Result is this JsBin. For my purposes it worked well, I only need support for the current versions of the major desktop browsers (Firefox, Chrome, Edge and Safari) and on iOS 11.

Just like clipboard.js I used the Selection and ExecCommand APIs. Fallback mechanisms were not needed for my use case.

read more

Mini game 1 + 2 = 3

2017-10-08 (Last updated on 2018-09-01)

I saw a nice little example game written by Emanuele Feronato where you need to calculate sums and differences using only 1, 2 or 3.

I then decided to program it using elm.

You can use either mouse, fingers, or the keyboard to enter the correct values and try to get as high a score as possible. The highscore is saved to local storage.

If this iframe is not displayed, try the game directly.

read more