From 8cd06f56bd86b9e311a7812e9e85616a40797a28 Mon Sep 17 00:00:00 2001 From: Matei Adriel Date: Thu, 28 Nov 2019 15:56:39 +0200 Subject: [PATCH 1/7] elm(todolist): chore: initial setup Signed-off-by: prescientmoon --- elm/todolist/.gitignore | 14 + elm/todolist/README.md | 937 ++++++++++++++++++++++++++++++ elm/todolist/elm.json | 26 + elm/todolist/public/favicon.ico | Bin 0 -> 103614 bytes elm/todolist/public/index.html | 22 + elm/todolist/public/logo.svg | 39 ++ elm/todolist/public/manifest.json | 15 + elm/todolist/src/Main.elm | 56 ++ elm/todolist/src/index.js | 12 + elm/todolist/src/main.css | 26 + elm/todolist/src/serviceWorker.js | 135 +++++ elm/todolist/tests/Tests.elm | 22 + 12 files changed, 1304 insertions(+) create mode 100644 elm/todolist/.gitignore create mode 100644 elm/todolist/README.md create mode 100644 elm/todolist/elm.json create mode 100644 elm/todolist/public/favicon.ico create mode 100644 elm/todolist/public/index.html create mode 100644 elm/todolist/public/logo.svg create mode 100644 elm/todolist/public/manifest.json create mode 100644 elm/todolist/src/Main.elm create mode 100644 elm/todolist/src/index.js create mode 100644 elm/todolist/src/main.css create mode 100644 elm/todolist/src/serviceWorker.js create mode 100644 elm/todolist/tests/Tests.elm diff --git a/elm/todolist/.gitignore b/elm/todolist/.gitignore new file mode 100644 index 0000000..e7e7f12 --- /dev/null +++ b/elm/todolist/.gitignore @@ -0,0 +1,14 @@ +# Distribution +build/ + +# elm-package generated files +elm-stuff + +# elm-repl generated files +repl-temp-* + +# Dependency directories +node_modules + +# Desktop Services Store on macOS +.DS_Store diff --git a/elm/todolist/README.md b/elm/todolist/README.md new file mode 100644 index 0000000..99db253 --- /dev/null +++ b/elm/todolist/README.md @@ -0,0 +1,937 @@ +# Elm App + +This project is bootstrapped with [Create Elm App](https://github.com/halfzebra/create-elm-app). + +Below you will find some information on how to perform basic tasks. +You can find the most recent version of this guide [here](https://github.com/halfzebra/create-elm-app/blob/master/template/README.md). + +## Table of Contents + +* [Sending feedback](#sending-feedback) +* [Folder structure](#folder-structure) +* [Installing Elm packages](#installing-elm-packages) +* [Installing JavaScript packages](#installing-javascript-packages) +* [Available scripts](#available-scripts) + * [elm-app build](#elm-app-build) + * [elm-app start](#elm-app-start) + * [elm-app install](#elm-app-install) + * [elm-app test](#elm-app-test) + * [elm-app eject](#elm-app-eject) + * [elm-app \](#elm-app-elm-platform-command) + * [package](#package) + * [repl](#repl) + * [make](#make) + * [reactor](#reactor) +* [Turning on/off Elm Debugger](#turning-onoff-elm-debugger) +* [Dead code elimination](#dead-code-elimination) +* [Changing the Page ``](#changing-the-page-title) +* [JavaScript Interop](#javascript-interop) +* [Adding a Stylesheet](#adding-a-stylesheet) +* [Post-Processing CSS](#post-processing-css) +* [Using elm-css](#using-elm-css) +* [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) +* [Adding Images and Fonts](#adding-images-and-fonts) +* [Using the `public` Folder](#using-the-public-folder) + * [Changing the HTML](#changing-the-html) + * [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) + * [When to Use the `public` Folder](#when-to-use-the-public-folder) +* [Using custom environment variables](#using-custom-environment-variables) +* [Setting up API Proxy](#setting-up-api-proxy) +* [Using HTTPS in Development](#using-https-in-development) +* [Running tests](#running-tests) + * [Continuous Integration](#continuous-integration) +* [Making a Progressive Web App](#making-a-progressive-web-app) + * [Opting Out of Caching](#opting-out-of-caching) + * [Offline-First Considerations](#offline-first-considerations) + * [Progressive Web App Metadata](#progressive-web-app-metadata) +* [Overriding Webpack Config](#overriding-webpack-config) +* [Configuring the Proxy Manually](#configuring-the-proxy-manually) +* [Deployment](#deployment) + * [Building for Relative Paths](#building-for-relative-paths) + * [Static Server](#static-server) + * [Netlify](#netlify) + * [GitHub Pages](#github-pages) +* [IDE setup for Hot Module Replacement](#ide-setup-for-hot-module-replacement) + +## Sending feedback + +You are very welcome with any [feedback](https://github.com/halfzebra/create-elm-app/issues) + +Feel free to join [@create-elm-app](https://elmlang.slack.com/messages/CBBET0YMR/) channel at Slack. + +## Installing Elm packages + +```sh +elm-app install <package-name> +``` + +Other `elm-package` commands are also [available].(#package) + +## Installing JavaScript packages + +To use JavaScript packages from npm, you'll need to add a `package.json`, install the dependencies, and you're ready to go. + +```sh +npm init -y # Add package.json +npm install --save-dev pouchdb-browser # Install library from npm +``` + +```js +// Use in your JS code +import PouchDB from 'pouchdb-browser'; +const db = new PouchDB('mydb'); +``` + +## Folder structure + +```sh +my-app/ +├── .gitignore +├── README.md +├── elm.json +├── elm-stuff +├── public +│ ├── favicon.ico +│ ├── index.html +│ ├── logo.svg +│ └── manifest.json +├── src +│ ├── Main.elm +│ ├── index.js +│ ├── main.css +│ └── serviceWorker.js +└── tests + └── Tests.elm +``` + +For the project to build, these files must exist with exact filenames: + +* `public/index.html` is the page template; +* `public/favicon.ico` is the icon you see in the browser tab; +* `src/index.js` is the JavaScript entry point. + +You can delete or rename the other files. + +You may create subdirectories inside src. + +## Available scripts + +In the project directory you can run: + +### `elm-app build` + +Builds the app for production to the `build` folder. + +The build is minified, and the filenames include the hashes. +Your app is ready to be deployed! + +### `elm-app start` + +Runs the app in the development mode. + +The browser should open automatically to [http://localhost:3000](http://localhost:3000). If the browser does not open, you can open it manually and visit the URL. + +The page will reload if you make edits. +You will also see any lint errors in the console. + +You may change the listening port number by using the `PORT` environment variable. For example type `PORT=8000 elm-app start ` into the terminal/bash to run it from: [http://localhost:8000/](http://localhost:8000/). + +You can prevent the browser from opening automatically, +```sh +elm-app start --no-browser +``` + +### `elm-app install` + +Alias for [`elm install`](http://guide.elm-lang.org/get_started.html#elm-install) + +Use it for installing Elm packages from [package.elm-lang.org](http://package.elm-lang.org/) + +### `elm-app test` + +Run tests with [node-test-runner](https://github.com/rtfeldman/node-test-runner/tree/master) + +You can make test runner watch project files by running: + +```sh +elm-app test --watch +``` + +### `elm-app eject` + +**Note: this is a one-way operation. Once you `eject`, you can’t go back!** + +If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. + +Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Elm Platform, etc.) right into your project, so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point, you’re on your own. + +You don’t have to use 'eject' The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However, we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. + +### `elm-app <elm-platform-command>` + +Create Elm App does not rely on the global installation of Elm Platform, but you still can use its local Elm Platform to access default command line tools: + +#### `repl` + +Alias for [`elm repl`](http://guide.elm-lang.org/get_started.html#elm-repl) + +#### `make` + +Alias for [`elm make`](http://guide.elm-lang.org/get_started.html#elm-make) + +#### `reactor` + +Alias for [`elm reactor`](http://guide.elm-lang.org/get_started.html#elm-reactor) + +## Turning on/off Elm Debugger + +By default, in production (`elm-app build`) the Debugger is turned off and in development mode (`elm-app start`) it's turned on. + +To turn on/off Elm Debugger explicitly, set `ELM_DEBUGGER` environment variable to `true` or `false` respectively. + +## Dead code elimination + +Create Elm App comes with an setup for dead code elimination which relies on the elm compiler flag `--optimize` and `uglifyjs`. + +## Changing the base path of the assets in the HTML + +By default, assets will be linked from the HTML to the root url. For example `/css/style.css`. + +If you deploy to a path that is not the root, you can change the `PUBLIC_URL` environment variable to properly reference your assets in the compiled assets. For example: `PUBLIC_URL=./ elm-app build`. + +## Changing the Page `<title>` + +You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “Elm App” to anything else. + +Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. + +If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API and JavaScript interoperation. The next section of this tutorial will explain it in more detail. + +## JavaScript Interop + +You can send and receive values to and from JavaScript using [ports](https://guide.elm-lang.org/interop/javascript.html#ports). + +In the following example we will use JavaScript to write a log in the console, every time the state changes in outrElm app. To make it work with files created by `create-elm-app` you need to modify +`src/index.js` file to look like this: + +```js +import { Elm } from './Main.elm'; + +const app = Elm.Main.init({ + node: document.getElementById('root') +}); + +app.ports.logger.subscribe(message => { + console.log('Port emitted a new message: ' + message); +}); +``` + +Please note the `logger` port in the above example, more about it later. + +First let's allow the Main module to use ports and in `Main.elm` file please prepend `port` to the module declaration: + +```elm +port module Main exposing (..) +``` + +Do you remember `logger` in JavaScript? Let's declare the port: + +```elm +port logger : String -> Cmd msg +``` + +and use it to call JavaScript in you update function. + +```elm +update : Msg -> Model -> ( Model, Cmd Msg ) +update msg model = + case msg of + Inc -> + ( { model | counter = model.counter + 1} + , logger ("Elm-count up " ++ (toString (model.counter + 1))) + ) + Dec -> + ( { model | counter = model.counter - 1} + , logger ("Elm-count down " ++ (toString (model.counter - 1)))) + NoOp -> + ( model, Cmd.none ) +``` + +Please note that for `Inc` and `Dec` operations `Cmd.none` was replaced with `logger` port call which sends a message string to the JavaScript side. + +## Adding a Stylesheet + +This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: + +### `main.css` + +```css +body { + padding: 20px; +} +``` + +### `index.js` + +```js +import './main.css'; // Tell Webpack to pick-up the styles from main.css +``` + +## Post-Processing CSS + +This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. + +For example, this: + +```css +.container { + display: flex; +} +``` + +becomes this: + +```css +.container { + display: -webkit-box; + display: -ms-flexbox; + display: flex; +} +``` + +In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. + +You can put all your CSS right into `src/main.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. + +## Using elm-css + +### Step 1: Install [elm-css](https://github.com/rtfeldman/elm-css) npm package + +```sh +npm install elm-css -g +``` + +### Step 2: Install Elm dependencies + +```sh +elm-app install rtfeldman/elm-css +elm-app install rtfeldman/elm-css-helpers +``` + +### Step 3: Create the stylesheet file + +Create an Elm file at `src/Stylesheets.elm` (The name of this file cannot be changed). + +```elm +port module Stylesheets exposing (main, CssClasses(..), CssIds(..), helpers) + +import Css exposing (..) +import Css.Elements exposing (body, li) +import Css.Namespace exposing (namespace) +import Css.File exposing (..) +import Html.CssHelpers exposing (withNamespace) + + +port files : CssFileStructure -> Cmd msg + + +cssFiles : CssFileStructure +cssFiles = + toFileStructure [ ( "src/style.css", Css.File.compile [ css ] ) ] + + +main : CssCompilerProgram +main = + Css.File.compiler files cssFiles + + +type CssClasses + = NavBar + + +type CssIds + = Page + + +appNamespace = + "App" + + +helpers = + withNamespace appNamespace + + +css = + (stylesheet << namespace appNamespace) + [ body + [ overflowX auto + , minWidth (px 1280) + ] + , id Page + [ backgroundColor (rgb 200 128 64) + , color (hex "CCFFFF") + , width (pct 100) + , height (pct 100) + , boxSizing borderBox + , padding (px 8) + , margin zero + ] + , class NavBar + [ margin zero + , padding zero + , children + [ li + [ (display inlineBlock) |> important + , color primaryAccentColor + ] + ] + ] + ] + + +primaryAccentColor = + hex "ccffaa" +``` + +### Step 4: Compiling the stylesheet + +To compile the CSS file, just run + +```sh +elm-css src/Stylesheets.elm +``` + +This will generate a file called `style.css` + +### Step 5: Import the compiled CSS file + +Add the following line to your `src/index.js`: + +```js +import './style.css'; +``` + +### Step 6: Using the stylesheet in your Elm code + +```elm +import Stylesheets exposing (helpers, CssIds(..), CssClasses(..)) + + +view model = + div [ helpers.id Page ] + [ div [ helpers.class [ NavBar ] ] + [ text "Your Elm App is working!" ] + ] +``` + +Please note that `Stylesheets.elm` exposes `helpers` record, which contains functions for creating id and class attributes. + +You can also destructure `helpers` to make your view more readable: + +```elm +{ id, class } = + helpers +``` + +## Adding a CSS Preprocessor (Sass, Less etc.) + +If you find CSS preprocessors valuable you can integrate one. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. + +First we need to create a `package.json` file, since create-elm-app is not shipping one at the moment. Walk through the normal `npm init` process. + +```sh +npm init +``` + +Second, let’s install the command-line interface for Sass: + +```sh +npm install --save node-sass-chokidar +``` + +Alternatively you may use `yarn`: + +```sh +yarn add node-sass-chokidar +``` + +Then in `package.json`, add the following lines to `scripts`: + +```diff + "scripts": { ++ "build-css": "node-sass-chokidar src/ -o src/", ++ "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", + ... + } +``` + +> Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. + +Now you can rename `src/main.css` to `src/main.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/main.css`. Since `src/index.js` still imports `src/main.css`, the styles become a part of your application. You can now edit `src/main.scss`, and `src/main.css` will be regenerated. + +To share variables between Sass files, you can use Sass imports. For example, `src/main.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. + +To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`. + +```json +{ + "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/", + "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive", +} +``` + +This will allow you to do imports like + +```scss +@import 'styles/_colors.scss'; // assuming a styles directory under src/ +@import 'nprogress/nprogress'; // importing a css file from the nprogress node module +``` + +At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. + +**Why `node-sass-chokidar`?** + +`node-sass` has been reported as having the following issues: + +* `node-sass --watch` has been reported to have _performance issues_ in certain conditions when used in a virtual machine or with docker. + +* Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939) + +* `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891) + +`node-sass-chokidar` is used here as it addresses these issues. + +## Adding Images and Fonts + +With Webpack, using static assets like images and fonts works similarly to CSS. + +By requiring an image in JavaScript code, you tell Webpack to add a file to the build of your application. The variable will contain a unique path to the said file. + +Here is an example: + +```js +import logoPath from './logo.svg'; // Tell Webpack this JS file uses this image +import { Main } from './Main.elm'; + +Main.embed( + document.getElementById('root'), + logoPath // Pass image path as a flag for Html.programWithFlags +); +``` + +Later on, you can use the image path in your view for displaying it in the DOM. + +```elm +view : Model -> Html Msg +view model = + div [] + [ img [ src model.logo ] [] + , div [] [ text model.message ] + ] +``` + +## Using the `public` Folder + +### Changing the HTML + +The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). +The `<script>` tag with the compiled code will be added to it automatically during the build process. + +### Adding Assets Outside of the Module System + +You can also add other assets to the `public` folder. + +Note that we normally encourage you to `import` assets in JavaScript files instead. +For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). +This mechanism provides a few benefits: + +* Scripts and stylesheets get minified and bundled together to avoid extra network requests. +* Missing files cause compilation errors instead of 404 errors for your users. +* Result filenames include content hashes, so you don’t need to worry about browsers caching their old versions. + +However, there is a **escape hatch** that you can use to add an asset outside of the module system. + +If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead, it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. + +Inside `index.html`, you can use it like this: + +```html +<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> +``` + +Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. + +When you run `elm-app build`, Create Elm App will substitute `%PUBLIC_URL%` with a correct absolute path, so your project works even if you use client-side routing or host it at a non-root URL. + +In Elm code, you can use `%PUBLIC_URL%` for similar purposes: + +```elm +{- Note: this is an escape hatch and should be used sparingly! + Normally we recommend using `import` and `Html.programWithFlags` for getting + asset URLs as described in “Adding Images and Fonts” above this section. +-} +img [ src "%PUBLIC_URL%/logo.svg" ] [] +``` + +In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: + +```js +const logo = `<img src=${process.env.PUBLIC_URL + '/img/logo.svg'} />`; +``` + +Keep in mind the downsides of this approach: + +* None of the files in `public` folder get post-processed or minified. +* Missing files will not be called at compilation time, and will cause 404 errors for your users. +* Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. + +### When to Use the `public` Folder + +Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. +The `public` folder is used as a workaround for some less common cases: + +* You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). +* You have thousands of images and need to dynamically reference their paths. +* You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. +* Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. + +Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. + +## Using custom environment variables + +In your JavaScript code you have access to variables declared in your +environment, like an API key set in an `.env`-file or via your shell. They are +available on the `process.env`-object and will be injected during build time. + +Besides the `NODE_ENV` variable you can access all variables prefixed with +`ELM_APP_`: + +```bash +# .env +ELM_APP_API_KEY="secret-key" +``` + +Alternatively, you can set them on your shell before calling the start- or +build-script, e.g.: + +```bash +ELM_APP_API_KEY="secret-key" elm-app start +``` + +Both ways can be mixed, but variables set on your shell prior to calling one of +the scripts will take precedence over those declared in an `.env`-file. + +Passing the variables to your Elm-code can be done via `flags`: + +```javascript +// index.js +import { Main } from './Main.elm'; + +Main.fullscreen({ + environment: process.env.NODE_ENV, + apiKey: process.env.ELM_APP_API_KEY +}); +``` + +```elm +-- Main.elm +type alias Flags = { apiKey : String, environment : String } + +init : Flags -> ( Model, Cmd Msg ) +init flags = + ... + +main = + programWithFlags { init = init, ... } +``` + +Be aware that you cannot override `NODE_ENV` manually. See +[this list from the `dotenv`-library](https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use) +for a list of files you can use to declare environment variables. + +**Note: Changes to your `.env` are only picked up on `elm-app start`. This means that you have to restart your server for your .env file changes to be picked up!** + + +## Setting up API Proxy + +To forward the API ( REST ) calls to backend server, add a proxy to the `elmapp.config.js` in the top level json object. + +```js +module.exports = { + ... + proxy: "http://localhost:1313", + ... +} +``` + +Make sure the XHR requests set the `Content-type: application/json` and `Accept: application/json`. +The development server has heuristics, to handle its own flow, which may interfere with proxying of +other html and javascript content types. + +```sh + curl -X GET -H "Content-type: application/json" -H "Accept: application/json" http://localhost:3000/api/list +``` + +## Using HTTPS in Development + +If you need to serve the development server over HTTPS, set the `HTTPS` environment variable to `true` before you start development server with `elm-app start`. + +Note that the server will use a self-signed certificate, so you will most likely have to add an exception to accept it in your browser. + +## Running Tests + +Create Elm App uses [elm-test](https://github.com/rtfeldman/node-test-runner) as its test runner. + +### Continuous Integration + +#### Travis CI + +1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page. +2. Add a `.travis.yml` file to your git repository. + +```yaml +language: node_js + +sudo: required + +node_js: + - '7' + +install: + - npm i create-elm-app -g + +script: elm-app test +``` + +1. Trigger your first build with a git push. +1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed. + +## Making a Progressive Web App + +By default, the production build is a fully functional, offline-first +[Progressive Web App](https://developers.google.com/web/progressive-web-apps/). + +Progressive Web Apps are faster and more reliable than traditional web pages, and provide an engaging mobile experience: + +* All static site assets are cached so that your page loads fast on subsequent visits, regardless of network connectivity (such as 2G or 3G). Updates are downloaded in the background. +* Your app will work regardless of network state, even if offline. This means your users will be able to use your app at 10,000 feet and on the Subway. +* On mobile devices, your app can be added directly to the user's home screen, app icon and all. You can also re-engage users using web **push notifications**. This eliminates the need for the app store. + +The [`workbox-webpack-plugin`](https://www.npmjs.com/package/workbox-webpack-plugin) +is integrated into production configuration, +and it will take care of generating a service worker file that will automatically +precache all of your local assets and keep them up to date as you deploy updates. +The service worker will use a [cache-first strategy](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network) +for handling all requests for local assets, including the initial HTML, ensuring +that your web app is reliably fast, even on a slow or unreliable network. + +### Opting Out of Caching + +If you would prefer not to enable service workers prior to your initial +production deployment, then remove the call to `serviceWorkerRegistration.register()` +from [`src/index.js`](src/index.js). + +If you had previously enabled service workers in your production deployment and +have decided that you would like to disable them for all your existing users, +you can swap out the call to `serviceWorkerRegistration.register()` in +[`src/index.js`](src/index.js) with a call to `serviceWorkerRegistration.unregister()`. +After the user visits a page that has `serviceWorkerRegistration.unregister()`, +the service worker will be uninstalled. Note that depending on how `/service-worker.js` is served, +it may take up to 24 hours for the cache to be invalidated. + +### Offline-First Considerations + +1. Service workers [require HTTPS](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers#you_need_https), although to facilitate local testing, that policy [does not apply to `localhost`](http://stackoverflow.com/questions/34160509/options-for-testing-service-workers-via-http/34161385#34161385). If your production web server does not support HTTPS, then the service worker registration will fail, but the rest of your web app will remain functional. + +1. Service workers are [not currently supported](https://jakearchibald.github.io/isserviceworkerready/) in all web browsers. Service worker registration [won't be attempted](src/serviceWorker.js) on browsers that lack support. + +1. The service worker is only enabled in the [production environment](#deployment), e.g. the output of `npm run build`. It's recommended that you do not enable an offline-first service worker in a development environment, as it can lead to frustration when previously cached assets are used and do not include the latest changes you've made locally. + +1. If you _need_ to test your offline-first service worker locally, build the application (using `npm run build`) and run a simple http server from your build directory. After running the build script, `create-elm-app` will give instructions for one way to test your production build locally and the [deployment instructions](#deployment) have instructions for using other methods. _Be sure to always use an incognito window to avoid complications with your browser cache._ + +1. If possible, configure your production environment to serve the generated `service-worker.js` [with HTTP caching disabled](http://stackoverflow.com/questions/38843970/service-worker-javascript-update-frequency-every-24-hours). If that's not possible—[GitHub Pages](#github-pages), for instance, does not allow you to change the default 10 minute HTTP cache lifetime—then be aware that if you visit your production site, and then revisit again before `service-worker.js` has expired from your HTTP cache, you'll continue to get the previously cached assets from the service worker. If you have an immediate need to view your updated production deployment, performing a shift-refresh will temporarily disable the service worker and retrieve all assets from the network. + +1. Users aren't always familiar with offline-first web apps. It can be useful to [let the user know](https://developers.google.com/web/fundamentals/instant-and-offline/offline-ux#inform_the_user_when_the_app_is_ready_for_offline_consumption) when the service worker has finished populating your caches (showing a "This web app works offline!" message) and also let them know when the service worker has fetched the latest updates that will be available the next time they load the page (showing a "New content is available; please refresh." message). Showing this messages is currently left as an exercise to the developer, but as a starting point, you can make use of the logic included in [`src/serviceWorker.js`](src/serviceWorker.js), which demonstrates which service worker lifecycle events to listen for to detect each scenario, and which as a default, just logs appropriate messages to the JavaScript console. + +1. By default, the generated service worker file will not intercept or cache any cross-origin traffic, like HTTP [API requests](#integrating-with-an-api-backend), images, or embeds loaded from a different domain. If you would like to use a runtime caching strategy for those requests, you can [`eject`](#npm-run-eject) and then configure the [`runtimeCaching`](https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin) option in the `WorkboxPlugin` section of [`webpack.config.prod.js`](../config/webpack.config.prod.js). + +### Progressive Web App Metadata + +The default configuration includes a web app manifest located at +[`public/manifest.json`](public/manifest.json), that you can customize with +details specific to your web application. + +When a user adds a web app to their homescreen using Chrome or Firefox on +Android, the metadata in [`manifest.json`](public/manifest.json) determines what +icons, names, and branding colors to use when the web app is displayed. +[The Web App Manifest guide](https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/) +provides more context about what each field means, and how your customizations +will affect your users' experience. + +## Overriding Webpack Config + +Create Elm App allows Webpack config overrides without [ejecting](#elm-app-eject). + +Create a CommonJS module with the name `elmapp.config.js` in the root directory of your project. The module has to export an object with `"configureWebpack"` property as shown in the example. + +```js +module.exports = { + configureWebpack: (config, env) => { + // Manipulate the config object and return it. + return config; + } +} +``` + +Mutate the configuration directly or use [webpack-merge](https://www.npmjs.com/package/webpack-merge) to override the config. + +`env` variable will help you distinguish `"development"` from `"production"` for environment-specific overrides. + +## Configuring the Proxy Manually + +If the `proxy` option is not flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware. + +You can use this feature in conjunction with the `proxy` property in `elmapp.config.js`, but it is recommended you consolidate all of your logic into `setupProxy` property`. + +First, install http-proxy-middleware using npm: + +``` +$ npm init --yes +$ npm install http-proxy-middleware --save +``` + +Next, create `elmapp.config.js` in the root of your project and place the following contents in it: + +```js +const proxy = require('http-proxy-middleware'); + +module.exports = { + setupProxy: function(app) { + // ... + } +}; +``` + +You can now register proxies as you wish! Here's an example using the above http-proxy-middleware: + +```js +const proxy = require('http-proxy-middleware'); + +module.exports = { + setupProxy: function(app) { + app.use(proxy('/api', { target: 'http://localhost:5000/' })); + } +}; +``` + +## Deployment + +`elm-app build` creates a `build` directory with a production build of your app. Set up your favourite HTTP server so that a visitor to your site is served `index.html`, and requests to static paths like `/static/js/main.<hash>.js` are served with the contents of the `/static/js/main.<hash>.js` file. + +### Building for Relative Paths + +By default, Create Elm App produces a build assuming your app is hosted at the server root. + +To override this, specify the `homepage` in your `elmapp.config.js`, for example: + +```js +module.exports = { + homepage: "http://mywebsite.com/relativepath" +} +``` + +This will let Create Elm App correctly infer the root path to use in the generated HTML file. + +### Static Server + +For environments using [Node](https://nodejs.org/), the easiest way to handle this would be to install [serve](https://github.com/zeit/serve) and let it handle the rest: + +```sh +npm install -g serve +serve -s build +``` + +The last command shown above will serve your static site on the port **5000**. Like many of [serve](https://github.com/zeit/serve)’s internal settings, the port can be adjusted using the `-p` or `--port` flags. + +Run this command to get a full list of the options available: + +```sh +serve -h +``` + +### Netlify + +#### Step 1: Create a `package.json` file +#### Step 2: `npm install --save-dev create-elm-app` +Since netlify runs the build step on their server we need to install create-elm-app. +#### Step 3: Add a build script to the `package.json` file +``` +"scripts": { + "build": "elm-app build", + ... +} +``` +#### Step 4: Add a netlify.toml file in the repo's root +``` +[[redirects]] + from = "/*" + to = "/index.html" + status = 200 +``` +#### Step 5: Go to the netlify settings and set the publish directory to `build` and the build command to `npm run build` +This step is important to make sure netlify uses the correct build command. + +### GitHub Pages + +#### Step 1: Add `homepage` to `elmapp.config.js` + +**The step below is important!** + +**If you skip it, your app will not deploy correctly.** + +Open your `elmapp.config.js` and add a `homepage` field: + +```js +module.exports = { + homepage: "https://myusername.github.io/my-app", +} +``` + +Create Elm App uses the `homepage` field to determine the root URL in the built HTML file. + +#### Step 2: Build the static site + +```sh +elm-app build +``` + +#### Step 3: Deploy the site by running `gh-pages -d build` + +We will use [gh-pages](https://www.npmjs.com/package/gh-pages) to upload the files from the `build` directory to GitHub. If you haven't already installed it, do so now (`npm install -g gh-pages`) + +Now run: + +```sh +gh-pages -d build +``` + +#### Step 4: Ensure your project’s settings use `gh-pages` + +Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch: + +![GH Pages branch](https://i.imgur.com/HUjEr9l.png) + +#### Step 5: Optionally, configure the domain + +You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder. + +#### Notes on client-side routing + +GitHub Pages doesn’t support routers that use the HTML5 `pushState` history API under the hood (for example, React Router using `browserHistory`). This is because when there is a fresh page load for a url like `http://user.github.io/todomvc/todos/42`, where `/todos/42` is a frontend route, the GitHub Pages server returns 404 because it knows nothing of `/todos/42`. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions: + +* You could switch from using HTML5 history API to routing with hashes. +* Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your `index.html` page with a special redirect parameter. You would need to add a `404.html` file with the redirection code to the `build` folder before deploying your project, and you’ll need to add code handling the redirect parameter to `index.html`. You can find a detailed explanation of this technique [in this guide](https://github.com/rafrex/spa-github-pages). + +## IDE setup for Hot Module Replacement + +Remember to disable [safe write](https://webpack.js.org/guides/development/#adjusting-your-text-editor) if you are using VIM or IntelliJ IDE, such as WebStorm. diff --git a/elm/todolist/elm.json b/elm/todolist/elm.json new file mode 100644 index 0000000..5e90087 --- /dev/null +++ b/elm/todolist/elm.json @@ -0,0 +1,26 @@ +{ + "type": "application", + "source-directories": ["src"], + "elm-version": "0.19.1", + "dependencies": { + "direct": { + "elm/browser": "1.0.1", + "elm/core": "1.0.2", + "elm/html": "1.0.0" + }, + "indirect": { + "elm/json": "1.1.2", + "elm/time": "1.0.0", + "elm/url": "1.0.0", + "elm/virtual-dom": "1.0.2" + } + }, + "test-dependencies": { + "direct": { + "elm-explorations/test": "1.0.0" + }, + "indirect": { + "elm/random": "1.0.0" + } + } +} diff --git a/elm/todolist/public/favicon.ico b/elm/todolist/public/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..d7057bd07e970a1212f6a8a048c2343026118353 GIT binary patch literal 103614 zcmeHQ30M<H8{UK{QL7MpfQk_DsK;N$svKTK1;kp9-<DbsB`Wo-iq^A53Ds7t2|+7f zzg4OridU_IXC<}@R?(_0hj`IaFDwEcl~zptZ#Fxyf!r5KNS<zIkD2-2_j|vYot+&Q zf?yDh3G`zSTw=5nK}>;tfk1xTnav<F;2e)f9S<gmTP_U3%S(Q|t0O@)4ug_h>e!he z_Qx;?XGl?f(^v%YK>~wVHG1UG=1p5Sg{qqm3l12AuA+^NOoz|g1vZ^rh6N0IfAN;m zo5O`;a~atcw_7D0{BPR+wAI~beYAQ0<Zh*xX21Ju!f#2BU8lK8vOY}T$#XbAGk`bZ z;fWC`iA|XU-z#kNQ(pI08;2E+NOwAMxS303=Vv|Vk93Lp-6`jWOm^$DOF!JJc=_?@ z$Nn<es=LoGR!wvd>bNy}YQ@OVn-PDz29$}O`HZ|VQ}}V>keOMj>vPVXicDT|s(WME zyP1ytpZ$Gg(YR|XuOEG-@1&>yX3M01lpHLRK6p2A@{XaY>(3YDcX+FOey_!OK155- zIVR`aRURWDj`v0!Z(-vWf&kX{Jl6MPx=`1G?hwHN+-C6KkZ$?2j;EG<`)qamoStug z79Gxx{VwcO`M;xDh<;dbp{i^4-#v~!h}#?5ZhGOb7mF?@toi5Jx#J_8J{S<pdYi{u z>(k-q;Jed31)-eS<mTVJNM!S82XI4&43ORE%=~`gk)J+m*E@haY{-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V6N*_lNUTqaB%z_f>ifN2bZ$K(@SmKWj7b|u)(uMjM5V}i+ZfSCyfIXl6GtSl(P zhN8|;1sAH~L6s5*2}6cHIOIUE2)GRYcZUCS;r~4NzW}O7|DFu&!jbxUik)l6j{sf| zbm2zjeK7yKZ6hGgic{A{4A-%a2aEP?84mq!F&U?kp?~U7M+sSWXW5@nzNVk4siQ;< zmy+cN)&@bj>c2&z&`&`fY3oTY%IYW)otZb%r(kUqlutvp73`z&D>;S@{d3Q{3GV_1 zdL1Qe&qfW0aal2nL+|`G^I&|nM`?L^J$GnzP-R7b(qdTZoeOoqJ6Q$%7=t`5*|92o z<chQNM?tv<w6ZnrJ6F6!W%)^A4+h6>8PWFi4?!4r?K=FfiM~`?9?Fi0CjERHFcy1A zGKSU0;CC%P{=#9txK4S+viP0%?RKXR0S-A2-)qn(rSlVz&b7*yP<C^{F08qrZOP?% z+#fUiVNKP%ob-unaE#E(mxQgGJ4)TVR^IhhZm<SvEiOy5Uos(K&bxq*u2GGjL36(X z;a3+AM|@2$OO?lE@6`4$K1O9>oUyKUS#<p2H}gh9KUaeD)=vB8eH9ISzg1Qior9hR tx)kUqpmTDDP6~P=g4F>!uEEf6#KI<keIA_S%CC8p%li~KMF<20@qbEsl)nG~ literal 0 HcmV?d00001 diff --git a/elm/todolist/public/index.html b/elm/todolist/public/index.html new file mode 100644 index 0000000..40cb71b --- /dev/null +++ b/elm/todolist/public/index.html @@ -0,0 +1,22 @@ +<!DOCTYPE html> +<html lang="en"> +<head> + <meta charset="utf-8"> + <meta http-equiv="x-ua-compatible" content="ie=edge"> + <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> + <meta name="theme-color" content="#000000"> + <!-- + manifest.json provides metadata used when your web app is added to the + homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/ + --> + <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> + <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> + <title>Elm App + + + +
+ + diff --git a/elm/todolist/public/logo.svg b/elm/todolist/public/logo.svg new file mode 100644 index 0000000..4321d4d --- /dev/null +++ b/elm/todolist/public/logo.svg @@ -0,0 +1,39 @@ + + + + + + + + + + + + + + + + + + + + diff --git a/elm/todolist/public/manifest.json b/elm/todolist/public/manifest.json new file mode 100644 index 0000000..9b7dc41 --- /dev/null +++ b/elm/todolist/public/manifest.json @@ -0,0 +1,15 @@ +{ + "short_name": "Elm App", + "name": "Create Elm App Sample", + "icons": [ + { + "src": "favicon.ico", + "sizes": "192x192", + "type": "image/png" + } + ], + "start_url": "./index.html", + "display": "standalone", + "theme_color": "#000000", + "background_color": "#ffffff" +} diff --git a/elm/todolist/src/Main.elm b/elm/todolist/src/Main.elm new file mode 100644 index 0000000..c3ab483 --- /dev/null +++ b/elm/todolist/src/Main.elm @@ -0,0 +1,56 @@ +module Main exposing (..) + +import Browser +import Html exposing (Html, text, div, h1, img) +import Html.Attributes exposing (src) + + +---- MODEL ---- + + +type alias Model = + {} + + +init : ( Model, Cmd Msg ) +init = + ( {}, Cmd.none ) + + + +---- UPDATE ---- + + +type Msg + = NoOp + + +update : Msg -> Model -> ( Model, Cmd Msg ) +update msg model = + ( model, Cmd.none ) + + + +---- VIEW ---- + + +view : Model -> Html Msg +view model = + div [] + [ img [ src "/logo.svg" ] [] + , h1 [] [ text "Your Elm App is working!" ] + ] + + + +---- PROGRAM ---- + + +main : Program () Model Msg +main = + Browser.element + { view = view + , init = \_ -> init + , update = update + , subscriptions = always Sub.none + } diff --git a/elm/todolist/src/index.js b/elm/todolist/src/index.js new file mode 100644 index 0000000..c9bbd20 --- /dev/null +++ b/elm/todolist/src/index.js @@ -0,0 +1,12 @@ +import './main.css'; +import { Elm } from './Main.elm'; +import * as serviceWorker from './serviceWorker'; + +Elm.Main.init({ + node: document.getElementById('root') +}); + +// If you want your app to work offline and load faster, you can change +// unregister() to register() below. Note this comes with some pitfalls. +// Learn more about service workers: https://bit.ly/CRA-PWA +serviceWorker.unregister(); diff --git a/elm/todolist/src/main.css b/elm/todolist/src/main.css new file mode 100644 index 0000000..d9f0b64 --- /dev/null +++ b/elm/todolist/src/main.css @@ -0,0 +1,26 @@ +/* + elm-hot creates an additional div wrapper around the app to make HMR possible. + This could break styling in development mode if you are using Elm UI. + + More context in the issue: + https://github.com/halfzebra/create-elm-app/issues/320 +*/ +[data-elm-hot="true"] { + height: inherit; +} + +body { + font-family: 'Source Sans Pro', 'Trebuchet MS', 'Lucida Grande', 'Bitstream Vera Sans', 'Helvetica Neue', sans-serif; + margin: 0; + text-align: center; + color: #293c4b; +} + +h1 { + font-size: 30px; +} + +img { + margin: 20px 0; + max-width: 200px; +} diff --git a/elm/todolist/src/serviceWorker.js b/elm/todolist/src/serviceWorker.js new file mode 100644 index 0000000..f8c7e50 --- /dev/null +++ b/elm/todolist/src/serviceWorker.js @@ -0,0 +1,135 @@ +// This optional code is used to register a service worker. +// register() is not called by default. + +// This lets the app load faster on subsequent visits in production, and gives +// it offline capabilities. However, it also means that developers (and users) +// will only see deployed updates on subsequent visits to a page, after all the +// existing tabs open on the page have been closed, since previously cached +// resources are updated in the background. + +// To learn more about the benefits of this model and instructions on how to +// opt-in, read https://bit.ly/CRA-PWA + +const isLocalhost = Boolean( + window.location.hostname === 'localhost' || + // [::1] is the IPv6 localhost address. + window.location.hostname === '[::1]' || + // 127.0.0.1/8 is considered localhost for IPv4. + window.location.hostname.match( + /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/ + ) +); + +export function register(config) { + if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) { + // The URL constructor is available in all browsers that support SW. + const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href); + if (publicUrl.origin !== window.location.origin) { + // Our service worker won't work if PUBLIC_URL is on a different origin + // from what our page is served on. This might happen if a CDN is used to + // serve assets; see https://github.com/facebook/create-react-app/issues/2374 + return; + } + + window.addEventListener('load', () => { + const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`; + + if (isLocalhost) { + // This is running on localhost. Let's check if a service worker still exists or not. + checkValidServiceWorker(swUrl, config); + + // Add some additional logging to localhost, pointing developers to the + // service worker/PWA documentation. + navigator.serviceWorker.ready.then(() => { + console.log( + 'This web app is being served cache-first by a service ' + + 'worker. To learn more, visit https://bit.ly/CRA-PWA' + ); + }); + } else { + // Is not localhost. Just register service worker + registerValidSW(swUrl, config); + } + }); + } +} + +function registerValidSW(swUrl, config) { + navigator.serviceWorker + .register(swUrl) + .then(registration => { + registration.onupdatefound = () => { + const installingWorker = registration.installing; + if (installingWorker == null) { + return; + } + installingWorker.onstatechange = () => { + if (installingWorker.state === 'installed') { + if (navigator.serviceWorker.controller) { + // At this point, the updated precached content has been fetched, + // but the previous service worker will still serve the older + // content until all client tabs are closed. + console.log( + 'New content is available and will be used when all ' + + 'tabs for this page are closed. See https://bit.ly/CRA-PWA.' + ); + + // Execute callback + if (config && config.onUpdate) { + config.onUpdate(registration); + } + } else { + // At this point, everything has been precached. + // It's the perfect time to display a + // "Content is cached for offline use." message. + console.log('Content is cached for offline use.'); + + // Execute callback + if (config && config.onSuccess) { + config.onSuccess(registration); + } + } + } + }; + }; + }) + .catch(error => { + console.error('Error during service worker registration:', error); + }); +} + +function checkValidServiceWorker(swUrl, config) { + // Check if the service worker can be found. If it can't reload the page. + fetch(swUrl) + .then(response => { + // Ensure service worker exists, and that we really are getting a JS file. + const contentType = response.headers.get('content-type'); + if ( + response.status === 404 || + (contentType != null && contentType.indexOf('javascript') === -1) + ) { + // No service worker found. Probably a different app. Reload the page. + navigator.serviceWorker.ready.then(registration => { + registration.unregister().then(() => { + window.location.reload(); + }); + }); + } else { + // Service worker found. Proceed as normal. + registerValidSW(swUrl, config); + } + }) + .catch(() => { + console.log( + 'No internet connection found. App is running in offline mode.' + ); + }); +} + +export function unregister() { + if ('serviceWorker' in navigator) { + navigator.serviceWorker.ready.then(registration => { + registration.unregister(); + }); + } +} diff --git a/elm/todolist/tests/Tests.elm b/elm/todolist/tests/Tests.elm new file mode 100644 index 0000000..3cf3499 --- /dev/null +++ b/elm/todolist/tests/Tests.elm @@ -0,0 +1,22 @@ +module Tests exposing (..) + +import Test exposing (..) +import Expect + + +-- Check out https://package.elm-lang.org/packages/elm-explorations/test/latest to learn more about testing in Elm! + + +all : Test +all = + describe "A Test Suite" + [ test "Addition" <| + \_ -> + Expect.equal 10 (3 + 7) + , test "String.left" <| + \_ -> + Expect.equal "a" (String.left 1 "abcdefg") + , test "This test should fail" <| + \_ -> + Expect.fail "failed as expected!" + ] From 5278cf694d261da24093c6e00f6e94b883c7a726 Mon Sep 17 00:00:00 2001 From: Matei Adriel Date: Thu, 28 Nov 2019 16:57:45 +0200 Subject: [PATCH 2/7] elm(todolist): feat: basic todo operations Signed-off-by: prescientmoon --- elm/todolist/elm-analyse.json | 6 ++ elm/todolist/src/Main.elm | 141 ++++++++++++++++++++++++++++++---- elm/todolist/src/main.css | 97 +++++++++++++++++++++-- 3 files changed, 223 insertions(+), 21 deletions(-) create mode 100644 elm/todolist/elm-analyse.json diff --git a/elm/todolist/elm-analyse.json b/elm/todolist/elm-analyse.json new file mode 100644 index 0000000..2e716e1 --- /dev/null +++ b/elm/todolist/elm-analyse.json @@ -0,0 +1,6 @@ +{ + "checks": { + "ExposeAll": false, + "ImportAll": false + } +} diff --git a/elm/todolist/src/Main.elm b/elm/todolist/src/Main.elm index c3ab483..8413e38 100644 --- a/elm/todolist/src/Main.elm +++ b/elm/todolist/src/Main.elm @@ -1,20 +1,36 @@ module Main exposing (..) import Browser -import Html exposing (Html, text, div, h1, img) -import Html.Attributes exposing (src) +import Html exposing (..) +import Html.Attributes exposing (..) +import Html.Events exposing (..) + + + +-- HELPER TYPES + + +type alias Todo = + { done : Bool + , text : String + , id : Int + } + ---- MODEL ---- type alias Model = - {} + { todos : List Todo + , lastId : Int + , nextTodoText : String + } -init : ( Model, Cmd Msg ) +init : Model init = - ( {}, Cmd.none ) + Model [] 0 "" @@ -22,12 +38,48 @@ init = type Msg - = NoOp + = AddTodo + | DeleteTodo Int + | ToggleTodoCompletion Int + | SetNextTodoText String -update : Msg -> Model -> ( Model, Cmd Msg ) -update msg model = - ( model, Cmd.none ) +update : Msg -> Model -> Model +update message model = + case message of + AddTodo -> + if model.nextTodoText == "" then + model + + else + let + id = + model.lastId + 1 + + text = + model.nextTodoText + in + { model | lastId = id, todos = Todo False text id :: model.todos } + + DeleteTodo id -> + { model | todos = List.filter ((/=) id << .id) model.todos } + + ToggleTodoCompletion id -> + { model + | todos = + List.map + (\todo -> + if todo.id == id then + { todo | done = not todo.done } + + else + todo + ) + model.todos + } + + SetNextTodoText text -> + { model | nextTodoText = text } @@ -36,9 +88,69 @@ update msg model = view : Model -> Html Msg view model = - div [] - [ img [ src "/logo.svg" ] [] - , h1 [] [ text "Your Elm App is working!" ] + div [ class "container" ] + [ header model + , div [ class "todos" ] <| + List.map + todoView + model.todos + ] + + + +-- HEADER + + +header : Model -> Html Msg +header _ = + div [ class "header" ] + [ button + [ class "btn" + , onClick AddTodo + ] + [ text "add todo" ] + , input + [ placeholder "todo text" + , onInput SetNextTodoText + , class "todoTextInput" + ] + [] + ] + + + +-- _TODO VIEW + + +todoClasses : Todo -> String +todoClasses todo = + "todo" + ++ (if todo.done then + " completed" + + else + "" + ) + + +todoView : Todo -> Html Msg +todoView todo = + div [ class <| todoClasses todo ] + [ div [ class "todoCompleted" ] + [ input + [ checked todo.done + , type_ "checkbox" + , class "todoCheckbox" + , onCheck <| \_ -> ToggleTodoCompletion todo.id + ] + [] + ] + , div [ class "todoText" ] [ text todo.text ] + , button + [ class "btn" + , onClick <| DeleteTodo todo.id + ] + [ text "Delete todo" ] ] @@ -48,9 +160,8 @@ view model = main : Program () Model Msg main = - Browser.element + Browser.sandbox { view = view - , init = \_ -> init + , init = init , update = update - , subscriptions = always Sub.none } diff --git a/elm/todolist/src/main.css b/elm/todolist/src/main.css index d9f0b64..206b7b0 100644 --- a/elm/todolist/src/main.css +++ b/elm/todolist/src/main.css @@ -9,18 +9,103 @@ height: inherit; } +:root { + --secondary: #009fb7; + --primary: #1a213b; + --on-secondary: #eff1f4; + --disabled: #555555; +} + body { - font-family: 'Source Sans Pro', 'Trebuchet MS', 'Lucida Grande', 'Bitstream Vera Sans', 'Helvetica Neue', sans-serif; + font-family: "Source Sans Pro", "Trebuchet MS", "Lucida Grande", + "Bitstream Vera Sans", "Helvetica Neue", sans-serif; margin: 0; - text-align: center; - color: #293c4b; + background: var(--primary); + + color: var(--on-secondary); } h1 { font-size: 30px; } -img { - margin: 20px 0; - max-width: 200px; +.header { + display: flex; +} + +.btn { + background-color: var(--secondary); + color: var(--on-secondary); + padding: 1rem; + margin: 1rem; + border: none; +} + +input { + outline: none; +} + +.todos { + display: flex; + flex-direction: column; + min-height: 67vh; + border: 1px solid var(--secondary); +} + +.todo { + transition: filter 0.5s; + background: var(--primary); + display: flex; +} + +.todo:hover { + filter: brightness(1.4); +} + +.todo.completed { + color: var(--disabled); + + text-decoration: line-through; +} + +.todo.completed > .btn { + color: var(--disabled); +} + +.todo > * { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +.todoText { + justify-content: flex-start; + flex-direction: row; + flex-grow: 1; +} + +.todoCompleted { + margin: 1rem; +} + +.todoTextInput { + background: var(--primary); + border: 1px var(--secondary) solid; + margin: 1rem; + padding: 2px; + box-sizing: border-box; + color: var(--on-secondary); + font-size: 1.5rem; + transition: filter 0.5s; +} + +.todoTextInput:focus { + filter: brightness(1.4); +} + +.todoCheckbox { + width: 1rem; + height: 1rem; + background: var(--secondary); } From 9ab4e2d0793a2f97016dbf1c25e942df9f141138 Mon Sep 17 00:00:00 2001 From: Matei Adriel Date: Thu, 28 Nov 2019 17:05:32 +0200 Subject: [PATCH 3/7] elm(todolist): ci: added a basic github actions config Signed-off-by: prescientmoon --- elm/todolist/.github/workflows/elm.yml | 30 + elm/todolist/README.md | 938 +------------------------ elm/todolist/tests/Tests.elm | 22 - 3 files changed, 32 insertions(+), 958 deletions(-) create mode 100644 elm/todolist/.github/workflows/elm.yml delete mode 100644 elm/todolist/tests/Tests.elm diff --git a/elm/todolist/.github/workflows/elm.yml b/elm/todolist/.github/workflows/elm.yml new file mode 100644 index 0000000..b020b75 --- /dev/null +++ b/elm/todolist/.github/workflows/elm.yml @@ -0,0 +1,30 @@ +name: Elm + +on: [push] + +jobs: + deploy: + runs-on: ubuntu-latest + + strategy: + matrix: + node-version: [12.x] + + steps: + - name: Checkout + uses: actions/checkout@v1 + - name: Use node 12 + uses: actions/setup-node@v1 + + with: + node-version: ${{ matrix.node-version }} + - run: npm i -g elm create-elm-app + - run: elm install + - run: elm-app build + - name: Deploy to github pages + uses: JamesIves/github-pages-deploy-action@master + env: + ACCESS_TOKEN: ${{ secrets.ACCESS_TOKEN }} + BASE_BRANCH: master + BRANCH: gh-pages + FOLDER: build diff --git a/elm/todolist/README.md b/elm/todolist/README.md index 99db253..3b963fc 100644 --- a/elm/todolist/README.md +++ b/elm/todolist/README.md @@ -1,937 +1,3 @@ -# Elm App +# Elm todo app -This project is bootstrapped with [Create Elm App](https://github.com/halfzebra/create-elm-app). - -Below you will find some information on how to perform basic tasks. -You can find the most recent version of this guide [here](https://github.com/halfzebra/create-elm-app/blob/master/template/README.md). - -## Table of Contents - -* [Sending feedback](#sending-feedback) -* [Folder structure](#folder-structure) -* [Installing Elm packages](#installing-elm-packages) -* [Installing JavaScript packages](#installing-javascript-packages) -* [Available scripts](#available-scripts) - * [elm-app build](#elm-app-build) - * [elm-app start](#elm-app-start) - * [elm-app install](#elm-app-install) - * [elm-app test](#elm-app-test) - * [elm-app eject](#elm-app-eject) - * [elm-app \](#elm-app-elm-platform-command) - * [package](#package) - * [repl](#repl) - * [make](#make) - * [reactor](#reactor) -* [Turning on/off Elm Debugger](#turning-onoff-elm-debugger) -* [Dead code elimination](#dead-code-elimination) -* [Changing the Page ``](#changing-the-page-title) -* [JavaScript Interop](#javascript-interop) -* [Adding a Stylesheet](#adding-a-stylesheet) -* [Post-Processing CSS](#post-processing-css) -* [Using elm-css](#using-elm-css) -* [Adding a CSS Preprocessor (Sass, Less etc.)](#adding-a-css-preprocessor-sass-less-etc) -* [Adding Images and Fonts](#adding-images-and-fonts) -* [Using the `public` Folder](#using-the-public-folder) - * [Changing the HTML](#changing-the-html) - * [Adding Assets Outside of the Module System](#adding-assets-outside-of-the-module-system) - * [When to Use the `public` Folder](#when-to-use-the-public-folder) -* [Using custom environment variables](#using-custom-environment-variables) -* [Setting up API Proxy](#setting-up-api-proxy) -* [Using HTTPS in Development](#using-https-in-development) -* [Running tests](#running-tests) - * [Continuous Integration](#continuous-integration) -* [Making a Progressive Web App](#making-a-progressive-web-app) - * [Opting Out of Caching](#opting-out-of-caching) - * [Offline-First Considerations](#offline-first-considerations) - * [Progressive Web App Metadata](#progressive-web-app-metadata) -* [Overriding Webpack Config](#overriding-webpack-config) -* [Configuring the Proxy Manually](#configuring-the-proxy-manually) -* [Deployment](#deployment) - * [Building for Relative Paths](#building-for-relative-paths) - * [Static Server](#static-server) - * [Netlify](#netlify) - * [GitHub Pages](#github-pages) -* [IDE setup for Hot Module Replacement](#ide-setup-for-hot-module-replacement) - -## Sending feedback - -You are very welcome with any [feedback](https://github.com/halfzebra/create-elm-app/issues) - -Feel free to join [@create-elm-app](https://elmlang.slack.com/messages/CBBET0YMR/) channel at Slack. - -## Installing Elm packages - -```sh -elm-app install <package-name> -``` - -Other `elm-package` commands are also [available].(#package) - -## Installing JavaScript packages - -To use JavaScript packages from npm, you'll need to add a `package.json`, install the dependencies, and you're ready to go. - -```sh -npm init -y # Add package.json -npm install --save-dev pouchdb-browser # Install library from npm -``` - -```js -// Use in your JS code -import PouchDB from 'pouchdb-browser'; -const db = new PouchDB('mydb'); -``` - -## Folder structure - -```sh -my-app/ -├── .gitignore -├── README.md -├── elm.json -├── elm-stuff -├── public -│ ├── favicon.ico -│ ├── index.html -│ ├── logo.svg -│ └── manifest.json -├── src -│ ├── Main.elm -│ ├── index.js -│ ├── main.css -│ └── serviceWorker.js -└── tests - └── Tests.elm -``` - -For the project to build, these files must exist with exact filenames: - -* `public/index.html` is the page template; -* `public/favicon.ico` is the icon you see in the browser tab; -* `src/index.js` is the JavaScript entry point. - -You can delete or rename the other files. - -You may create subdirectories inside src. - -## Available scripts - -In the project directory you can run: - -### `elm-app build` - -Builds the app for production to the `build` folder. - -The build is minified, and the filenames include the hashes. -Your app is ready to be deployed! - -### `elm-app start` - -Runs the app in the development mode. - -The browser should open automatically to [http://localhost:3000](http://localhost:3000). If the browser does not open, you can open it manually and visit the URL. - -The page will reload if you make edits. -You will also see any lint errors in the console. - -You may change the listening port number by using the `PORT` environment variable. For example type `PORT=8000 elm-app start ` into the terminal/bash to run it from: [http://localhost:8000/](http://localhost:8000/). - -You can prevent the browser from opening automatically, -```sh -elm-app start --no-browser -``` - -### `elm-app install` - -Alias for [`elm install`](http://guide.elm-lang.org/get_started.html#elm-install) - -Use it for installing Elm packages from [package.elm-lang.org](http://package.elm-lang.org/) - -### `elm-app test` - -Run tests with [node-test-runner](https://github.com/rtfeldman/node-test-runner/tree/master) - -You can make test runner watch project files by running: - -```sh -elm-app test --watch -``` - -### `elm-app eject` - -**Note: this is a one-way operation. Once you `eject`, you can’t go back!** - -If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. - -Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Elm Platform, etc.) right into your project, so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point, you’re on your own. - -You don’t have to use 'eject' The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However, we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it. - -### `elm-app <elm-platform-command>` - -Create Elm App does not rely on the global installation of Elm Platform, but you still can use its local Elm Platform to access default command line tools: - -#### `repl` - -Alias for [`elm repl`](http://guide.elm-lang.org/get_started.html#elm-repl) - -#### `make` - -Alias for [`elm make`](http://guide.elm-lang.org/get_started.html#elm-make) - -#### `reactor` - -Alias for [`elm reactor`](http://guide.elm-lang.org/get_started.html#elm-reactor) - -## Turning on/off Elm Debugger - -By default, in production (`elm-app build`) the Debugger is turned off and in development mode (`elm-app start`) it's turned on. - -To turn on/off Elm Debugger explicitly, set `ELM_DEBUGGER` environment variable to `true` or `false` respectively. - -## Dead code elimination - -Create Elm App comes with an setup for dead code elimination which relies on the elm compiler flag `--optimize` and `uglifyjs`. - -## Changing the base path of the assets in the HTML - -By default, assets will be linked from the HTML to the root url. For example `/css/style.css`. - -If you deploy to a path that is not the root, you can change the `PUBLIC_URL` environment variable to properly reference your assets in the compiled assets. For example: `PUBLIC_URL=./ elm-app build`. - -## Changing the Page `<title>` - -You can find the source HTML file in the `public` folder of the generated project. You may edit the `<title>` tag in it to change the title from “Elm App” to anything else. - -Note that normally you wouldn’t edit files in the `public` folder very often. For example, [adding a stylesheet](#adding-a-stylesheet) is done without touching the HTML. - -If you need to dynamically update the page title based on the content, you can use the browser [`document.title`](https://developer.mozilla.org/en-US/docs/Web/API/Document/title) API and JavaScript interoperation. The next section of this tutorial will explain it in more detail. - -## JavaScript Interop - -You can send and receive values to and from JavaScript using [ports](https://guide.elm-lang.org/interop/javascript.html#ports). - -In the following example we will use JavaScript to write a log in the console, every time the state changes in outrElm app. To make it work with files created by `create-elm-app` you need to modify -`src/index.js` file to look like this: - -```js -import { Elm } from './Main.elm'; - -const app = Elm.Main.init({ - node: document.getElementById('root') -}); - -app.ports.logger.subscribe(message => { - console.log('Port emitted a new message: ' + message); -}); -``` - -Please note the `logger` port in the above example, more about it later. - -First let's allow the Main module to use ports and in `Main.elm` file please prepend `port` to the module declaration: - -```elm -port module Main exposing (..) -``` - -Do you remember `logger` in JavaScript? Let's declare the port: - -```elm -port logger : String -> Cmd msg -``` - -and use it to call JavaScript in you update function. - -```elm -update : Msg -> Model -> ( Model, Cmd Msg ) -update msg model = - case msg of - Inc -> - ( { model | counter = model.counter + 1} - , logger ("Elm-count up " ++ (toString (model.counter + 1))) - ) - Dec -> - ( { model | counter = model.counter - 1} - , logger ("Elm-count down " ++ (toString (model.counter - 1)))) - NoOp -> - ( model, Cmd.none ) -``` - -Please note that for `Inc` and `Dec` operations `Cmd.none` was replaced with `logger` port call which sends a message string to the JavaScript side. - -## Adding a Stylesheet - -This project setup uses [Webpack](https://webpack.js.org/) for handling all assets. Webpack offers a custom way of “extending” the concept of `import` beyond JavaScript. To express that a JavaScript file depends on a CSS file, you need to **import the CSS from the JavaScript file**: - -### `main.css` - -```css -body { - padding: 20px; -} -``` - -### `index.js` - -```js -import './main.css'; // Tell Webpack to pick-up the styles from main.css -``` - -## Post-Processing CSS - -This project setup minifies your CSS and adds vendor prefixes to it automatically through [Autoprefixer](https://github.com/postcss/autoprefixer) so you don’t need to worry about it. - -For example, this: - -```css -.container { - display: flex; -} -``` - -becomes this: - -```css -.container { - display: -webkit-box; - display: -ms-flexbox; - display: flex; -} -``` - -In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified `.css` file in the build output. - -You can put all your CSS right into `src/main.css`. It would still be imported from `src/index.js`, but you could always remove that import if you later migrate to a different build tool. - -## Using elm-css - -### Step 1: Install [elm-css](https://github.com/rtfeldman/elm-css) npm package - -```sh -npm install elm-css -g -``` - -### Step 2: Install Elm dependencies - -```sh -elm-app install rtfeldman/elm-css -elm-app install rtfeldman/elm-css-helpers -``` - -### Step 3: Create the stylesheet file - -Create an Elm file at `src/Stylesheets.elm` (The name of this file cannot be changed). - -```elm -port module Stylesheets exposing (main, CssClasses(..), CssIds(..), helpers) - -import Css exposing (..) -import Css.Elements exposing (body, li) -import Css.Namespace exposing (namespace) -import Css.File exposing (..) -import Html.CssHelpers exposing (withNamespace) - - -port files : CssFileStructure -> Cmd msg - - -cssFiles : CssFileStructure -cssFiles = - toFileStructure [ ( "src/style.css", Css.File.compile [ css ] ) ] - - -main : CssCompilerProgram -main = - Css.File.compiler files cssFiles - - -type CssClasses - = NavBar - - -type CssIds - = Page - - -appNamespace = - "App" - - -helpers = - withNamespace appNamespace - - -css = - (stylesheet << namespace appNamespace) - [ body - [ overflowX auto - , minWidth (px 1280) - ] - , id Page - [ backgroundColor (rgb 200 128 64) - , color (hex "CCFFFF") - , width (pct 100) - , height (pct 100) - , boxSizing borderBox - , padding (px 8) - , margin zero - ] - , class NavBar - [ margin zero - , padding zero - , children - [ li - [ (display inlineBlock) |> important - , color primaryAccentColor - ] - ] - ] - ] - - -primaryAccentColor = - hex "ccffaa" -``` - -### Step 4: Compiling the stylesheet - -To compile the CSS file, just run - -```sh -elm-css src/Stylesheets.elm -``` - -This will generate a file called `style.css` - -### Step 5: Import the compiled CSS file - -Add the following line to your `src/index.js`: - -```js -import './style.css'; -``` - -### Step 6: Using the stylesheet in your Elm code - -```elm -import Stylesheets exposing (helpers, CssIds(..), CssClasses(..)) - - -view model = - div [ helpers.id Page ] - [ div [ helpers.class [ NavBar ] ] - [ text "Your Elm App is working!" ] - ] -``` - -Please note that `Stylesheets.elm` exposes `helpers` record, which contains functions for creating id and class attributes. - -You can also destructure `helpers` to make your view more readable: - -```elm -{ id, class } = - helpers -``` - -## Adding a CSS Preprocessor (Sass, Less etc.) - -If you find CSS preprocessors valuable you can integrate one. In this walkthrough, we will be using Sass, but you can also use Less, or another alternative. - -First we need to create a `package.json` file, since create-elm-app is not shipping one at the moment. Walk through the normal `npm init` process. - -```sh -npm init -``` - -Second, let’s install the command-line interface for Sass: - -```sh -npm install --save node-sass-chokidar -``` - -Alternatively you may use `yarn`: - -```sh -yarn add node-sass-chokidar -``` - -Then in `package.json`, add the following lines to `scripts`: - -```diff - "scripts": { -+ "build-css": "node-sass-chokidar src/ -o src/", -+ "watch-css": "npm run build-css && node-sass-chokidar src/ -o src/ --watch --recursive", - ... - } -``` - -> Note: To use a different preprocessor, replace `build-css` and `watch-css` commands according to your preprocessor’s documentation. - -Now you can rename `src/main.css` to `src/main.scss` and run `npm run watch-css`. The watcher will find every Sass file in `src` subdirectories, and create a corresponding CSS file next to it, in our case overwriting `src/main.css`. Since `src/index.js` still imports `src/main.css`, the styles become a part of your application. You can now edit `src/main.scss`, and `src/main.css` will be regenerated. - -To share variables between Sass files, you can use Sass imports. For example, `src/main.scss` and other component style files could include `@import "./shared.scss";` with variable definitions. - -To enable importing files without using relative paths, you can add the `--include-path` option to the command in `package.json`. - -```json -{ - "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/", - "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive", -} -``` - -This will allow you to do imports like - -```scss -@import 'styles/_colors.scss'; // assuming a styles directory under src/ -@import 'nprogress/nprogress'; // importing a css file from the nprogress node module -``` - -At this point you might want to remove all CSS files from the source control, and add `src/**/*.css` to your `.gitignore` file. It is generally a good practice to keep the build products outside of the source control. - -**Why `node-sass-chokidar`?** - -`node-sass` has been reported as having the following issues: - -* `node-sass --watch` has been reported to have _performance issues_ in certain conditions when used in a virtual machine or with docker. - -* Infinite styles compiling [#1939](https://github.com/facebookincubator/create-react-app/issues/1939) - -* `node-sass` has been reported as having issues with detecting new files in a directory [#1891](https://github.com/sass/node-sass/issues/1891) - -`node-sass-chokidar` is used here as it addresses these issues. - -## Adding Images and Fonts - -With Webpack, using static assets like images and fonts works similarly to CSS. - -By requiring an image in JavaScript code, you tell Webpack to add a file to the build of your application. The variable will contain a unique path to the said file. - -Here is an example: - -```js -import logoPath from './logo.svg'; // Tell Webpack this JS file uses this image -import { Main } from './Main.elm'; - -Main.embed( - document.getElementById('root'), - logoPath // Pass image path as a flag for Html.programWithFlags -); -``` - -Later on, you can use the image path in your view for displaying it in the DOM. - -```elm -view : Model -> Html Msg -view model = - div [] - [ img [ src model.logo ] [] - , div [] [ text model.message ] - ] -``` - -## Using the `public` Folder - -### Changing the HTML - -The `public` folder contains the HTML file so you can tweak it, for example, to [set the page title](#changing-the-page-title). -The `<script>` tag with the compiled code will be added to it automatically during the build process. - -### Adding Assets Outside of the Module System - -You can also add other assets to the `public` folder. - -Note that we normally encourage you to `import` assets in JavaScript files instead. -For example, see the sections on [adding a stylesheet](#adding-a-stylesheet) and [adding images and fonts](#adding-images-fonts-and-files). -This mechanism provides a few benefits: - -* Scripts and stylesheets get minified and bundled together to avoid extra network requests. -* Missing files cause compilation errors instead of 404 errors for your users. -* Result filenames include content hashes, so you don’t need to worry about browsers caching their old versions. - -However, there is a **escape hatch** that you can use to add an asset outside of the module system. - -If you put a file into the `public` folder, it will **not** be processed by Webpack. Instead, it will be copied into the build folder untouched. To reference assets in the `public` folder, you need to use a special variable called `PUBLIC_URL`. - -Inside `index.html`, you can use it like this: - -```html -<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> -``` - -Only files inside the `public` folder will be accessible by `%PUBLIC_URL%` prefix. If you need to use a file from `src` or `node_modules`, you’ll have to copy it there to explicitly specify your intention to make this file a part of the build. - -When you run `elm-app build`, Create Elm App will substitute `%PUBLIC_URL%` with a correct absolute path, so your project works even if you use client-side routing or host it at a non-root URL. - -In Elm code, you can use `%PUBLIC_URL%` for similar purposes: - -```elm -{- Note: this is an escape hatch and should be used sparingly! - Normally we recommend using `import` and `Html.programWithFlags` for getting - asset URLs as described in “Adding Images and Fonts” above this section. --} -img [ src "%PUBLIC_URL%/logo.svg" ] [] -``` - -In JavaScript code, you can use `process.env.PUBLIC_URL` for similar purposes: - -```js -const logo = `<img src=${process.env.PUBLIC_URL + '/img/logo.svg'} />`; -``` - -Keep in mind the downsides of this approach: - -* None of the files in `public` folder get post-processed or minified. -* Missing files will not be called at compilation time, and will cause 404 errors for your users. -* Result filenames won’t include content hashes so you’ll need to add query arguments or rename them every time they change. - -### When to Use the `public` Folder - -Normally we recommend importing [stylesheets](#adding-a-stylesheet), [images, and fonts](#adding-images-fonts-and-files) from JavaScript. -The `public` folder is used as a workaround for some less common cases: - -* You need a file with a specific name in the build output, such as [`manifest.webmanifest`](https://developer.mozilla.org/en-US/docs/Web/Manifest). -* You have thousands of images and need to dynamically reference their paths. -* You want to include a small script like [`pace.js`](http://github.hubspot.com/pace/docs/welcome/) outside of the bundled code. -* Some library may be incompatible with Webpack and you have no other option but to include it as a `<script>` tag. - -Note that if you add a `<script>` that declares global variables, you also need to read the next section on using them. - -## Using custom environment variables - -In your JavaScript code you have access to variables declared in your -environment, like an API key set in an `.env`-file or via your shell. They are -available on the `process.env`-object and will be injected during build time. - -Besides the `NODE_ENV` variable you can access all variables prefixed with -`ELM_APP_`: - -```bash -# .env -ELM_APP_API_KEY="secret-key" -``` - -Alternatively, you can set them on your shell before calling the start- or -build-script, e.g.: - -```bash -ELM_APP_API_KEY="secret-key" elm-app start -``` - -Both ways can be mixed, but variables set on your shell prior to calling one of -the scripts will take precedence over those declared in an `.env`-file. - -Passing the variables to your Elm-code can be done via `flags`: - -```javascript -// index.js -import { Main } from './Main.elm'; - -Main.fullscreen({ - environment: process.env.NODE_ENV, - apiKey: process.env.ELM_APP_API_KEY -}); -``` - -```elm --- Main.elm -type alias Flags = { apiKey : String, environment : String } - -init : Flags -> ( Model, Cmd Msg ) -init flags = - ... - -main = - programWithFlags { init = init, ... } -``` - -Be aware that you cannot override `NODE_ENV` manually. See -[this list from the `dotenv`-library](https://github.com/bkeepers/dotenv#what-other-env-files-can-i-use) -for a list of files you can use to declare environment variables. - -**Note: Changes to your `.env` are only picked up on `elm-app start`. This means that you have to restart your server for your .env file changes to be picked up!** - - -## Setting up API Proxy - -To forward the API ( REST ) calls to backend server, add a proxy to the `elmapp.config.js` in the top level json object. - -```js -module.exports = { - ... - proxy: "http://localhost:1313", - ... -} -``` - -Make sure the XHR requests set the `Content-type: application/json` and `Accept: application/json`. -The development server has heuristics, to handle its own flow, which may interfere with proxying of -other html and javascript content types. - -```sh - curl -X GET -H "Content-type: application/json" -H "Accept: application/json" http://localhost:3000/api/list -``` - -## Using HTTPS in Development - -If you need to serve the development server over HTTPS, set the `HTTPS` environment variable to `true` before you start development server with `elm-app start`. - -Note that the server will use a self-signed certificate, so you will most likely have to add an exception to accept it in your browser. - -## Running Tests - -Create Elm App uses [elm-test](https://github.com/rtfeldman/node-test-runner) as its test runner. - -### Continuous Integration - -#### Travis CI - -1. Following the [Travis Getting started](https://docs.travis-ci.com/user/getting-started/) guide for syncing your GitHub repository with Travis. You may need to initialize some settings manually in your [profile](https://travis-ci.org/profile) page. -2. Add a `.travis.yml` file to your git repository. - -```yaml -language: node_js - -sudo: required - -node_js: - - '7' - -install: - - npm i create-elm-app -g - -script: elm-app test -``` - -1. Trigger your first build with a git push. -1. [Customize your Travis CI Build](https://docs.travis-ci.com/user/customizing-the-build/) if needed. - -## Making a Progressive Web App - -By default, the production build is a fully functional, offline-first -[Progressive Web App](https://developers.google.com/web/progressive-web-apps/). - -Progressive Web Apps are faster and more reliable than traditional web pages, and provide an engaging mobile experience: - -* All static site assets are cached so that your page loads fast on subsequent visits, regardless of network connectivity (such as 2G or 3G). Updates are downloaded in the background. -* Your app will work regardless of network state, even if offline. This means your users will be able to use your app at 10,000 feet and on the Subway. -* On mobile devices, your app can be added directly to the user's home screen, app icon and all. You can also re-engage users using web **push notifications**. This eliminates the need for the app store. - -The [`workbox-webpack-plugin`](https://www.npmjs.com/package/workbox-webpack-plugin) -is integrated into production configuration, -and it will take care of generating a service worker file that will automatically -precache all of your local assets and keep them up to date as you deploy updates. -The service worker will use a [cache-first strategy](https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#cache-falling-back-to-network) -for handling all requests for local assets, including the initial HTML, ensuring -that your web app is reliably fast, even on a slow or unreliable network. - -### Opting Out of Caching - -If you would prefer not to enable service workers prior to your initial -production deployment, then remove the call to `serviceWorkerRegistration.register()` -from [`src/index.js`](src/index.js). - -If you had previously enabled service workers in your production deployment and -have decided that you would like to disable them for all your existing users, -you can swap out the call to `serviceWorkerRegistration.register()` in -[`src/index.js`](src/index.js) with a call to `serviceWorkerRegistration.unregister()`. -After the user visits a page that has `serviceWorkerRegistration.unregister()`, -the service worker will be uninstalled. Note that depending on how `/service-worker.js` is served, -it may take up to 24 hours for the cache to be invalidated. - -### Offline-First Considerations - -1. Service workers [require HTTPS](https://developers.google.com/web/fundamentals/getting-started/primers/service-workers#you_need_https), although to facilitate local testing, that policy [does not apply to `localhost`](http://stackoverflow.com/questions/34160509/options-for-testing-service-workers-via-http/34161385#34161385). If your production web server does not support HTTPS, then the service worker registration will fail, but the rest of your web app will remain functional. - -1. Service workers are [not currently supported](https://jakearchibald.github.io/isserviceworkerready/) in all web browsers. Service worker registration [won't be attempted](src/serviceWorker.js) on browsers that lack support. - -1. The service worker is only enabled in the [production environment](#deployment), e.g. the output of `npm run build`. It's recommended that you do not enable an offline-first service worker in a development environment, as it can lead to frustration when previously cached assets are used and do not include the latest changes you've made locally. - -1. If you _need_ to test your offline-first service worker locally, build the application (using `npm run build`) and run a simple http server from your build directory. After running the build script, `create-elm-app` will give instructions for one way to test your production build locally and the [deployment instructions](#deployment) have instructions for using other methods. _Be sure to always use an incognito window to avoid complications with your browser cache._ - -1. If possible, configure your production environment to serve the generated `service-worker.js` [with HTTP caching disabled](http://stackoverflow.com/questions/38843970/service-worker-javascript-update-frequency-every-24-hours). If that's not possible—[GitHub Pages](#github-pages), for instance, does not allow you to change the default 10 minute HTTP cache lifetime—then be aware that if you visit your production site, and then revisit again before `service-worker.js` has expired from your HTTP cache, you'll continue to get the previously cached assets from the service worker. If you have an immediate need to view your updated production deployment, performing a shift-refresh will temporarily disable the service worker and retrieve all assets from the network. - -1. Users aren't always familiar with offline-first web apps. It can be useful to [let the user know](https://developers.google.com/web/fundamentals/instant-and-offline/offline-ux#inform_the_user_when_the_app_is_ready_for_offline_consumption) when the service worker has finished populating your caches (showing a "This web app works offline!" message) and also let them know when the service worker has fetched the latest updates that will be available the next time they load the page (showing a "New content is available; please refresh." message). Showing this messages is currently left as an exercise to the developer, but as a starting point, you can make use of the logic included in [`src/serviceWorker.js`](src/serviceWorker.js), which demonstrates which service worker lifecycle events to listen for to detect each scenario, and which as a default, just logs appropriate messages to the JavaScript console. - -1. By default, the generated service worker file will not intercept or cache any cross-origin traffic, like HTTP [API requests](#integrating-with-an-api-backend), images, or embeds loaded from a different domain. If you would like to use a runtime caching strategy for those requests, you can [`eject`](#npm-run-eject) and then configure the [`runtimeCaching`](https://developers.google.com/web/tools/workbox/modules/workbox-webpack-plugin) option in the `WorkboxPlugin` section of [`webpack.config.prod.js`](../config/webpack.config.prod.js). - -### Progressive Web App Metadata - -The default configuration includes a web app manifest located at -[`public/manifest.json`](public/manifest.json), that you can customize with -details specific to your web application. - -When a user adds a web app to their homescreen using Chrome or Firefox on -Android, the metadata in [`manifest.json`](public/manifest.json) determines what -icons, names, and branding colors to use when the web app is displayed. -[The Web App Manifest guide](https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/) -provides more context about what each field means, and how your customizations -will affect your users' experience. - -## Overriding Webpack Config - -Create Elm App allows Webpack config overrides without [ejecting](#elm-app-eject). - -Create a CommonJS module with the name `elmapp.config.js` in the root directory of your project. The module has to export an object with `"configureWebpack"` property as shown in the example. - -```js -module.exports = { - configureWebpack: (config, env) => { - // Manipulate the config object and return it. - return config; - } -} -``` - -Mutate the configuration directly or use [webpack-merge](https://www.npmjs.com/package/webpack-merge) to override the config. - -`env` variable will help you distinguish `"development"` from `"production"` for environment-specific overrides. - -## Configuring the Proxy Manually - -If the `proxy` option is not flexible enough for you, you can get direct access to the Express app instance and hook up your own proxy middleware. - -You can use this feature in conjunction with the `proxy` property in `elmapp.config.js`, but it is recommended you consolidate all of your logic into `setupProxy` property`. - -First, install http-proxy-middleware using npm: - -``` -$ npm init --yes -$ npm install http-proxy-middleware --save -``` - -Next, create `elmapp.config.js` in the root of your project and place the following contents in it: - -```js -const proxy = require('http-proxy-middleware'); - -module.exports = { - setupProxy: function(app) { - // ... - } -}; -``` - -You can now register proxies as you wish! Here's an example using the above http-proxy-middleware: - -```js -const proxy = require('http-proxy-middleware'); - -module.exports = { - setupProxy: function(app) { - app.use(proxy('/api', { target: 'http://localhost:5000/' })); - } -}; -``` - -## Deployment - -`elm-app build` creates a `build` directory with a production build of your app. Set up your favourite HTTP server so that a visitor to your site is served `index.html`, and requests to static paths like `/static/js/main.<hash>.js` are served with the contents of the `/static/js/main.<hash>.js` file. - -### Building for Relative Paths - -By default, Create Elm App produces a build assuming your app is hosted at the server root. - -To override this, specify the `homepage` in your `elmapp.config.js`, for example: - -```js -module.exports = { - homepage: "http://mywebsite.com/relativepath" -} -``` - -This will let Create Elm App correctly infer the root path to use in the generated HTML file. - -### Static Server - -For environments using [Node](https://nodejs.org/), the easiest way to handle this would be to install [serve](https://github.com/zeit/serve) and let it handle the rest: - -```sh -npm install -g serve -serve -s build -``` - -The last command shown above will serve your static site on the port **5000**. Like many of [serve](https://github.com/zeit/serve)’s internal settings, the port can be adjusted using the `-p` or `--port` flags. - -Run this command to get a full list of the options available: - -```sh -serve -h -``` - -### Netlify - -#### Step 1: Create a `package.json` file -#### Step 2: `npm install --save-dev create-elm-app` -Since netlify runs the build step on their server we need to install create-elm-app. -#### Step 3: Add a build script to the `package.json` file -``` -"scripts": { - "build": "elm-app build", - ... -} -``` -#### Step 4: Add a netlify.toml file in the repo's root -``` -[[redirects]] - from = "/*" - to = "/index.html" - status = 200 -``` -#### Step 5: Go to the netlify settings and set the publish directory to `build` and the build command to `npm run build` -This step is important to make sure netlify uses the correct build command. - -### GitHub Pages - -#### Step 1: Add `homepage` to `elmapp.config.js` - -**The step below is important!** - -**If you skip it, your app will not deploy correctly.** - -Open your `elmapp.config.js` and add a `homepage` field: - -```js -module.exports = { - homepage: "https://myusername.github.io/my-app", -} -``` - -Create Elm App uses the `homepage` field to determine the root URL in the built HTML file. - -#### Step 2: Build the static site - -```sh -elm-app build -``` - -#### Step 3: Deploy the site by running `gh-pages -d build` - -We will use [gh-pages](https://www.npmjs.com/package/gh-pages) to upload the files from the `build` directory to GitHub. If you haven't already installed it, do so now (`npm install -g gh-pages`) - -Now run: - -```sh -gh-pages -d build -``` - -#### Step 4: Ensure your project’s settings use `gh-pages` - -Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch: - -![GH Pages branch](https://i.imgur.com/HUjEr9l.png) - -#### Step 5: Optionally, configure the domain - -You can configure a custom domain with GitHub Pages by adding a `CNAME` file to the `public/` folder. - -#### Notes on client-side routing - -GitHub Pages doesn’t support routers that use the HTML5 `pushState` history API under the hood (for example, React Router using `browserHistory`). This is because when there is a fresh page load for a url like `http://user.github.io/todomvc/todos/42`, where `/todos/42` is a frontend route, the GitHub Pages server returns 404 because it knows nothing of `/todos/42`. If you want to add a router to a project hosted on GitHub Pages, here are a couple of solutions: - -* You could switch from using HTML5 history API to routing with hashes. -* Alternatively, you can use a trick to teach GitHub Pages to handle 404 by redirecting to your `index.html` page with a special redirect parameter. You would need to add a `404.html` file with the redirection code to the `build` folder before deploying your project, and you’ll need to add code handling the redirect parameter to `index.html`. You can find a detailed explanation of this technique [in this guide](https://github.com/rafrex/spa-github-pages). - -## IDE setup for Hot Module Replacement - -Remember to disable [safe write](https://webpack.js.org/guides/development/#adjusting-your-text-editor) if you are using VIM or IntelliJ IDE, such as WebStorm. +Todo app made in 1h for getting a better understanding of the elm architecture diff --git a/elm/todolist/tests/Tests.elm b/elm/todolist/tests/Tests.elm deleted file mode 100644 index 3cf3499..0000000 --- a/elm/todolist/tests/Tests.elm +++ /dev/null @@ -1,22 +0,0 @@ -module Tests exposing (..) - -import Test exposing (..) -import Expect - - --- Check out https://package.elm-lang.org/packages/elm-explorations/test/latest to learn more about testing in Elm! - - -all : Test -all = - describe "A Test Suite" - [ test "Addition" <| - \_ -> - Expect.equal 10 (3 + 7) - , test "String.left" <| - \_ -> - Expect.equal "a" (String.left 1 "abcdefg") - , test "This test should fail" <| - \_ -> - Expect.fail "failed as expected!" - ] From 548c05df99bb921ba6ec13194384c73bd823265a Mon Sep 17 00:00:00 2001 From: Matei Adriel <rafaeladriel11@gmail.com> Date: Thu, 28 Nov 2019 17:15:34 +0200 Subject: [PATCH 4/7] elm(todolist): fix: fixed ci trying to elm install Signed-off-by: prescientmoon <git@moonythm.dev> --- elm/todolist/.github/workflows/elm.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/elm/todolist/.github/workflows/elm.yml b/elm/todolist/.github/workflows/elm.yml index b020b75..ad95080 100644 --- a/elm/todolist/.github/workflows/elm.yml +++ b/elm/todolist/.github/workflows/elm.yml @@ -19,7 +19,6 @@ jobs: with: node-version: ${{ matrix.node-version }} - run: npm i -g elm create-elm-app - - run: elm install - run: elm-app build - name: Deploy to github pages uses: JamesIves/github-pages-deploy-action@master From 98b2f7ee9f84b41b5b87ebed90c2ea2cb2b2b95a Mon Sep 17 00:00:00 2001 From: Matei Adriel <rafaeladriel11@gmail.com> Date: Thu, 28 Nov 2019 17:19:32 +0200 Subject: [PATCH 5/7] elm(todolist): fix: fixed gh pages not beeing able to serve files Signed-off-by: prescientmoon <git@moonythm.dev> --- elm/todolist/public/index.html | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/elm/todolist/public/index.html b/elm/todolist/public/index.html index 40cb71b..2552e93 100644 --- a/elm/todolist/public/index.html +++ b/elm/todolist/public/index.html @@ -1,22 +1,26 @@ <!DOCTYPE html> <html lang="en"> -<head> - <meta charset="utf-8"> - <meta http-equiv="x-ua-compatible" content="ie=edge"> - <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> - <meta name="theme-color" content="#000000"> + <head> + <meta charset="utf-8" /> + <meta http-equiv="x-ua-compatible" content="ie=edge" /> + <meta + name="viewport" + content="width=device-width, initial-scale=1, shrink-to-fit=no" + /> + <meta name="theme-color" content="#000000" /> <!-- manifest.json provides metadata used when your web app is added to the homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/ --> - <link rel="manifest" href="%PUBLIC_URL%/manifest.json"> - <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> + <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> + <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" /> <title>Elm App - - + + +
- + From 5a8729c9842d8ebe83936fd528bdd2763387bc62 Mon Sep 17 00:00:00 2001 From: Matei Adriel Date: Thu, 28 Nov 2019 17:26:28 +0200 Subject: [PATCH 6/7] elm(todolist): fix: hopefully fixed gh pages not beeing able to serve files Signed-off-by: prescientmoon --- elm/todolist/public/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/elm/todolist/public/index.html b/elm/todolist/public/index.html index 2552e93..c0fb46e 100644 --- a/elm/todolist/public/index.html +++ b/elm/todolist/public/index.html @@ -15,7 +15,7 @@ Elm App - +