Repository: elm-community/js-integration-examples
Branch: master
Commit: 3952f9440d3f
Files: 18
Total size: 44.3 KB
Directory structure:
gitextract_30tzxhax/
├── .gitignore
├── LICENSE
├── README.md
├── internationalization/
│ ├── README.md
│ ├── elm.json
│ ├── index.html
│ └── src/
│ └── Main.elm
├── localStorage/
│ ├── README.md
│ ├── elm.json
│ ├── index.html
│ └── src/
│ └── Main.elm
├── more/
│ ├── README.md
│ └── webcomponents/
│ ├── README.md
│ └── minimal-es5-setup.html
└── websockets/
├── README.md
├── elm.json
├── index.html
└── src/
└── Main.elm
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
dist/
node_modules/
elm-stuff
elm.js
package-lock.json
================================================
FILE: LICENSE
================================================
BSD 3-Clause License
Copyright (c) 2020, Elm Community
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
================================================
FILE: README.md
================================================
# Using JS within Elm
Elm can interact with JavaScript in three ways:
- [flags](https://guide.elm-lang.org/interop/flags.html)
- [ports](https://guide.elm-lang.org/interop/ports.html)
- [custom elements](https://guide.elm-lang.org/interop/custom_elements.html)
Not all browser APIs are covered by an official package yet, so if you are evaluating using Elm in your company, definitely browse through the examples here to get familiar with flags, ports, and custom elements to make sure these interop mechanisms will fully meet your needs. It may be safest to circle back to Elm later if not!
## Ports
- [localStorage](/localStorage) — [demo](https://ellie-app.com/8yYddD6HRYJa1)
- [WebSockets](/websockets) — [demo](https://ellie-app.com/8yYgw7y7sM2a1)
## Custom Elements
- [Internationalization](/internationalization) — [demo](https://ellie-app.com/8yYbRQ3Hzrta1)
- [Pie Chart Widget](https://ellie-app.com/8B2B8fWbvZwa1)
- [Calendar Widget](https://ellie-app.com/8B8D2Q3WLh7a1)
- [Project Fluent](https://github.com/wolfadex/fluent-web/)
## Do you want to know more?
The top-level examples presented here are intentionally boiled down to a minimal setup for you to understand the basic ideas and get started quickly. As the web platform is a place with a lot of history and odd API corners there are more involved examples and tutorials to be explored in the [more](/more) section.
* [Everything you need to know to use WebComponents in your Elm app](/more/webcomponents)
================================================
FILE: internationalization/README.md
================================================
# Internationalization - [Live Demo](https://ellie-app.com/8yYbRQ3Hzrta1)
This is a minimal example of how to use the `Intl` library with a custom element.

The important code lives in `src/Main.elm` and in `index.html` with comments!
Check out [`wolfadex/fluent-web`](https://github.com/wolfadex/fluent-web/) for a more complete approach, making [Project Fluent](https://projectfluent.org/) available through custom elements.
## Building Locally
Run the following commands:
```bash
git clone https://github.com/elm-community/js-integration-examples.git
cd js-integration-examples/internationalization
elm make src/Main.elm --output=elm.js
open index.html
```
Some terminals may not have an `open` command, in which case you should open the index.html file in your browser another way.
================================================
FILE: internationalization/elm.json
================================================
{
"type": "application",
"source-directories": [
"src"
],
"elm-version": "0.19.1",
"dependencies": {
"direct": {
"elm/browser": "1.0.2",
"elm/core": "1.0.5",
"elm/html": "1.0.0",
"elm/json": "1.1.3"
},
"indirect": {
"elm/time": "1.0.0",
"elm/url": "1.0.0",
"elm/virtual-dom": "1.0.2"
}
},
"test-dependencies": {
"direct": {},
"indirect": {}
}
}
================================================
FILE: internationalization/index.html
================================================
Elm + Intl
================================================
FILE: internationalization/src/Main.elm
================================================
module Main exposing (..)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Json.Decode as D
-- MAIN
main : Program () Model Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = \_ -> Sub.none
}
-- MODEL
type alias Model =
{ language : String
}
init : () -> ( Model, Cmd Msg )
init _ =
( { language = "sr-RS" }
, Cmd.none
)
-- UPDATE
type Msg
= LanguageChanged String
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
LanguageChanged language ->
( { model | language = language }
, Cmd.none
)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ p [] [ viewDate model.language 2012 5 ]
, select
[ on "change" (D.map LanguageChanged valueDecoder)
]
[ option [ value "sr-RS" ] [ text "sr-RS" ]
, option [ value "en-GB" ] [ text "en-GB" ]
, option [ value "en-US" ] [ text "en-US" ]
]
]
-- Use the Custom Element defined in index.html
--
viewDate : String -> Int -> Int -> Html msg
viewDate lang year month =
node "intl-date"
[ attribute "lang" lang
, attribute "year" (String.fromInt year)
, attribute "month" (String.fromInt month)
]
[]
valueDecoder : D.Decoder String
valueDecoder =
D.field "currentTarget" (D.field "value" D.string)
================================================
FILE: localStorage/README.md
================================================
# Local Storage - [Live Demo](https://ellie-app.com/8yYddD6HRYJa1)
This is a minimal example of how to use `localStorage` through ports.
It remembers user data across sessions. This data may be lost if the user clears their cookies, so it is safest to think of this as a **cache** rather than normal storage.
Anyway, the important code lives in `src/Main.elm` and in `index.html` with comments!
## Building Locally
Run the following commands:
```bash
git clone https://github.com/elm-community/js-integration-examples.git
cd js-integration-examples/localStorage
elm make src/Main.elm --output=elm.js
open index.html
```
Some terminals may not have an `open` command, in which case you should open the index.html file in your browser another way.
================================================
FILE: localStorage/elm.json
================================================
{
"type": "application",
"source-directories": [
"src"
],
"elm-version": "0.19.1",
"dependencies": {
"direct": {
"elm/browser": "1.0.2",
"elm/core": "1.0.5",
"elm/html": "1.0.0",
"elm/json": "1.1.3"
},
"indirect": {
"elm/time": "1.0.0",
"elm/url": "1.0.0",
"elm/virtual-dom": "1.0.2"
}
},
"test-dependencies": {
"direct": {},
"indirect": {}
}
}
================================================
FILE: localStorage/index.html
================================================
Elm + localStorage
================================================
FILE: localStorage/src/Main.elm
================================================
port module Main exposing (..)
import Browser
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events exposing (..)
import Json.Decode as D
import Json.Encode as E
-- MAIN
main : Program E.Value Model Msg
main =
Browser.element
{ init = init
, view = view
, update = updateWithStorage
, subscriptions = \_ -> Sub.none
}
-- MODEL
type alias Model =
{ name : String
, email : String
}
-- Here we use "flags" to load information in from localStorage. The
-- data comes in as a JS value, so we define a `decoder` at the bottom
-- of this file to turn it into an Elm value.
--
-- Check out index.html to see the corresponding code on the JS side.
--
init : E.Value -> ( Model, Cmd Msg )
init flags =
(
case D.decodeValue decoder flags of
Ok model -> model
Err _ -> { name = "", email = "" }
,
Cmd.none
)
-- UPDATE
type Msg
= NameChanged String
| EmailChanged String
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
NameChanged name ->
( { model | name = name }
, Cmd.none
)
EmailChanged email ->
( { model | email = email }
, Cmd.none
)
-- VIEW
view : Model -> Html Msg
view model =
div []
[ input
[ type_ "text"
, placeholder "Name"
, onInput NameChanged
, value model.name
]
[]
, input
[ type_ "text"
, placeholder "Email"
, onInput EmailChanged
, value model.email
]
[]
]
-- PORTS
port setStorage : E.Value -> Cmd msg
-- We want to `setStorage` on every update, so this function adds
-- the setStorage command on each step of the update function.
--
-- Check out index.html to see how this is handled on the JS side.
--
updateWithStorage : Msg -> Model -> ( Model, Cmd Msg )
updateWithStorage msg oldModel =
let
( newModel, cmds ) = update msg oldModel
in
( newModel
, Cmd.batch [ setStorage (encode newModel), cmds ]
)
-- JSON ENCODE/DECODE
encode : Model -> E.Value
encode model =
E.object
[ ("name", E.string model.name)
, ("email", E.string model.email)
]
decoder : D.Decoder Model
decoder =
D.map2 Model
(D.field "name" D.string)
(D.field "email" D.string)
================================================
FILE: more/README.md
================================================
# More JavaScript Integration Examples
This section provides more involved interop examples as well as tutorials around JavaScript usage in conjunction with Elm.
* [Everything you need to know to use WebComponents in your Elm app](webcomponents/README.md)
================================================
FILE: more/webcomponents/README.md
================================================
# A Guide to Using Elm With Webcomponents
This document is meant to be a practical guide to the somewhat confusing [web components specs][wc-specs].
Most documentation on web components show the spec and basic usage examples, assuming that you already know the intricate details of why specific parts of the spec exist in the first place and what use case they try to solve. This situation can be daunting even for experienced web developers and even more so for newcomers.
We try to be as concise as possible, while also providing enough information to get you up and running.
## TL;DR
If you are looking for a quick start with Elm, Webcomponents and the setup of choice have a look at
* [web components setup](#web-components-setup)
* [the browser support section](#Browser-Support)
* don't forget to check [the gotchas section](#Gotchas) to learn how to build Webcomponents that play nice with Elm.
## Prerequisites
First-off: if you haven't read [the official Elm guide][guide] you should do so before reading on, of particular note is [the interop section][guide-interop] as this is where the usage of [ports][guide-ports] and [custom elements][guide-custom-elements] is motivated.
Now that you're up to date and positive that using web components is the way to solve the problem at hand we'll start off with a quick summary of what web components are, followed by a rundown of the parts of [the spec][wc-specs] you'll most likely interact with when using Elm.
The remainder of the guide is dedicated to getting your app ready for web components in all the browsers you want/need to support.
## What are web components and what can I do with them?
You might have heard or read "just use web components" as an answer to the question how to integrate a particular JavaScript API or external library with Elm.
To quote the first paragraph on the [web components specs page][wc-specs]
> These four specifications can __be used on their own__ but combined allow developers to define their own tags (custom element), whose styles are encapsulated and isolated (shadow dom), that can be restamped many times (template), and have a consistent way of being integrated into applications (es module).
I've emphasized the most important information: in order to "use web components" you can and should actually pick and choose what part of the spec you need in order to solve your problem.
* You don't need to use Shadow DOM, if you don't need style encapsulation.
* You don't need to use HTML templates, if you already have a templating solution.
* You don't need ES Modules, if you have a compile-to-js language like, say, *drumroll* Elm.
You may find yourself using all of these specs but they aren't usually necessary in conjuction with Elm. If you want to dive deeper into Webcomponents in plain JavaScript the [MDN page about Webcomponents][mdn-wc] is a good place to start.
## Web Components Setup
At the time of writing this article you're probably using some form of build system for your JavaScript assets, by choice, custom or force. A detailed assessment of bundling modern web apps is outside the scope of this guide but you can check out [our minimal ES5 compatible setup](minimal-es5-setup.html) that provides the polyfills necessary to use web components with older browsers like Internet Explorer 11.
There is more information available in the [browser support section](#browser-support).
## Custom Elements And Elm
Note that if at this point you skipped the earlier requests to have a look at the [interop section of the Elm guide][guide-interop] it's a good idea to do so now.
So we've looked at [the specs][wc-specs] and the most relevant one to Elm is arguably [Custom Elements][wc-custom-elements]. Looking at the examples on that page, defining a custom element is easy enough.
```javascript
class MyElement extends HTMLElement {}
customElements.define("my-element", MyElement);
```
This defines a new HTML element ``. Note that
* the name *has* to include a hyphen and
* the class *needs* to extend `HTMLElement`.
This is what custom elements are about: they let you build your own HTML elements with behavior tailored to your application that are indistinguishable from built-in elements like `` or ``. Which in turn means we can create these kind of elements within Elm without problems.
```elm
import Html
element =
Html.node "my-element" [] [ Html.text "Awesome!" ]
```
Let's have a look at the anatomy of a custom element. Note that this only covers the part of the API that is most relevant to Elm, we provide links to associated concepts where appropriate.
### Construction ([demo](https://ellie-app.com/8Vw6BbYYpc4a1))
A custom element, just like any other built-in element, can be created declaratively using HTML or imperatively using JavaScript.
```javascript
customElements.define("my-element", class extends HTMLElement {});
const element = document.createElement("my-element");
```
```html
```
```elm
import Html
myElement =
Html.node "my-element" [] []
```
### Lifecycles ([demo](https://ellie-app.com/8Vw7J3nFNNma1))
There are lifecycles you can attach clunkily-named callbacks to.
```javascript
customElements.define("i-support-lifecycles", class extends HTMLElement {
constructor() {
super();
// This is being initialized, it's not been
// added to any document yet but you can initialize your fields but
// don't temper with the DOM just yet, do that in `connectedCallback`
}
adoptedCallback() {
// This has been moved to a different document
}
connectedCallback() {
// This has been added to the DOM
}
disconnectedCallback() {
// This has been removed from the DOM
}
});
```
### Attributes ([demo](https://ellie-app.com/8Vwfz6c5v2wa1))
Custom elements may declare supported attributes via `observedAttributes` - only attribute names returned from this trigger the `attributeChangedCallback` when changed. Note that attributes can only carry `string` values.
There's also a [discussion on whether to use an attribute or a property](#attributes-vs-properties), if you're not sure which to use.
```javascript
customElements.define("twbs-alert", class extends HTMLElement {
static get observedAttributes() {
// We need to declare which attributes should be observed,
// only these trigger the `attributeChangedCallback`
return ['type'];
}
connectedCallback() {
this.classList.add('alert');
}
attributeChangedCallback(name, oldValue, newValue) {
switch (name) {
case 'type':
this.classList.remove(`alert-${oldValue}`);
this.classList.add(`alert-${newValue}`);
break;
}
}
});
const element = document.createElement("twbs-alert");
element.setAttribute("type", "info");
```
```html
```
```elm
import Html
import Html.Attributes
alert =
Html.node "twbs-alert"
[ Html.Attributes.attribute "type" "info"
-- or alternatively Html.Attributes.type_ "info"
]
[ Html.text "This is a Twitter Bootstrap info box"
]
```
If you need to transfer object data you can use a [property](#Properties).
### Properties ([demo](https://ellie-app.com/8VwjNrnhyKKa1))
Custom elements can declare properties via `get` and `set`, most kinds of JavaScript objects are supported.
There's also a [discussion on whether to use an attribute or a property](#attributes-vs-properties), if you're not sure which to use.
```javascript
customElements.define("atla-trivia", class extends HTMLElement {
constructor() {
super();
this._meta = null;
}
set meta(value) {
this._meta = value;
}
get meta() {
return this._meta;
}
});
const element = document.createElement("atla-trivia");
element.meta = {
teamAvatar: ["Aang", "Katara", "Soka"],
seasons: 3,
};
```
```html
```
With Elm you need to use a JSON encoder provided by the [`elm/json`][elmpkg-elm-json] package.
```elm
import Html
import Html.Attributes
import Json.Encode -- elm install elm/json
trivia =
Html.node "atla-trivia"
[ Html.Attributes.property "meta"
(Json.Encode.object
[ ( "teamAvatar"
, Json.Encode.list Json.Encode.string
[ "Aang"
, "Katara"
, "Soka"
]
)
, ( "seasons", Json.Encode.int 3 )
]
)
]
[]
```
### Attributes vs Properties
For Elm projects a good rule of thumb is
> Use properties unless you want your custom elements to be used from hand-written or server-rendered HTML.
The reasoning being
* You're interacting with your custom element via JavaScript anyways, so the fact that properties can not be set from raw HTML is usually not an issue
* You can transfer structured data via properties, not just strings
* It's easier to use a consistent interaction method with custom elements from Elm - just use `Html.Attributes.property` everywhere
On the other hand writing custom elements using only attributes might be more suitable for your use case as they can easily be included in static HTML, hand-written or produced by server-side-rendering.
### Children ([demo](https://ellie-app.com/8VwmHKFMYCqa1))
As we've noted a number of times: custom elements are just like regular HTML elements, this includes the ability to be a root node for a sub-tree, your custom element can have child nodes.
```javascript
customElements.define("tree-root", class extends HTMLElement {});
const root = document.createElement("tree-root");
const span = document.createElement("span");
span.innerText = "A span";
const div = document.createElement("div");
div.innerText = "A div";
const plainText = document.createTextNode("Plain text");
root.appendChild(span);
root.appendChild(div);
root.appendChild(plainText);
```
```html
A span
A div
Plain text
```
This is equivalent to the following Elm code. Be sure to read up on [the gotchas](#Gotchas) due to Elm's virtual DOM, though.
```elm
import Html
subTree =
Html.node "tree-root" []
[ Html.span [] [ Html.text "A span" ]
, Html.div [] [ Html.text "A div" ]
, Html.text "Plain Text"
]
```
### Listening to Events ([demo](https://ellie-app.com/8Vwpg8T5GDQa1))
Custom elements support listening to events; this is usually not that useful in conjunction with Elm since you can't imperatively trigger events with it. However, it allows you to employ some nifty tricks like [event delegation][jq-event-delegation] where you use the [DOM's event bubbling phase][mdn-event-bubbling] to listen for events that "bubble up" from your custom element's children.
```javascript
customElements.define("event-delegator", class extends HTMLElement {
_handleInnerClick(evt) {
evt.preventDefault();
evt.stopPropagation();
alert(`You clicked inside of me`);
}
connectedCallback() {
this.addEventListener("click", this._handleInnerClick)
}
disconnectedCallback() {
this.removeEventListener("click", this._handleInnerClick)
}
});
const element = document.createElement("event-delegator");
const button = document.createElement("button");
button.innerHTML = "Click Me!";
element.appendChild(button);
document.body.appendChild(element);
```
```html
```
As we've seen in [the Children section](#Children) building DOM trees with Elm is a breeze. In this example we see both the power and the potential problems with using custom elements in Elm, they allow you to execute arbitrary JavaScript inside your declarative views. So be aware of the fact that a rogue custom element can compromise Elm's runtime guarantees, have a look at [the Gotchas section](#Gotchas) to learn more.
```elm
import Html
root =
Html.node "event-delegator" []
[ Html.button [ {- no `onClick` here -} ]
[ Html.text "Click Me!"
]
]
```
### Triggering Events ([demo](https://ellie-app.com/8VvL6ggT5qJa1))
Custom elements [can listen to events](#Listening-to-Events) but they become really useful as soon as they're triggering events themselves. You mainly want to use this as an adapter to give Elm access to [Web APIs][html5-apis] it does not yet support in form of a core package or to embed functionality from external JavaScript libraries.
To demonstrate this we build a slightly more involved custom element `` that lets the user copy text from an Elm app via button click using the [Document.execCommand API][doc-exec-command]. This is a fairly old non-standard API that's widely supported, nonetheless. The [Clipboard API][mdn-clipboard] is the modern successor, in case you don't need support for older browsers.
The gist is that our element listens for `click` events from its children, copies the value of its `text` attribute to the clipboard and triggers a [`CustomEvent`][mdn-customevent] notifying Elm that the operation has been successful, Elm can also decode event data being passed.
```javascript
customElements.define("copy-to-clipboard", class extends HTMLElement {
static get observedAttributes() {
return ["text"];
}
_handleClick(evt) {
evt.preventDefault();
evt.stopPropagation();
const text = this.getAttribute("text");
this._copy(text);
this.dispatchEvent(new CustomEvent("clipboard", {
bubbles: true,
cancelable: true,
detail: {
copiedText: text,
},
}));
}
_copy(value) {
const preSelected =
document.getSelection().rangeCount > 0
? document.getSelection().getRangeAt(0)
: false;
const textarea = document.createElement('textarea');
textarea.setAttribute('readonly', '');
textarea.style.position = 'absolute';
textarea.style.left = '-9999px';
textarea.value = value;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
if (preSelected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(preSelected);
}
}
connectedCallback() {
this.addEventListener("click", this._handleClick);
}
disconnectedCallback() {
this.removeEventListener("click", this._handleClick);
}
});
```
```elm
module Main exposing (main)
import Browser
import Html exposing (Html)
import Html.Attributes
import Html.Events
import Json.Decode exposing (Decoder)
type Msg
= CopiedToClipboard String
type alias Model =
{ copied : Maybe String
}
clipboardEventDecoder : (String -> msg) -> Decoder msg
clipboardEventDecoder toMsg =
Json.Decode.map (\copiedTextFromDetail -> toMsg copiedTextFromDetail)
(Json.Decode.at [ "detail", "copiedText" ] Json.Decode.string)
view : Model -> Html Msg
view { copied } =
let
textToCopy =
"Text from Elm"
in
Html.div []
[ Html.node "copy-to-clipboard"
[ Html.Attributes.attribute "text" textToCopy
, Html.Events.on "clipboard" (clipboardEventDecoder CopiedToClipboard)
]
[ Html.button []
[ Html.text "Copy "
, Html.text ("\"" ++ textToCopy ++ "\"")
, Html.text " to clipboard"
]
]
, case copied of
Just _ ->
Html.div []
[ Html.div [] [ Html.text "Copied!" ]
, Html.textarea
[ Html.Attributes.placeholder "Try pasting it in here"
]
[]
]
Nothing ->
Html.text ""
]
update : Msg -> Model -> Model
update (CopiedToClipboard text) model =
{ model | copied = Just text }
main : Program () Model Msg
main =
Browser.sandbox
{ init = { copied = Nothing }
, update = update
, view = view
}
```
_Note that Internet Explorer needs [a polyfill for CustomEvent][mdn-customevent-polyfill]._
Many Elm apps use this technique to embed libraries like [CodeMirror](https://github.com/ellie-app/ellie/blob/a45637b81e2495ffada12f9a75dd6bb547a69226/assets/src/Ellie/Ui/CodeEditor.js) or [Google Maps](https://package.elm-lang.org/packages/PaackEng/elm-google-maps/latest/).
Until now all seems hunky-dory in the world of custom elements being embedded with Elm but there are some [gotchas](#Gotchas) you need to be aware of. We'll take a look at these in the next section.
## Gotchas
There are some things to keep in mind when employing custom elements in your Elm app.
### Web Components And Virtual DOM
Elm takes full control of the part of the DOM it manages. Like other virtual-dom based libraries it keeps track of the current state of the DOM in the form of an in-memory representation of the tree and assumes that what is currently rendered in the real DOM is a pure derivative from this in-memory representation.
Some libraries are more forgiving than others with unexpected mutations but if you mess with those nodes too much you risk breaking their invariants, which in turn will cause runtime exceptions, even in Elm. What that means in practice is that you should adhere to the following rules for your custom elements to play nice with virtual-dom libraries in general.
* 1) Make sure your custom element cleans up after itself via `disconnectedCallback` as Elm may decide to re-create any part of the DOM without notice.
* 2) This also means that you should not rely on Elm creating your custom element node exactly x amount of times.
* 3) If your custom element is supposed to receive child nodes from the outside like [in our little event delegation example](#Listening-to-Events) make sure not to add or remove any children as this may confuse Elm's virtual-dom.
* 4) If your custom element doesn't expect children from the outside you are free to manage the element's child nodes.
* 5) If you need both external and self-managed children you can "hide" them inside a [Shadow Root][mdn-shadow-dom], Elm won't inspect sub-trees of shadow roots. Note that there are polyfills for the Shadow DOM spec out there that work in older browsers but this API is farely involved so these might slow down the browser significantly and/or have unexpected behavior.
### Customized Built-ins
The [spec][wc-specs] mentions that you can [extend built-in elements][mdn-customized-builtins], e.g. to make your own `