### Run Elm Land development server
Source: https://elm.land/guide
This command starts the built-in development server for your Elm Land project. Once running, you can access your application in a web browser, typically at `http://localhost:1234`, to see the 'Hello, world!' default page.
```sh
elm-land server
```
--------------------------------
### Create a new Elm Land project
Source: https://elm.land/guide
Use the `elm-land` CLI tool to initialize a new Elm Land project in a specified folder. This command creates a basic project structure including `elm.json`, `elm-land.json`, and an initial homepage file, along with `README.md` and `.gitignore`.
```sh
elm-land init quickstart
```
--------------------------------
### Running Elm Land Server with Specific Environment Variable
Source: https://elm.land/guide/working-with-js
Command line example for starting the Elm Land server while setting a specific environment variable (e.g., `NODE_ENV`) for testing or production builds.
```shell
NODE_ENV=production elm-land server
```
--------------------------------
### Install Elm Land CLI globally
Source: https://elm.land/guide
This command installs the Elm Land command-line interface tool globally using npm. It allows you to create new projects, add features, and run the development server. Node.js v18.16.0 or higher is a prerequisite for installation. If you encounter EACCES errors, consult the official NPM guide for permission fixes.
```sh
npm install -g elm-land@latest
```
--------------------------------
### Elm Land new project default file structure
Source: https://elm.land/guide
This snippet illustrates the default directory and file structure generated when a new Elm Land project is initialized. It highlights the core configuration files (`elm.json`, `elm-land.json`) and the initial `Home_.elm` page within the `src/Pages` directory.
```bash
quickstart/
|- elm.json # 🌐 Elm's `package.json` file
|- elm-land.json # 🌈 Elm Land configuration
|- src/
|- Pages/
|- Home_.elm # 🏡 The homepage for our app
```
--------------------------------
### Example URL Query String Format
Source: https://elm.land/reference/route
Illustrates a common format for URL query parameters, used as an example for the `route.query` field.
```txt
?sort=name&owner=me&date=upcoming
```
--------------------------------
### Elm Land Catch-all Route Example for Blog Paths
Source: https://elm.land/concepts/pages
This snippet provides a practical example of a catch-all route for a blog, showing how 'route.params.all_' captures single or multiple path segments as a List String for different URLs under the '/blog/*' pattern.
```Elm
-- /blog/hello-world
route.params ==
{ all_ = [ "hello-world" ]
}
-- /blog/elm/part-1
route.params ==
{ all_ = [ "elm", "part-1" ]
}
-- /blog/elm/part-2
route.params ==
{ all_ = [ "elm", "part-2" ]
}
```
--------------------------------
### Start the Elm Land development server
Source: https://elm.land/guide/user-input
Launches a local development server to preview the Elm Land application in a web browser.
```sh
elm-land server
```
--------------------------------
### Examples of Catch-All Route URLs
Source: https://elm.land/guide/pages-and-routes
These examples demonstrate various real-world URLs that would match the catch-all route pattern for a code explorer page. They highlight how the '*' wildcard allows for arbitrary depth in the URL path, accommodating different file paths within a repository.
```txt
/elm/compiler/tree/master/README.md
/elm-land/elm-land/tree/main/docs/README.md
/elm-land/elm-land/tree/main/examples/01-hello-world/elm.json
```
--------------------------------
### Elm Land File-Based Routing Example
Source: https://elm.land/concepts
Demonstrates how Elm Land's file-based routing convention maps file paths in the `src/Pages` directory to application URLs, showing examples of nested pages and special naming conventions like trailing underscores.
```txt
src/
└── Pages/
├── Home_.elm
├── Settings
│ ├── Account.elm
│ └── Notifications.elm
├── People.elm
└── People/
└── Id_.elm
```
--------------------------------
### Create a Basic Elm Button
Source: https://elm.land/concepts/components
This example demonstrates how to create a simple button using the `Components.Button.new` constructor and render it with `Components.Button.view`. It shows the minimal setup for a functional button with a label and an `onClick` message.
```Elm
viewSignUpButton : Html msg
viewSignUpButton =
Components.Button.new
{ label = "Sign up"
, onClick = ClickedSignUp
}
|> Components.Button.view
```
--------------------------------
### Install Three.js NPM Package
Source: https://elm.land/guide/working-with-js
This command installs the `three` JavaScript library as a dependency in the current project, saving it to `package.json`.
```sh
npm install --save three
```
--------------------------------
### Initialize and run a new Elm Land project
Source: https://elm.land/guide/pages-and-routes
This snippet provides the command-line steps to create a new Elm Land project, navigate into its directory, and start the development server, making the application accessible locally at http://localhost:1234.
```sh
elm-land init pages-and-routes
```
```sh
cd pages-and-routes
```
```sh
elm-land server
```
--------------------------------
### Install Elm HTTP Package
Source: https://elm.land/guide/user-auth
Installs the `elm/http` package, a prerequisite for making HTTP requests in an Elm Land project.
```sh
elm install elm/http
```
--------------------------------
### Elm: Example Messages for Query Parameter Changes
Source: https://elm.land/reference/page
Provides examples of the `SortParameterChanged` message structure, demonstrating the `from` and `to` values passed to the `update` function when a URL query parameter changes, including cases for initial set, change, and removal.
```elm
-- When "/people" becomes "/people?sort=name"
SortParameterChanged
{ from = Nothing
, to = Just "name"
}
-- When "/people?sort=name" becomes "/people?sort=jobTitle"
SortParameterChanged
{ from = Just "name"
, to = Just "jobTitle"
}
-- When "/people?sort=jobTitle" becomes "/people"
SortParameterChanged
{ from = Just "jobTitle"
, to = Nothing
}
```
--------------------------------
### Elm Cmd Example: Fetching Posts with HTTP Request
Source: https://elm.land/concepts/effect
Provides a practical Elm example of fetching posts for a Twitter clone's feed using `Cmd Msg`. It demonstrates how to initialize a page, make an HTTP GET request with dynamic headers (for authorization) and a timeout, and handle the response, highlighting the need to pass `shared` values for context.
```elm
module Pages.Home_ exposing (Model, Msg, page)
-- ...
page : Shared.Model -> Route () -> Page Model Msg
page shared route =
Page.element
{ init = init shared
, ...
}
-- ...
init : Shared.Model -> () -> ( Model, Cmd Msg )
init shared _ =
( { model | posts = Loading }
, Http.request
{ method = "GET"
, url = shared.baseApiUrl ++ "/api/feed"
, headers =
case shared.user of
Just user ->
[ Http.header "Authorization" ("Bearer " ++ user.token)
]
Nothing ->
[]
, body = Http.emptyBody
, expect = Http.expectJson GotPostsForFeed decoder
, timeout = Just 15000
, tracker = Nothing
}
)
decoder : Json.Decode.Decoder (List Post)
decoder =
...
-- ...
```
--------------------------------
### Start the Elm Land development server
Source: https://elm.land/guide/user-auth
Launch the local development server for the Elm Land project, making the application accessible in a web browser at `http://localhost:1234`.
```sh
elm-land server
```
--------------------------------
### Run the Elm Land development server
Source: https://elm.land/guide/working-with-js
Start the local development server for the Elm Land project, typically accessible at http://localhost:1234, to view the application.
```sh
elm-land server
```
--------------------------------
### Install Elm JSON Package
Source: https://elm.land/guide/rest-apis
Command to install the `elm/json` package, essential for decoding and encoding JSON data in Elm.
```sh
npx elm install elm/json
```
--------------------------------
### Install Elm Land CLI Globally
Source: https://elm.land/concepts
This command installs the Elm Land command-line interface (CLI) tool globally using npm. The CLI enables users to create new projects, add pages or layouts, run a development server, and perform production builds.
```Shell
npm install -g elm-land
```
--------------------------------
### Elm Land Generated Pages Model Example
Source: https://elm.land/concepts/shared
Illustrates an example of the `Pages.Model` type generated by Elm Land for an application with multiple distinct pages like Dashboard, Settings, and SignIn.
```Elm
module Pages exposing (..)
-- ...
type Model
= Dashboard Pages.Dashboard.Model
| Settings Pages.Settings.Model
| SignIn Pages.SignIn.Model
```
--------------------------------
### Elm Land: Demonstrate Catch-all Route Parameter Mapping
Source: https://elm.land/concepts/pages
This example illustrates how Elm Land's catch-all routing (ALL_.elm) works in conjunction with dynamic parameters. It shows how the route.params record is populated with user, repo, branch, and all_ (a list of strings) based on different URL paths, mimicking a file explorer structure.
```elm
-- /elm-land/elm-land/tree/main/README.md
route.params ==
{ repo = "elm-land"
, user = "elm-land"
, branch = "main"
, all_ = [ "README.md" ]
}
-- /ryannhg/elm-spa/tree/master/README.md
route.params ==
{ repo = "ryannhg"
, user = "elm-spa"
, branch = "master"
, all_ = [ "README.md" ]
}
-- /elm-land/elm-land/tree/main/projects/cli/package.json
route.params ==
{ repo = "elm-land"
, user = "elm-land"
, branch = "main"
, all_ = [ "projects", "cli", "package.json" ]
}
```
--------------------------------
### Elm Land app.env Configuration Example
Source: https://elm.land/reference/elm-land-json
Example JSON configuration for `elm-land.json` showing how to expose specific environment variables like `NODE_ENV` and `PUBLIC_GITHUB_TOKEN` to the Elm application. These variables become accessible via `src/interop.js`.
```jsonc
{
"app": {
// ...
"env": [ "NODE_ENV", "PUBLIC_GITHUB_TOKEN" ],
// ...
}
}
```
--------------------------------
### Install Elm HTTP Package
Source: https://elm.land/guide/rest-apis
Command to install the `elm/http` package, which is used for sending HTTP requests in Elm applications.
```sh
npx elm install elm/http
```
--------------------------------
### Start PokeAPI Cache Server with Delay
Source: https://elm.land/guide/rest-apis
Command to start the Node.js PokeAPI cache server. `DELAY=1000` sets an intentional 1000ms delay on each request to simulate loading states.
```sh
DELAY=1000 npm start
```
--------------------------------
### Elm: Example Messages for URL Hash Changes
Source: https://elm.land/reference/page
Provides examples of the `UrlHashChanged` message structure, illustrating the `from` and `to` values passed to the `update` function when the URL hash fragment changes, including cases for initial set and subsequent changes.
```elm
-- When "/people" becomes "/people#about-us"
UrlHashChanged
{ from = Nothing
, to = Just "about-us"
}
-- When "/people#about-us" becomes "/people#our-mission"
UrlHashChanged
{ from = Just "about-us"
, to = Just "our-mission"
}
```
--------------------------------
### Elm Layout.withParentProps Usage Example
Source: https://elm.land/reference/layout
Illustrates how to use `Layout.withParentProps` within an Elm layout definition. This example shows how to pipe the result of `Layout.new` into `Layout.withParentProps` to provide specific user settings to a parent sidebar layout.
```elm
module Layouts.Sidebar.Header exposing (..)
-- ...
layout :
Props
-> Shared.Model
-> Route ()
-> Layout Layouts.Sidebar.Props Model Msg contentMsg
layout props shared route =
Layout.new { ... }
|> Layout.withParentProps
{ user = settings.user
}
```
--------------------------------
### Example Usage of Route.Path.href for Navigation
Source: https://elm.land/reference/route-path
This example demonstrates how to use `Route.Path.href` within an Elm `view` function to create a navigation link. By passing a `Route.Path` value, it ensures that links are type-checked at compile time, improving application robustness.
```Elm
import Html exposing (..)
import Route.Path
viewLinkToDashboard : Html msg
viewLinkToDashboard =
a [ Route.Path.href Route.Path.Dashboard ]
[ text "Go to Dashboard"
]
```
--------------------------------
### Example CSS for Elm Land Page Layout
Source: https://elm.land/guide/pages-and-routes
Provides a sample `main.css` file with basic styling for the `body`, `.layout`, and `.sidebar` elements, illustrating how CSS placed in the `static` folder can be used to style an Elm Land application.
```css
/* static/main.css */
body {
padding: 32px;
}
.layout {
display: flex;
gap: 16px;
}
.sidebar {
display: flex;
flex-direction: column;
gap: 8px;
}
```
--------------------------------
### Elm Land HEAD Tag Attributes Configuration Example
Source: https://elm.land/reference/elm-land-json
Demonstrates how to configure attributes for the `
` tag in `elm-land.json` and the resulting `dist/index.html` output, adding `color` and `fruit` attributes.
```jsonc
{
"app": {
// ...
"html": {
"attributes": {
// ...
"head": { "color": "red", "fruit": "apple" },
// ...
},
// ...
}
}
}
```
```html
```
--------------------------------
### Elm Land HTML Tag Attributes Configuration Example
Source: https://elm.land/reference/elm-land-json
Demonstrates how to configure attributes for the `` tag in `elm-land.json` and the resulting `dist/index.html` output, adding `lang` and `elm` attributes.
```jsonc
{
"app": {
// ...
"html": {
"attributes": {
"html": { "lang": "en", "elm": "very-cool" },
// ...
},
// ...
}
}
}
```
```html
```
--------------------------------
### Elm Land: Example Project Page File Structure
Source: https://elm.land/concepts/pages
This snippet illustrates a typical directory structure for pages within an Elm Land project. It shows how Home_.elm, nested pages like Settings/Account.elm, and dynamic pages like People/Id_.elm are organized, which directly influences how URLs are mapped to page files.
```txt
src/
└── Pages/
├── Home_.elm
├── Settings
│ ├── Account.elm
│ └── Notifications.elm
├── People.elm
└── People/
└── Id_.elm
```
--------------------------------
### Example Pokemon Details JSON Response
Source: https://elm.land/guide/rest-apis
Illustrates a sample JSON response from the PokeAPI for a Pokemon, highlighting key fields like name, ID, sprites, and types that are used for display.
```jsonc
{
// ...
"name": "bulbasaur",
"id": 1,
// ...
"sprites": {
// ...
"other": {
// ...
"official-artwork": {
// ...
"front_default": ".../bulbasaur.png"
}
}
},
"types": [
{
"slot": 1,
"type": {
"name": "grass",
"url": "http://localhost:5000/api/v2/type/12/"
}
},
{
"slot": 1,
"type": {
"name": "poison",
"url": "http://localhost:5000/api/v2/type/4/"
}
}
]
}
```
--------------------------------
### JSON Example for app.proxy Dev Server Configuration
Source: https://elm.land/reference/elm-land-json
Demonstrates how to set up a proxy rule in `elm-land.json` to redirect requests from `/api` on the development server (e.g., `http://localhost:1234/api/xyz`) to a backend API server (e.g., `http://localhost:5000/api/xyz`). Note that JavaScript functions like `rewrite` or `configure` are not supported.
```jsonc
{
"app": {
// ...
"proxy": {
"/api": "http://localhost:5000"
}
}
}
```
--------------------------------
### Elm Accessing Route Query Parameters
Source: https://elm.land/reference/route
Demonstrates how to access and retrieve values from the `route.query` dictionary, which parses URL query parameters into key-value pairs. Shows examples of successful retrieval and a non-existent key.
```elm
-- ?sort=name&owner=me&date=upcoming
Dict.get "sort" route.query == Just "name"
Dict.get "owner" route.query == Just "me"
Dict.get "date" route.query == Just "upcoming"
Dict.get "archived" route.query == Nothing
```
--------------------------------
### Example Folder Structure for Elm Path Generation
Source: https://elm.land/concepts/route
This text snippet illustrates a typical `src/Pages` folder structure. The organization of these files directly influences the generated `Route.Path` custom type, mapping directory and file names to type constructors.
```txt
src/
└── Pages/
├── Home_.elm
├── Settings
│ ├── Account.elm
│ └── Notifications.elm
├── People.elm
└── People/
└── Id_.elm
```
--------------------------------
### Initialize the Elm Model with a starting counter value
Source: https://elm.land/guide/user-input
Defines the `init` function to provide the initial state of the application's `Model`. For the counter app, it sets the `counter` field to `0` when the page first loads.
```elm
init : Model
init =
{ counter = 0
}
```
--------------------------------
### Run Elm Land local development server
Source: https://elm.land/concepts/cli
The `elm-land server` command starts a local development server, powered by Vite, typically at `http://localhost:1234`. If the default port is occupied, it automatically finds the next available one. Elm Land manages Vite configuration internally via `elm-land.json`, ensuring seamless upgrades and consistent developer experience without custom `vite.config.js` files.
```txt
elm-land server ................ run a local dev server
```
--------------------------------
### Configure Elm Development Debugger in elm-land.json
Source: https://elm.land/reference/elm-land-json
Example JSON snippet demonstrating how to configure the Elm debugger for the development environment within the `elm-land.json` file. Setting `debugger` to `true` enables the debugger.
```json
{
"app": {
"elm": {
"development": { "debugger": true },
// ...
}
// ...
}
}
```
--------------------------------
### API Request: GET /api/me (With Token)
Source: https://elm.land/guide/user-auth
Example HTTP GET request to the `/api/me` endpoint including a valid user token as a query parameter, demonstrating the expected successful response. This shows how to properly authenticate the request.
```APIDOC
GET http://localhost:5000/api/me?token=ryans-secret-token
```
```json
Status code: 200
{
"id": "1",
"name": "Ryan Haskell-Glatz",
"profileImageUrl": "https://avatars.githubusercontent.com/u/6187256?v=4",
"email": "ryan@elm.land"
}
```
--------------------------------
### Configure Elm Production Debugger in elm-land.json
Source: https://elm.land/reference/elm-land-json
Example JSON snippet demonstrating how to configure the Elm debugger for the production environment within the `elm-land.json` file. Setting `debugger` to `false` disables the debugger for optimized builds.
```json
{
"app": {
"elm": {
// ...
"production": { "debugger": false }
}
// ...
}
}
```
--------------------------------
### Complete Elm Land Counter Application File
Source: https://elm.land/guide/user-input
This snippet provides the complete source code for `src/Pages/Counter.elm`, combining the `init`, `update`, and `view` functions into a single, runnable Elm Land application. It includes the module declaration, necessary imports, the `Page.sandbox` setup, the `Model` type alias, initial state, `Msg` type definition, and the full implementations of `update` and `view` functions, demonstrating a complete interactive counter.
```Elm
module Pages.Counter exposing (Model, Msg, page)
import Html exposing (Html)
import Html.Events
import Page exposing (Page)
import View exposing (View)
-- PAGE
page : Page Model Msg
page =
Page.sandbox
{ init = init
, update = update
, view = view
}
-- INIT
type alias Model =
{ counter : Int
}
init : Model
init =
{ counter = 0
}
-- UPDATE
type Msg
= UserClickedIncrement
| UserClickedDecrement
update : Msg -> Model -> Model
update msg model =
case msg of
UserClickedIncrement ->
{ model | counter = model.counter + 1 }
UserClickedDecrement ->
{ model | counter = model.counter - 1 }
-- VIEW
view : Model -> View Msg
view model =
{ title = "Counter"
, body =
[ Html.button
[ Html.Events.onClick UserClickedIncrement ]
[ Html.text "+" ]
, Html.div []
[ Html.text (String.fromInt model.counter) ]
, Html.button
[ Html.Events.onClick UserClickedDecrement ]
[ Html.text "-" ]
]
}
```
--------------------------------
### API Request: GET /api/me (Missing Token)
Source: https://elm.land/guide/user-auth
Example HTTP GET request to the `/api/me` endpoint without a required authentication token, demonstrating the expected error response. This illustrates the API's security requirement.
```APIDOC
GET http://localhost:5000/api/me
```
```json
Status code: 401
{
"message": "Token is required to access /api/me"
}
```
--------------------------------
### Initialize a new Elm Land project
Source: https://elm.land/guide/user-input
Creates a new Elm Land project directory with a basic structure, ready for development.
```sh
elm-land init user-input
```
--------------------------------
### Elm Land Page: Passing Route Information to Init Function
Source: https://elm.land/concepts/pages
Illustrates how to pass the `route` argument from the `page` function to the `init` function in an Elm Land application. This enables the `init` function to access URL parameters or query information for initial state setup.
```elm
module Pages.Settings exposing (Model, Msg, page)
import Page exposing (Page)
-- ...
page : Shared.Model -> Route () -> Page Model Msg
page shared route =
Page.new
{ init = init route
, update = update
, view = view
, subscriptions = subscriptions
}
```
--------------------------------
### Accessing Catch-all Route Parameters in Elm Land
Source: https://elm.land/concepts/pages
This example illustrates how a catch-all route, defined by 'ALL_.elm', provides access to all subsequent URL path segments as a List String via the 'route.params.all_' variable. This is useful for handling paths of unknown depth.
```Elm
-- Filename: src/Pages/ALL_.elm
-- URL: /each/part/of/the/path
route.params ==
{ all_ = [ "each", "part", "of", "the", "path" ]
}
```
--------------------------------
### Initial Elm sandbox page module structure
Source: https://elm.land/guide/user-input
The default Elm code generated for a new sandbox page. It defines the basic `Model`, `Msg`, `init`, `update`, and `view` functions required by the Elm Architecture, serving as a starting point for interactive UI.
```elm
module Pages.Counter exposing (Model, Msg, page)
import Html exposing (Html)
import Page exposing (Page)
import View exposing (View)
-- PAGE
page : Page Model Msg
page =
Page.sandbox
{ init = init
, update = update
, view = view
}
-- INIT
type alias Model =
{}
init : Model
init =
{}
-- UPDATE
type Msg
= NoOp
update : Msg -> Model -> Model
update msg model =
case msg of
NoOp ->
model
-- VIEW
view : Model -> View Msg
view model =
{ title = "Counter"
, body = [ Html.text "/counter" ]
}
```
--------------------------------
### Example HTML Output for Elm Notification Component
Source: https://elm.land/concepts/components
This HTML snippet illustrates the structure rendered in the browser when the Elm `Components.Notification.view` function is called with specific data. It shows how the component's properties are translated into standard HTML elements with Bulma CSS classes.
```html
Your credit card expires soon!
The Visa credit card ending in 1234 will expire on 08/24.
Be sure to update your payment settings to avoid any
gaps in service.
```
--------------------------------
### Integrate Sidebar component into Elm Land pages
Source: https://elm.land/guide/pages-and-routes
These Elm code snippets demonstrate how to import and use the `Components.Sidebar` module across different pages (`Pages.Home_`, `Pages.Settings.Account`, `Pages.User_`). Each example shows how to pass a specific title and body content, including dynamic parameters for the user page, to wrap page content within the sidebar layout.
```Elm
module Pages.Home_ exposing (page)
import Components.Sidebar
import Html exposing (..)
import View exposing (View)
page : View msg
page =
Components.Sidebar.view
{ title = "Homepage"
, body = [ text "Hello, world!" ]
}
```
```Elm
module Pages.Settings.Account exposing (page)
import Components.Sidebar
import Html exposing (..)
import View exposing (View)
page : View msg
page =
Components.Sidebar.view
{ title = "Pages.Settings.Account"
, body = [ text "/settings/account" ]
}
```
```Elm
module Pages.User_ exposing (page)
import Components.Sidebar
import Html exposing (..)
import View exposing (View)
page : { username : String } -> View msg
page params =
Components.Sidebar.view
{ title = "Pages.User_"
, body = [ text ("/" ++ params.user) ]
}
```
--------------------------------
### Build an Elm Land application for production
Source: https://elm.land/guide/deploying
Use the `elm-land build` command to compile, optimize, and minify your Elm Land application for production deployment. The output confirms a successful build.
```sh
elm-land build
```
```txt
🌈 Elm Land (v0.20.1) build was successful.
⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺
```
--------------------------------
### Pass route to Elm init function
Source: https://elm.land/guide/user-auth
This Elm code snippet illustrates how to extend the pattern of passing data to `view` to also pass `route` to the `init` function of an Elm `Layout`. By passing `route` to `init`, the initialization logic gains access to the current URL, enabling URL-dependent setup or data fetching.
```elm
module Layouts.Sidebar exposing (Props, Model, Msg, layout)
-- ...
layout : Props -> Shared.Model -> Route () -> Layout Model Msg contentMsg
layout props shared route =
Layout.new
{ init = init route
, update = update
, view = view props
, subscriptions = subscriptions
}
-- ...
```
--------------------------------
### Initialize a new Elm Land project
Source: https://elm.land/guide/working-with-js
Command to create a new Elm Land project with a specified name, setting up the basic project structure.
```sh
elm-land init working-with-js
```
--------------------------------
### Setting up Local Backend API for User Authentication
Source: https://elm.land/guide/user-auth
These bash commands provide instructions to clone and run a simple Node.js backend API server locally. This API will be used to simulate user authentication requests, allowing the Elm frontend to interact with a real backend.
```bash
# Clone the backend API project into an "api-server" folder
npx degit elm-land/elm-land/examples/05-user-auth/api-server api-server
# Enter that folder, and run the project
cd api-server
npm start
```
--------------------------------
### Define Three.js Web Component for Forest Demo
Source: https://elm.land/guide/working-with-js
This JavaScript snippet defines a custom web component named `forest-demo` that encapsulates a Three.js 3D scene. It initializes a camera, renderer, controls, and populates the scene with a simple forest of cylinders, along with lighting. The code is adapted from a Three.js example and is designed to be appended to the DOM when the component is connected.
```javascript
//
// This code was taken from this Three.js example:
// https://github.com/mrdoob/three.js/blob/master/examples/webgl_lightprobe.html
//
import * as THREE from 'three'
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'
window.customElements.define('forest-demo', class extends HTMLElement {
connectedCallback() {
let size = {
width: 800,
height: 450
}
let camera, controls, scene, renderer
let self = this
init()
animate()
function init() {
scene = new THREE.Scene()
scene.background = new THREE.Color(0xcccccc)
scene.fog = new THREE.FogExp2(0xcccccc, 0.002)
renderer = new THREE.WebGLRenderer({ antialias: true })
renderer.setPixelRatio(window.devicePixelRatio)
renderer.setSize(size.width, size.height)
self.appendChild(renderer.domElement)
camera = new THREE.PerspectiveCamera(60, size.width / size.height, 1, 1000)
camera.position.set(400, 200, 0)
// controls
controls = new OrbitControls(camera, renderer.domElement)
controls.listenToKeyEvents(window)
controls.enableDamping = true
controls.dampingFactor = 0.05
controls.screenSpacePanning = false
controls.minDistance = 100
controls.maxDistance = 500
controls.maxPolarAngle = Math.PI / 2
// world
const geometry = new THREE.CylinderGeometry(0, 10, 30, 4, 1)
const material = new THREE.MeshPhongMaterial({ color: 0xffffff, flatShading: true })
for (let i = 0; i < 500; i++) {
const mesh = new THREE.Mesh(geometry, material)
mesh.position.x = Math.random() * 1600 - 800
mesh.position.y = 0
mesh.position.z = Math.random() * 1600 - 800
mesh.updateMatrix()
mesh.matrixAutoUpdate = false
scene.add(mesh)
}
// lights
const dirLight1 = new THREE.DirectionalLight(0xffffff)
dirLight1.position.set(1, 1, 1)
scene.add(dirLight1)
const dirLight2 = new THREE.DirectionalLight(0x002288)
dirLight2.position.set(-1, -1, -1)
scene.add(dirLight2)
const ambientLight = new THREE.AmbientLight(0x222222)
scene.add(ambientLight)
window.addEventListener('resize', onWindowResize)
}
function onWindowResize() {
camera.aspect = size.width / size.height
camera.updateProjectionMatrix()
renderer.setSize(size.width, size.height)
}
function animate() {
requestAnimationFrame(animate)
controls.update()
render()
}
function render() {
renderer.render(scene, camera)
}
}
})
```
--------------------------------
### Initialize a new Elm Land project
Source: https://elm.land/concepts/cli
The `elm-land init` command creates a new Elm Land project. It sets up essential files like `elm.json`, `elm-land.json`, and the initial homepage `src/Pages/Home_.elm`. It also generates a `.gitignore` and an `.elm-land` folder, which should not be committed to version control. A folder name is a required argument for the new project's directory.
```txt
elm-land init ...... create a new project
```
--------------------------------
### Elm `Route.Path.href` Function Example Usage
Source: https://elm.land/concepts/route
Demonstrates how to use `Route.Path.href` within an `Html.a` element to generate a link. This example creates an anchor tag that points to the `/people` page, ensuring the link is type-safe.
```elm
--
-- Renders:
-- People page
--
Html.a
[ Route.Path.href Route.Path.People ]
[ Html.text "People page" ]
```
--------------------------------
### Initialize a new Elm Land project
Source: https://elm.land/guide/user-auth
Use the Elm Land CLI to create a new project directory named 'user-auth', setting up the basic project structure.
```sh
elm-land init user-auth
```
--------------------------------
### Initialize Elm Land Project for REST APIs
Source: https://elm.land/guide/rest-apis
Commands to set up a new Elm Land project named 'rest-apis', navigate into its directory, and launch the development server. This project will be used to demonstrate REST API integration.
```sh
elm-land init rest-apis
cd rest-apis
elm-land server
```
--------------------------------
### Configure Netlify for Elm Land SPA deployment
Source: https://elm.land/guide/deploying
Add this `netlify.toml` file to your project's root to instruct Netlify on how to build your Elm Land application and how to handle SPA redirects, ensuring all routes are directed to `index.html`.
```toml
# 1️⃣ Tells Netlify how to build your app, and where the files are
[build]
command = "npx elm-land build"
publish = "dist"
# 2️⃣ Handles SPA redirects so all your pages work
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
```
--------------------------------
### Elm Land Standard Project Structure
Source: https://elm.land/concepts
Illustrates the standard directory and file organization for an Elm Land application, including configuration files (`elm.json`, `elm-land.json`), source code folders (`src/Pages`, `src/Layouts`, `src/Components`), and a static assets directory (`static`).
```txt
your-project/
├── elm.json
├── elm-land.json
├── src/
│ └── Pages/
│ └── Layouts/
│ └── Components/
└── static/
└── main.css
```
--------------------------------
### Elm Land UI Components Folder Structure
Source: https://elm.land/concepts
Shows the typical organization of reusable UI components within the `src/Components` directory, illustrating how individual components like accordions, buttons, dropdowns, and modals are defined in separate files, potentially with nested sub-folders.
```txt
src/
└── Components/
├── Accordion.elm
├── Button.elm
├── Dropdown
│ ├── Autocomplete.elm
│ └── Multiselect.elm
└── Modal.elm
```
--------------------------------
### Elm Layout `view` Function Example with Content Embedding
Source: https://elm.land/concepts/layouts
An example demonstrating how to use the `view` function in an Elm layout to embed inner page content (`content.body`), modify the page title (`content.title`), and map messages from a sidebar component (`viewSidebar`) using `Html.map toContentMsg`.
```elm
view :
{ model : Model
, toContentMsg : Msg -> contentMsg
, content : View contentMsg
}
-> View contentMsg
view { model, toContentMsg, content } =
{ title = content.title ++ " | My app"
, body =
[ -- View the sidebar
viewSidebar model
|> Html.map toContentMsg
-- View the inner content
, div [ class "page" ] content.body
]
}
viewSidebar : Model -> Html Msg
viewSidebar model =
aside [ class "sidebar" ] [ ... ]
```
--------------------------------
### Initialize Node.js Project with npm
Source: https://elm.land/guide/working-with-js
This command initializes a new Node.js project, creating a `package.json` file with default values, which is necessary for managing JavaScript dependencies.
```sh
npm init -y
```
--------------------------------
### Example Usage of Route.Path.fromString in Update Function
Source: https://elm.land/reference/route-path
This example illustrates how `Route.Path.fromString` can be used within an Elm `update` function to handle programmatic navigation. Specifically, it shows redirecting a user after a successful sign-in to a path specified by a 'from' query parameter, defaulting to the Dashboard if no valid path is found.
```Elm
update : Route () -> Msg -> Model -> ( Model, Effect Msg )
update route msg model =
case msg of
OnSignInSuccess user ->
( { model | user = Just user }
, Effect.pushRoute
{ path =
Dict.get "from" route.query
|> Maybe.andThen Route.Path.fromString
|> Maybe.withDefault Route.Path.Dashboard
, query = Dict.empty
, hash = Nothing
}
)
```
--------------------------------
### Elm Land View.map function (Elm UI example)
Source: https://elm.land/concepts/view
This internal Elm Land function is used to transform messages (`msg1` to `msg2`) within a `View` type, which is crucial for connecting different pages and components. The example illustrates its application with `elm-ui`, showing how attributes and elements are mapped.
```elm
map : (msg1 -> msg2) -> View msg1 -> View msg2
map fn view =
{ title = view.title
, attributes = List.map (Element.mapAttribute fn) view.attributes
, element = Element.map fn view.element
}
```
--------------------------------
### Navigate into the new project directory
Source: https://elm.land/guide/working-with-js
Change the current directory to the newly created Elm Land project, preparing for further commands.
```sh
cd working-with-js
```
--------------------------------
### Elm Land View.toBrowserDocument function (Elm UI example)
Source: https://elm.land/concepts/view
This internal Elm Land function is responsible for converting a custom `View msg` type into Elm's expected `Browser.Document msg` type. The provided example demonstrates its usage when `elm-ui` is integrated, showing how `elm-ui` elements are rendered into the document body.
```elm
toBrowserDocument :
{ shared : Shared.Model.Model
, route : Route ()
, view : View msg
}
-> Browser.Document msg
toBrowserDocument { view } =
{ title = view.title
, body = [ Element.layout view.attributes view.element ]
}
```
--------------------------------
### Navigate into the project directory
Source: https://elm.land/guide/user-auth
Change the current working directory to the newly created 'user-auth' project to perform further operations within it.
```sh
cd user-auth
```
--------------------------------
### Fetch Pokemon Details API Request
Source: https://elm.land/guide/rest-apis
Demonstrates the HTTP GET request URL to retrieve details for a specific Pokemon from the local PokeAPI endpoint.
```txt
GET http://localhost:5000/api/v2/pokemon/bulbasaur
```
--------------------------------
### Elm Land Project Structure with Static Folder
Source: https://elm.land/guide/pages-and-routes
Demonstrates the typical directory layout for an Elm Land application, highlighting the location of the `static` folder relative to `src` and `elm-land.json` for serving static assets.
```txt
pages-and-routes/
├── README.md
├── elm.json
├── elm-land.json
├── src/
│ └── Pages/
│ └── ...
└── static/
└── main.css
```
--------------------------------
### Example Output of Successful Elm Flags Decoding
Source: https://elm.land/guide/working-with-js
Console output showing a successful decoding of flags from JavaScript, indicating the `message` field was correctly received.
```Text
FLAGS: Ok { message = "Hello, from JavaScript flags!" }
```
--------------------------------
### Define initial Elm Land interop.js structure
Source: https://elm.land/guide/working-with-js
Defines the basic structure for `src/interop.js`, including the `flags` function for passing initial data to Elm before startup and the `onReady` function for post-startup interactions with Elm ports.
```js
// This is called BEFORE your Elm app starts up
//
// The value returned here will be passed as flags
// into your `Shared.init` function.
export const flags = ({ env }) => {
}
// This is called AFTER your Elm app starts up
//
// Here you can work with `app.ports` to send messages
// to your Elm application, or subscribe to incoming
// messages from Elm
export const onReady = ({ app, env }) => {
}
```
--------------------------------
### Vercel Configuration for Elm Land Deployment
Source: https://elm.land/guide/deploying
This `vercel.json` configuration file is placed at the project root (next to `elm-land.json`) to define the build command, specify the output directory, and implement a rewrite rule to ensure 404 requests are handled by redirecting them to the root path.
```json
{
"buildCommand": "npx elm-land build",
"outputDirectory": "dist",
"rewrites": [
{ "source": "/(.*)", "destination": "/" }
]
}
```
--------------------------------
### Build Elm Land app for production
Source: https://elm.land/concepts/cli
The `elm-land build` command compiles the Elm Land application for production. This process includes optimizing Elm code with the `--optimize` flag and minifying JavaScript using Terser. The output is a static site located in the `./dist` folder, ready for deployment. Users should configure Single Page Application (SPA) redirects to the `dist/index.html` file for correct routing.
```txt
elm-land build .......... build your app for production
```
--------------------------------
### Example Output of Failed Elm Flags Decoding
Source: https://elm.land/guide/working-with-js
Console output showing an error during Elm flags decoding when JavaScript sends an unexpected `null` value for a `String` field.
```Text
FLAGS: Err (Field "message" (Failure "Expecting a STRING" ))
```
--------------------------------
### JavaScript Sending Null Message to Elm
Source: https://elm.land/guide/working-with-js
Example JavaScript `flags` export function that intentionally sends a `null` value for the `message` field, demonstrating error handling in Elm.
```JavaScript
export const flags = ({ env }) => {
return {
message: null
}
}
```
--------------------------------
### Add a new Elm Land layout using CLI
Source: https://elm.land/concepts/layouts
Use the elm-land CLI tool to generate a new layout file, for example, 'Sidebar'. This command creates a file at `src/Layouts/Sidebar.elm`.
```sh
elm-land add layout Sidebar
```
--------------------------------
### Create a new sign-in page
Source: https://elm.land/guide/user-auth
Generate a new page file and route for `/sign-in` using the Elm Land CLI, providing a fully featured page structure for authentication.
```sh
elm-land add page /sign-in
```
--------------------------------
### API Endpoint for Pokemon Data
Source: https://elm.land/guide/rest-apis
This is the API endpoint used to fetch the first 150 Pokemon data from a local server. It's a standard GET request to retrieve a list of resources.
```txt
GET http://localhost:5000/api/v2/pokemon?limit=150
```
--------------------------------
### Navigate into the project directory
Source: https://elm.land/guide/user-input
Changes the current working directory to the newly created Elm Land project.
```sh
cd user-input
```
--------------------------------
### Send initial data to Elm using JavaScript flags
Source: https://elm.land/guide/working-with-js
Demonstrates how to use the `flags` function in `src/interop.js` to send an initial message object from JavaScript to the Elm application upon startup, making data available to Elm's `Shared.init` function.
```js
// ...
export const flags = ({ env }) => {
return {
message: "Hello, from JavaScript flags!"
}
}
// ...
```
--------------------------------
### Elm Land HTML Title Configuration Example
Source: https://elm.land/reference/elm-land-json
Demonstrates how to set the default page title in `elm-land.json` and its appearance in the generated `dist/index.html`. This title is used when JavaScript is disabled or before the Elm app initializes.
```jsonc
{
"app": {
// ...
"html": {
// ...
"title": "My Cool App!",
// ...
}
}
}
```
```html
My Cool App!
```
--------------------------------
### Elm JSON Encoding for Sign-In Request Body
Source: https://elm.land/guide/user-auth
Demonstrates how to serialize Elm values into a JSON object using `Json.Encode.object` from `elm/json` for the sign-in request body. An example of the resulting JSON structure is provided.
```elm
-- ...
let
body : Json.Encode.Value
body =
Json.Encode.object
[ ( "email", Json.Encode.string options.email )
, ( "password", Json.Encode.string options.password )
]
-- ...
in
-- ...
```
```json
{ "email": "ryan@elm.land", "password": "secret123" }
```
--------------------------------
### Elm Land Default HTML Template Structure
Source: https://elm.land/reference/elm-land-json
Illustrates the general structure of the `index.html` file generated by Elm Land, showing placeholders for attributes, title, and various tags that are populated from the `app.html` configuration.
```html
{{title}}
{{ meta tags }}
{{ link tags }}
{{ script tags }}
```
--------------------------------
### Elm `Route.Path.toString` Function Example Usage
Source: https://elm.land/concepts/route
Illustrates how to use `Route.Path.toString` to obtain a URL string from a `Path` value. This is particularly useful when integrating with other Elm UI libraries, such as `Element`, where a direct URL string is needed for link properties.
```elm
Element.link
{ label = "People page"
, url = Route.Path.toString Route.Path.People
}
```
--------------------------------
### Define Props Type for Elm Layout with Auth.User
Source: https://elm.land/concepts/layouts
Example of defining the `Props` type alias in an Elm layout to expect an `Auth.User` value. This ensures that the layout, and consequently the view, will only be visible for signed-in users, as the `Auth.User` value is required.
```elm
module Layouts.Sidebar exposing (Props, Model, Msg, layout)
import Auth
import Layout exposing (Layout)
-- ...
type alias Props =
{ user : Auth.User
}
layout : Props -> Shared.Model -> Route () -> Layout () Model Msg contentMsg
layout props shared route =
...
-- ...
```
--------------------------------
### Add Catch-All Route and Elm Page for Code Explorer
Source: https://elm.land/guide/pages-and-routes
This snippet shows how to use the 'elm-land add page' command to create a catch-all route for a code explorer page, followed by the generated Elm page module. The Elm page demonstrates how the 'all_' parameter, a 'List String', captures the variable segments of the URL.
```sh
elm-land add page:view '/:user/:repo/tree/:branch/*'
```
```elm
module Pages.User_.Repo_.Tree.Branch_.ALL_ exposing (page)
import Html exposing (..)
import View exposing (View)
page :
{ user : String
, repo : String
, branch : String
, all_ : List String
}
-> View msg
page params =
{ title = "Pages.User_.Repo_.Tree.Branch_.ALL_"
, body = [ text "..." ]
}
```
--------------------------------
### Example JSON API Response for Pokemon List
Source: https://elm.land/guide/rest-apis
Illustrates the structure of the JSON data returned by the `/api/v2/pokemon?limit=150` REST API endpoint. It includes the total count, pagination links, and an array of Pokemon objects with their names and URLs.
```jsonc
{
"count": 1154,
"next": "http://localhost:5000/api/v2/pokemon?offset=150&limit=150",
"previous": null,
"results": [
{
"name": "bulbasaur",
"url": "http://localhost:5000/api/v2/pokemon/1/"
},
{
"name": "ivysaur",
"url": "http://localhost:5000/api/v2/pokemon/2/"
}
]
}
```
--------------------------------
### Elm UI View None Function Example
Source: https://elm.land/concepts/view
Defines a basic `none` function for the `View` module in Elm UI, providing an empty title, no attributes, and an `Element.none` element. This serves as a default or placeholder view.
```elm
none : View msg
none =
{ title = ""
, attributes = []
, element = Element.none
}
```
--------------------------------
### Compare Elm Page and Layout Function Signatures
Source: https://elm.land/concepts/layouts
Side-by-side comparison of the function signatures for Elm Land pages and layouts, highlighting the differences in parameters and return types, specifically the introduction of `Props` and `contentMsg` in layouts.
```elm
-- PAGES
page : Shared.Model -> Route () -> Page Model Msg
-- LAYOUTS
layout : Props -> Shared.Model -> Route () -> Layout () Model Msg contentMsg
```
--------------------------------
### Elm Land Project Directory Structure with Routes
Source: https://elm.land/guide/pages-and-routes
This snippet displays a typical directory structure for an Elm Land project that includes various pages and their corresponding route files. It provides context for how different route types (home, sign-in, settings, dynamic user/repo, and catch-all) are organized within the 'src/Pages' directory.
```txt
pages-and-routes/
├── README.md
├── elm.json
├── elm-land.json
└── src/
└── Pages/
├── Home_.elm
├── SignIn.elm
├── Settings/
│ └── Account.elm
├── User_.elm
└── User_/
├── Repo_.elm
└── Repo_/
└── Tree/
└── Branch_/
└── ALL_.elm
```
--------------------------------
### Define Catch-All Route Pattern for Code Explorer Page
Source: https://elm.land/guide/pages-and-routes
This snippet illustrates the URL pattern for a 'code explorer' page that needs to handle an unknown number of path segments after a specific base. It uses the '*' wildcard to signify a catch-all segment, allowing for flexible deep linking within a project's file structure.
```txt
/:owner/:repo/tree/:branch/*
```