1
0
mirror of https://github.com/jhillyerd/inbucket.git synced 2025-12-17 09:37:02 +00:00

ui: Initial Elm UI import

Merged from https://github.com/jhillyerd/inbucket-elm

Uses https://github.com/halfzebra/create-elm-app
This commit is contained in:
James Hillyerd
2018-06-02 12:44:15 -07:00
parent 8b5a05eb40
commit c5b5321be3
24 changed files with 3027 additions and 1 deletions

865
ui/README.md Normal file
View File

@@ -0,0 +1,865 @@
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-platform-comand>](#elm-app-elm-platform-comand)
- [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 `<title>`](#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)
- [Running tests](#running-tests)
- [Dependencies in Tests](#dependencies-in-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)
- [Deployment](#deployment)
- [Static Server](#static-server)
- [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)
## 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
```
my-app/
├── .gitignore
├── README.md
├── elm-package.json
├── elm-stuff
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo.svg
│ └── manifest.json
├── src
│ ├── Main.elm
│ ├── index.js
│ ├── main.css
│ └── registerServiceWorker.js
└── tests
├── Tests.elm
└── elm-package.json
```
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.
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
The page will reload if you make edits.
You will also see any lint errors in the console.
### `elm-app install`
An alias for [`elm-app package install`](#package)
### `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 cant go back!**
If you arent 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, youre on your own.
You dont have to use 'eject' The curated feature set is suitable for small and middle deployments, and you shouldnt feel obligated to use this feature. However, we understand that this tool wouldnt be useful if you couldnt customize it when you are ready for it.
### `elm-app <elm-platform-comand>`
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:
#### `package`
Alias for [elm-package](http://guide.elm-lang.org/get_started.html#elm-package)
Use it for installing Elm packages from [package.elm-lang.org](http://package.elm-lang.org/)
#### `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 opinionated setup for dead code elimination which is disabled by default, because it may break your code.
You can enable it by setting `DEAD_CODE_ELIMINATION` environment variable to `true`
## 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 wouldnt 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 from JavaScript using the concept of [ports.](https://guide.elm-lang.org/interop/javascript.html#ports).
In the following example we will use JavaScript to change the page title dynamically. 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 './main.css';
import { Main } from './Main.elm';
import registerServiceWorker from './registerServiceWorker';
var app = Main.embed(document.getElementById('root'));
registerServiceWorker();
// ports related code
app.ports.windowTitle.subscribe(function(newTitle){
window.document.title = newTitle;
});
```
Please note the `windowTitle` port in the above example, more about it later.
First let's allow the Main nodule to use ports and in `Main.elm` file please append `port` to the module declaration:
```elm
port module Main exposing (..)
```
Do you remember `windowTitle` in JavaScript? Let's declare the port:
```elm
port windowTitle : 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}
, windowTitle ("Elm-count up " ++ (toString (model.counter + 1)))
)
Dec ->
( { model | counter = model.counter - 1}
, windowTitle ("Elm-count down " ++ (toString (model.counter - 1))))
NoOp ->
( model, Cmd.none )
```
Please note that for Inc and Dec operations `Cmd.none` was replaced with `windowTitle` port call that is executed on 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 dont need to worry about it.
For example, this:
```css
.container {
display: flex;
flex-direction: row;
align-items: center;
}
```
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.
```
npm init
```
Second, lets 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 preprocessors 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`.
```
"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 dont 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`, youll 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 wont include content hashes so youll 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.
## Setting up API Proxy
To forward the API ( REST ) calls to backend server, add a proxy to the `elm-package.json` in the top level json object.
```json
{
...
"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
```
## Running Tests
Create Elm App uses [elm-test](https://github.com/rtfeldman/node-test-runner) as its test runner.
### Dependencies in Tests
To use packages in tests, you also need to install them in `tests` directory.
```bash
elm-app test --add-dependencies elm-package.json
```
### 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.
1. 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 [`sw-precache-webpack-plugin`](https://github.com/goldhand/sw-precache-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/registerServiceWorker.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-react-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/registerServiceWorker.js`](src/registerServiceWorker.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://github.com/GoogleChrome/sw-precache#runtimecaching-arrayobject)
option in the `SWPrecacheWebpackPlugin` 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.
## 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.
### 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
```
### GitHub Pages
#### Step 1: Add `homepage` to `elm-package.json`
**The step below is important!**<br>
**If you skip it, your app will not deploy correctly.**
Open your `elm-package.json` and add a `homepage` field:
```js
"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 projects settings use `gh-pages`
Finally, make sure **GitHub Pages** option in your GitHub project settings is set to use the `gh-pages` branch:
<img src="http://i.imgur.com/HUjEr9l.png" width="500" alt="gh-pages branch setting">
#### 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 doesnt 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 youll 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.github.io/docs/webpack-dev-server.html#working-with-editors-ides-supporting-safe-write) if you are using VIM or IntelliJ IDE, such as WebStorm.

32
ui/elm-package.json Normal file
View File

@@ -0,0 +1,32 @@
{
"version": "1.0.0",
"summary": "Elm powered UI for Inbucket",
"repository": "https://github.com/jhillyerd/inbucket.git",
"license": "MIT",
"source-directories": [
"src"
],
"exposed-modules": [],
"proxy": {
"/api": {
"target": "http://localhost:9000",
"ws": true
},
"/debug": {
"target": "http://localhost:9000"
}
},
"dependencies": {
"NoRedInk/elm-decode-pipeline": "3.0.0 <= v < 4.0.0",
"basti1302/elm-human-readable-filesize": "1.1.0 <= v < 2.0.0",
"elm-lang/core": "5.1.1 <= v < 6.0.0",
"elm-lang/html": "2.0.0 <= v < 3.0.0",
"elm-lang/http": "1.0.0 <= v < 2.0.0",
"elm-lang/navigation": "2.1.0 <= v < 3.0.0",
"elm-lang/svg": "2.0.0 <= v < 3.0.0",
"elm-lang/websocket": "1.0.2 <= v < 2.0.0",
"evancz/url-parser": "2.0.1 <= v < 3.0.0",
"jweir/sparkline": "3.0.0 <= v < 4.0.0"
},
"elm-version": "0.18.0 <= v < 0.19.0"
}

BIN
ui/public/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

22
ui/public/index.html Normal file
View File

@@ -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</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
</body>
</html>

15
ui/public/manifest.json Normal file
View File

@@ -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"
}

44
ui/src/Data/Message.elm Normal file
View File

@@ -0,0 +1,44 @@
module Data.Message exposing (..)
import Json.Decode as Decode exposing (..)
import Json.Decode.Pipeline exposing (..)
type alias Message =
{ mailbox : String
, id : String
, from : String
, to : List String
, subject : String
, date : String
, size : Int
, seen : Bool
, body : Body
}
type alias Body =
{ text : String
, html : String
}
decoder : Decoder Message
decoder =
decode Message
|> required "mailbox" string
|> required "id" string
|> optional "from" string ""
|> required "to" (list string)
|> optional "subject" string ""
|> required "date" string
|> required "size" int
|> required "seen" bool
|> required "body" bodyDecoder
bodyDecoder : Decoder Body
bodyDecoder =
decode Body
|> required "text" string
|> required "html" string

View File

@@ -0,0 +1,29 @@
module Data.MessageHeader exposing (..)
import Json.Decode as Decode exposing (..)
import Json.Decode.Pipeline exposing (..)
type alias MessageHeader =
{ mailbox : String
, id : String
, from : String
, to : List String
, subject : String
, date : String
, size : Int
, seen : Bool
}
decoder : Decoder MessageHeader
decoder =
decode MessageHeader
|> required "mailbox" string
|> required "id" string
|> optional "from" string ""
|> required "to" (list string)
|> optional "subject" string ""
|> required "date" string
|> required "size" int
|> required "seen" bool

62
ui/src/Data/Metrics.elm Normal file
View File

@@ -0,0 +1,62 @@
module Data.Metrics exposing (..)
import Json.Decode as Decode exposing (..)
import Json.Decode.Pipeline exposing (..)
type alias Metrics =
{ sysMem : Int
, heapSize : Int
, heapUsed : Int
, heapObjects : Int
, goRoutines : Int
, webSockets : Int
, smtpConnOpen : Int
, smtpConnTotal : Int
, smtpConnHist : List Int
, smtpReceivedTotal : Int
, smtpReceivedHist : List Int
, smtpErrorsTotal : Int
, smtpErrorsHist : List Int
, smtpWarnsTotal : Int
, smtpWarnsHist : List Int
, retentionDeletesTotal : Int
, retentionDeletesHist : List Int
, retainedCount : Int
, retainedCountHist : List Int
, retainedSize : Int
, retainedSizeHist : List Int
}
decoder : Decoder Metrics
decoder =
decode Metrics
|> requiredAt [ "memstats", "Sys" ] int
|> requiredAt [ "memstats", "HeapSys" ] int
|> requiredAt [ "memstats", "HeapAlloc" ] int
|> requiredAt [ "memstats", "HeapObjects" ] int
|> requiredAt [ "goroutines" ] int
|> requiredAt [ "http", "WebSocketConnectsCurrent" ] int
|> requiredAt [ "smtp", "ConnectsCurrent" ] int
|> requiredAt [ "smtp", "ConnectsTotal" ] int
|> requiredAt [ "smtp", "ConnectsHist" ] decodeIntList
|> requiredAt [ "smtp", "ReceivedTotal" ] int
|> requiredAt [ "smtp", "ReceivedHist" ] decodeIntList
|> requiredAt [ "smtp", "ErrorsTotal" ] int
|> requiredAt [ "smtp", "ErrorsHist" ] decodeIntList
|> requiredAt [ "smtp", "WarnsTotal" ] int
|> requiredAt [ "smtp", "WarnsHist" ] decodeIntList
|> requiredAt [ "retention", "DeletesTotal" ] int
|> requiredAt [ "retention", "DeletesHist" ] decodeIntList
|> requiredAt [ "retention", "RetainedCurrent" ] int
|> requiredAt [ "retention", "RetainedHist" ] decodeIntList
|> requiredAt [ "retention", "RetainedSize" ] int
|> requiredAt [ "retention", "SizeHist" ] decodeIntList
{-| Decodes Inbuckets hacky comma-separated-int JSON strings.
-}
decodeIntList : Decoder (List Int)
decodeIntList =
map (String.split "," >> List.map (String.toInt >> Result.withDefault 0)) string

91
ui/src/Data/Session.elm Normal file
View File

@@ -0,0 +1,91 @@
module Data.Session
exposing
( Session
, Persistent
, Msg(..)
, decoder
, decodeValueWithDefault
, init
, none
, update
)
import Json.Decode as Decode exposing (..)
import Json.Decode.Pipeline exposing (..)
type alias Session =
{ flash : String
, routing : Bool
, persistent : Persistent
}
type alias Persistent =
{ recentMailboxes : List String
}
type Msg
= None
| SetFlash String
| ClearFlash
| DisableRouting
| EnableRouting
| AddRecent String
init : Persistent -> Session
init persistent =
Session "" True persistent
update : Msg -> Session -> Session
update msg session =
case msg of
None ->
session
SetFlash flash ->
{ session | flash = flash }
ClearFlash ->
{ session | flash = "" }
DisableRouting ->
{ session | routing = False }
EnableRouting ->
{ session | routing = True }
AddRecent mailbox ->
if List.head session.persistent.recentMailboxes == Just mailbox then
session
else
let
recent =
session.persistent.recentMailboxes
|> List.filter ((/=) mailbox)
|> List.take 7
|> (::) mailbox
persistent =
session.persistent
in
{ session | persistent = { persistent | recentMailboxes = recent } }
none : Msg
none =
None
decoder : Decoder Persistent
decoder =
decode Persistent
|> optional "recentMailboxes" (list string) []
decodeValueWithDefault : Value -> Persistent
decodeValueWithDefault =
Decode.decodeValue decoder >> Result.withDefault { recentMailboxes = [] }

39
ui/src/HttpUtil.elm Normal file
View File

@@ -0,0 +1,39 @@
module HttpUtil exposing (..)
import Http
delete : String -> Http.Request ()
delete url =
Http.request
{ method = "DELETE"
, headers = []
, url = url
, body = Http.emptyBody
, expect = Http.expectStringResponse (\_ -> Ok ())
, timeout = Nothing
, withCredentials = False
}
errorString : Http.Error -> String
errorString error =
case error of
Http.BadUrl str ->
"Bad URL: " ++ str
Http.Timeout ->
"HTTP timeout"
Http.NetworkError ->
"HTTP Network error"
Http.BadStatus res ->
"Bad HTTP status: " ++ toString res.status.code
Http.BadPayload msg res ->
"Bad HTTP payload: "
++ msg
++ " ("
++ toString res.status.code
++ ")"

288
ui/src/Main.elm Normal file
View File

@@ -0,0 +1,288 @@
module Main exposing (..)
import Data.Session as Session exposing (Session, decoder)
import Json.Decode as Decode exposing (Value)
import Html exposing (..)
import Navigation exposing (Location)
import Page.Home as Home
import Page.Mailbox as Mailbox
import Page.Monitor as Monitor
import Page.Status as Status
import Ports
import Route exposing (Route)
import Views.Page as Page exposing (ActivePage(..), frame)
-- MODEL
type Page
= Home Home.Model
| Mailbox Mailbox.Model
| Monitor Monitor.Model
| Status Status.Model
type alias Model =
{ page : Page
, session : Session
, mailboxName : String
}
init : Value -> Location -> ( Model, Cmd Msg )
init sessionValue location =
let
session =
Session.init (Session.decodeValueWithDefault sessionValue)
model =
{ page = Home Home.init
, session = session
, mailboxName = ""
}
route =
Route.fromLocation location
in
applySession (setRoute route model)
type Msg
= SetRoute Route
| NewRoute Route
| UpdateSession (Result String Session.Persistent)
| MailboxNameInput String
| ViewMailbox String
| HomeMsg Home.Msg
| MailboxMsg Mailbox.Msg
| MonitorMsg Monitor.Msg
| StatusMsg Status.Msg
-- SUBSCRIPTIONS
subscriptions : Model -> Sub Msg
subscriptions model =
Sub.batch
[ pageSubscriptions model.page
, Sub.map UpdateSession sessionChange
]
sessionChange : Sub (Result String Session.Persistent)
sessionChange =
Ports.onSessionChange (Decode.decodeValue Session.decoder)
pageSubscriptions : Page -> Sub Msg
pageSubscriptions page =
case page of
Monitor subModel ->
Sub.map MonitorMsg (Monitor.subscriptions subModel)
Status subModel ->
Sub.map StatusMsg (Status.subscriptions subModel)
_ ->
Sub.none
-- UPDATE
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
applySession <|
case msg of
SetRoute route ->
-- Updates broser URL to requested route.
( model, Route.newUrl route, Session.none )
NewRoute route ->
-- Responds to new browser URL.
if model.session.routing then
setRoute route model
else
-- Skip once, but re-enable routing.
( model, Cmd.none, Session.EnableRouting )
UpdateSession (Ok persistent) ->
let
session =
model.session
in
( { model | session = { session | persistent = persistent } }
, Cmd.none
, Session.none
)
UpdateSession (Err error) ->
let
_ =
Debug.log "Error decoding session" error
in
( model, Cmd.none, Session.none )
MailboxNameInput name ->
( { model | mailboxName = name }, Cmd.none, Session.none )
ViewMailbox name ->
( { model | mailboxName = "" }
, Route.newUrl (Route.Mailbox name)
, Session.none
)
_ ->
updatePage msg model
{-| Delegates incoming messages to their respective sub-pages.
-}
updatePage : Msg -> Model -> ( Model, Cmd Msg, Session.Msg )
updatePage msg model =
let
-- Handles sub-model update by calling toUpdate with subMsg & subModel, then packing the
-- updated sub-model back into model.page.
modelUpdate toPage toMsg subUpdate subMsg subModel =
let
( newModel, subCmd, sessionMsg ) =
subUpdate model.session subMsg subModel
in
( { model | page = toPage newModel }, Cmd.map toMsg subCmd, sessionMsg )
in
case ( msg, model.page ) of
( HomeMsg subMsg, Home subModel ) ->
modelUpdate Home HomeMsg Home.update subMsg subModel
( MailboxMsg subMsg, Mailbox subModel ) ->
modelUpdate Mailbox MailboxMsg Mailbox.update subMsg subModel
( MonitorMsg subMsg, Monitor subModel ) ->
modelUpdate Monitor MonitorMsg Monitor.update subMsg subModel
( StatusMsg subMsg, Status subModel ) ->
modelUpdate Status StatusMsg Status.update subMsg subModel
( _, _ ) ->
-- Disregard messages destined for the wrong page.
( model, Cmd.none, Session.none )
setRoute : Route -> Model -> ( Model, Cmd Msg, Session.Msg )
setRoute route model =
case route of
Route.Unknown hash ->
( model, Cmd.none, Session.SetFlash ("Unknown route requested: " ++ hash) )
Route.Home ->
( { model | page = Home Home.init }
, Ports.windowTitle "Inbucket"
, Session.none
)
Route.Mailbox name ->
( { model | page = Mailbox (Mailbox.init name Nothing) }
, Cmd.map MailboxMsg (Mailbox.load name)
, Session.none
)
Route.Message mailbox id ->
( { model | page = Mailbox (Mailbox.init mailbox (Just id)) }
, Cmd.map MailboxMsg (Mailbox.load mailbox)
, Session.none
)
Route.Monitor ->
( { model | page = Monitor Monitor.init }
, Ports.windowTitle "Inbucket Monitor"
, Session.none
)
Route.Status ->
( { model | page = Status Status.init }
, Cmd.batch
[ Ports.windowTitle "Inbucket Status"
, Cmd.map StatusMsg (Status.load)
]
, Session.none
)
applySession : ( Model, Cmd Msg, Session.Msg ) -> ( Model, Cmd Msg )
applySession ( model, cmd, sessionMsg ) =
let
session =
Session.update sessionMsg model.session
newModel =
{ model | session = session }
in
if session.persistent == model.session.persistent then
-- No change
( newModel, cmd )
else
( newModel
, Cmd.batch [ cmd, Ports.storeSession session.persistent ]
)
-- VIEW
view : Model -> Html Msg
view model =
let
mailbox =
case model.page of
Mailbox subModel ->
subModel.name
_ ->
""
controls =
{ viewMailbox = ViewMailbox
, mailboxOnInput = MailboxNameInput
, mailboxValue = model.mailboxName
, recentOptions = model.session.persistent.recentMailboxes
, recentActive = mailbox
}
frame =
Page.frame controls model.session
in
case model.page of
Home subModel ->
Html.map HomeMsg (Home.view model.session subModel)
|> frame Page.Other
Mailbox subModel ->
Html.map MailboxMsg (Mailbox.view model.session subModel)
|> frame Page.Mailbox
Monitor subModel ->
Html.map MonitorMsg (Monitor.view model.session subModel)
|> frame Page.Monitor
Status subModel ->
Html.map StatusMsg (Status.view model.session subModel)
|> frame Page.Status
-- MAIN
main : Program Value Model Msg
main =
Navigation.programWithFlags (Route.fromLocation >> NewRoute)
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}

42
ui/src/Page/Home.elm Normal file
View File

@@ -0,0 +1,42 @@
module Page.Home exposing (Model, Msg, init, update, view)
import Html exposing (..)
import Html.Attributes exposing (..)
import Data.Session as Session exposing (Session)
-- MODEL --
type alias Model =
{}
init : Model
init =
{}
-- UPDATE --
type Msg
= Msg
update : Session -> Msg -> Model -> ( Model, Cmd Msg, Session.Msg )
update session msg model =
( model, Cmd.none, Session.none )
-- VIEW --
view : Session -> Model -> Html Msg
view session model =
div [ id "page" ]
[ h1 [] [ text "Inbucket" ]
, text "This is the home page"
]

216
ui/src/Page/Mailbox.elm Normal file
View File

@@ -0,0 +1,216 @@
module Page.Mailbox exposing (Model, Msg, init, load, update, view)
import Data.Message as Message exposing (Message)
import Data.MessageHeader as MessageHeader exposing (MessageHeader)
import Data.Session as Session exposing (Session)
import Json.Decode as Decode exposing (Decoder)
import Html exposing (..)
import Html.Attributes exposing (class, classList, href, id, placeholder, target)
import Html.Events exposing (..)
import Http exposing (Error)
import HttpUtil
import Ports
import Route exposing (Route)
inbucketBase : String
inbucketBase =
""
-- MODEL --
type alias Model =
{ name : String
, selected : Maybe String
, headers : List MessageHeader
, message : Maybe Message
}
init : String -> Maybe String -> Model
init name id =
Model name id [] Nothing
load : String -> Cmd Msg
load name =
Cmd.batch
[ Ports.windowTitle (name ++ " - Inbucket")
, getMailbox name
]
-- UPDATE --
type Msg
= ClickMessage String
| ViewMessage String
| DeleteMessage Message
| DeleteMessageResult (Result Http.Error ())
| NewMailbox (Result Http.Error (List MessageHeader))
| NewMessage (Result Http.Error Message)
update : Session -> Msg -> Model -> ( Model, Cmd Msg, Session.Msg )
update session msg model =
case msg of
ClickMessage id ->
( { model | selected = Just id }
, Cmd.batch
[ Route.newUrl (Route.Message model.name id)
, getMessage model.name id
]
, Session.DisableRouting
)
ViewMessage id ->
( { model | selected = Just id }
, getMessage model.name id
, Session.AddRecent model.name
)
DeleteMessage msg ->
deleteMessage model msg
DeleteMessageResult (Ok _) ->
( model, Cmd.none, Session.none )
DeleteMessageResult (Err err) ->
( model, Cmd.none, Session.SetFlash (HttpUtil.errorString err) )
NewMailbox (Ok headers) ->
let
newModel =
{ model | headers = headers }
in
case model.selected of
Nothing ->
( newModel, Cmd.none, Session.AddRecent model.name )
Just id ->
-- Recurse to select message id.
update session (ViewMessage id) newModel
NewMailbox (Err err) ->
( model, Cmd.none, Session.SetFlash (HttpUtil.errorString err) )
NewMessage (Ok msg) ->
( { model | message = Just msg }, Cmd.none, Session.none )
NewMessage (Err err) ->
( model, Cmd.none, Session.SetFlash (HttpUtil.errorString err) )
getMailbox : String -> Cmd Msg
getMailbox name =
let
url =
inbucketBase ++ "/api/v1/mailbox/" ++ name
in
Http.get url (Decode.list MessageHeader.decoder)
|> Http.send NewMailbox
deleteMessage : Model -> Message -> ( Model, Cmd Msg, Session.Msg )
deleteMessage model msg =
let
url =
inbucketBase ++ "/api/v1/mailbox/" ++ msg.mailbox ++ "/" ++ msg.id
cmd =
HttpUtil.delete url
|> Http.send DeleteMessageResult
in
( { model
| message = Nothing
, selected = Nothing
, headers = List.filter (\x -> x.id /= msg.id) model.headers
}
, cmd
, Session.none
)
getMessage : String -> String -> Cmd Msg
getMessage mailbox id =
let
url =
inbucketBase ++ "/api/v1/mailbox/" ++ mailbox ++ "/" ++ id
in
Http.get url Message.decoder
|> Http.send NewMessage
-- VIEW --
view : Session -> Model -> Html Msg
view session model =
div [ id "page", class "mailbox" ]
[ aside [ id "message-list" ] [ viewMailbox model ]
, main_ [ id "message" ] [ viewMessage model ]
]
viewMailbox : Model -> Html Msg
viewMailbox model =
div [] (List.map (viewHeader model) (List.reverse model.headers))
viewHeader : Model -> MessageHeader -> Html Msg
viewHeader mailbox msg =
div
[ classList
[ ( "message-list-entry", True )
, ( "selected", mailbox.selected == Just msg.id )
, ( "unseen", not msg.seen )
]
, onClick (ClickMessage msg.id)
]
[ div [ class "subject" ] [ text msg.subject ]
, div [ class "from" ] [ text msg.from ]
, div [ class "date" ] [ text msg.date ]
]
viewMessage : Model -> Html Msg
viewMessage model =
case model.message of
Just message ->
div []
[ div [ class "button-bar" ]
[ button [ class "danger", onClick (DeleteMessage message) ] [ text "Delete" ]
, a
[ href
(inbucketBase
++ "/mailbox/"
++ message.mailbox
++ "/"
++ message.id
++ "/source"
)
, target "_blank"
]
[ button [] [ text "Source" ] ]
]
, dl [ id "message-header" ]
[ dt [] [ text "From:" ]
, dd [] [ text message.from ]
, dt [] [ text "To:" ]
, dd [] (List.map text message.to)
, dt [] [ text "Date:" ]
, dd [] [ text message.date ]
, dt [] [ text "Subject:" ]
, dd [] [ text message.subject ]
]
, article [] [ text message.body.text ]
]
Nothing ->
text ""

88
ui/src/Page/Monitor.elm Normal file
View File

@@ -0,0 +1,88 @@
module Page.Monitor exposing (Model, Msg, init, subscriptions, update, view)
import Data.MessageHeader as MessageHeader exposing (MessageHeader)
import Data.Session as Session exposing (Session)
import Json.Decode exposing (decodeString)
import Html exposing (..)
import Html.Attributes exposing (..)
import Html.Events as Events
import Route
import WebSocket
-- MODEL --
type alias Model =
{ messages : List MessageHeader }
init : Model
init =
{ messages = [] }
-- SUBSCRIPTIONS --
subscriptions : Model -> Sub Msg
subscriptions model =
WebSocket.listen "ws://192.168.1.10:3000/api/v1/monitor/messages"
(decodeString MessageHeader.decoder >> NewMessage)
-- UPDATE --
type Msg
= NewMessage (Result String MessageHeader)
| OpenMessage MessageHeader
update : Session -> Msg -> Model -> ( Model, Cmd Msg, Session.Msg )
update session msg model =
case msg of
NewMessage (Ok msg) ->
( { model | messages = msg :: model.messages }, Cmd.none, Session.none )
NewMessage (Err err) ->
( model, Cmd.none, Session.SetFlash err )
OpenMessage msg ->
( model
, Route.newUrl (Route.Message msg.mailbox msg.id)
, Session.none
)
-- VIEW --
view : Session -> Model -> Html Msg
view session model =
div [ id "page" ]
[ h1 [] [ text "Monitor" ]
, p [] [ text "Messages will be listed here shortly after delivery." ]
, table [ id "monitor" ]
[ thead []
[ th [] [ text "Date" ]
, th [ class "desktop" ] [ text "From" ]
, th [] [ text "Mailbox" ]
, th [] [ text "Subject" ]
]
, tbody [] (List.map viewMessage model.messages)
]
]
viewMessage : MessageHeader -> Html Msg
viewMessage message =
tr [ Events.onClick (OpenMessage message) ]
[ td [] [ text message.date ]
, td [ class "desktop" ] [ text message.from ]
, td [] [ text message.mailbox ]
, td [] [ text message.subject ]
]

400
ui/src/Page/Status.elm Normal file
View File

@@ -0,0 +1,400 @@
module Page.Status exposing (Model, Msg, init, load, subscriptions, update, view)
import Data.Metrics as Metrics exposing (Metrics)
import Data.Session as Session exposing (Session)
import Filesize
import Html exposing (..)
import Html.Attributes exposing (..)
import Http exposing (Error)
import HttpUtil
import Sparkline exposing (sparkline, Point, DataSet, Size)
import Svg.Attributes as SvgAttrib
import Time exposing (Time)
-- MODEL --
type alias Model =
{ metrics : Maybe Metrics
, xCounter : Float
, sysMem : Metric
, heapSize : Metric
, heapUsed : Metric
, heapObjects : Metric
, goRoutines : Metric
, webSockets : Metric
, smtpConnOpen : Metric
, smtpConnTotal : Metric
, smtpReceivedTotal : Metric
, smtpErrorsTotal : Metric
, smtpWarnsTotal : Metric
, retentionDeletesTotal : Metric
, retainedCount : Metric
, retainedSize : Metric
}
type alias Metric =
{ label : String
, value : Int
, formatter : Int -> String
, graph : DataSet -> Html Msg
, history : DataSet
, minutes : Int
}
init : Model
init =
{ metrics = Nothing
, xCounter = 60
, sysMem = Metric "System Memory" 0 Filesize.format graphZero initDataSet 10
, heapSize = Metric "Heap Size" 0 Filesize.format graphZero initDataSet 10
, heapUsed = Metric "Heap Used" 0 Filesize.format graphZero initDataSet 10
, heapObjects = Metric "Heap # Objects" 0 fmtInt graphZero initDataSet 10
, goRoutines = Metric "Goroutines" 0 fmtInt graphZero initDataSet 10
, webSockets = Metric "Open WebSockets" 0 fmtInt graphZero initDataSet 10
, smtpConnOpen = Metric "Open Connections" 0 fmtInt graphZero initDataSet 10
, smtpConnTotal = Metric "Total Connections" 0 fmtInt graphChange initDataSet 60
, smtpReceivedTotal = Metric "Messages Received" 0 fmtInt graphChange initDataSet 60
, smtpErrorsTotal = Metric "Messages Errors" 0 fmtInt graphChange initDataSet 60
, smtpWarnsTotal = Metric "Messages Warns" 0 fmtInt graphChange initDataSet 60
, retentionDeletesTotal = Metric "Retention Deletes" 0 fmtInt graphChange initDataSet 60
, retainedCount = Metric "Stored Messages" 0 fmtInt graphZero initDataSet 60
, retainedSize = Metric "Store Size" 0 Filesize.format graphZero initDataSet 60
}
initDataSet : DataSet
initDataSet =
List.range 0 59
|> List.map (\x -> ( toFloat (x), 0 ))
load : Cmd Msg
load =
getMetrics
-- SUBSCRIPTIONS --
subscriptions : Model -> Sub Msg
subscriptions model =
Time.every (10 * Time.second) Tick
-- UPDATE --
type Msg
= NewMetrics (Result Http.Error Metrics)
| Tick Time
update : Session -> Msg -> Model -> ( Model, Cmd Msg, Session.Msg )
update session msg model =
case msg of
NewMetrics (Ok metrics) ->
( updateMetrics metrics model, Cmd.none, Session.none )
NewMetrics (Err err) ->
( model, Cmd.none, Session.SetFlash (HttpUtil.errorString err) )
Tick time ->
( model, getMetrics, Session.ClearFlash )
{-| Update all metrics in Model; increment xCounter.
-}
updateMetrics : Metrics -> Model -> Model
updateMetrics metrics model =
let
x =
model.xCounter
in
{ model
| metrics = Just metrics
, xCounter = x + 1
, sysMem = updateLocalMetric model.sysMem x metrics.sysMem
, heapSize = updateLocalMetric model.heapSize x metrics.heapSize
, heapUsed = updateLocalMetric model.heapUsed x metrics.heapUsed
, heapObjects = updateLocalMetric model.heapObjects x metrics.heapObjects
, goRoutines = updateLocalMetric model.goRoutines x metrics.goRoutines
, webSockets = updateLocalMetric model.webSockets x metrics.webSockets
, smtpConnOpen = updateLocalMetric model.smtpConnOpen x metrics.smtpConnOpen
, smtpConnTotal =
updateRemoteTotal
model.smtpConnTotal
metrics.smtpConnTotal
metrics.smtpConnHist
, smtpReceivedTotal =
updateRemoteTotal
model.smtpReceivedTotal
metrics.smtpReceivedTotal
metrics.smtpReceivedHist
, smtpErrorsTotal =
updateRemoteTotal
model.smtpErrorsTotal
metrics.smtpErrorsTotal
metrics.smtpErrorsHist
, smtpWarnsTotal =
updateRemoteTotal
model.smtpWarnsTotal
metrics.smtpWarnsTotal
metrics.smtpWarnsHist
, retentionDeletesTotal =
updateRemoteTotal
model.retentionDeletesTotal
metrics.retentionDeletesTotal
metrics.retentionDeletesHist
, retainedCount =
updateRemoteMetric
model.retainedCount
metrics.retainedCount
metrics.retainedCountHist
, retainedSize =
updateRemoteMetric
model.retainedSize
metrics.retainedSize
metrics.retainedSizeHist
}
{-| Update a single Metric, with history tracked locally.
-}
updateLocalMetric : Metric -> Float -> Int -> Metric
updateLocalMetric metric x value =
{ metric
| value = value
, history =
(Maybe.withDefault [] (List.tail metric.history))
++ [ ( x, (toFloat value) ) ]
}
{-| Update a single Metric, with history tracked on server.
-}
updateRemoteMetric : Metric -> Int -> List Int -> Metric
updateRemoteMetric metric value history =
{ metric
| value = value
, history =
history
|> zeroPadList
|> List.indexedMap (\x y -> ( toFloat x, toFloat y ))
}
{-| Update a single Metric, with history tracked on server. Sparkline will chart changes to the
total instead of its absolute value.
-}
updateRemoteTotal : Metric -> Int -> List Int -> Metric
updateRemoteTotal metric value history =
{ metric
| value = value
, history =
history
|> zeroPadList
|> changeList
|> List.indexedMap (\x y -> ( toFloat x, toFloat y ))
}
getMetrics : Cmd Msg
getMetrics =
Http.get "/debug/vars" Metrics.decoder
|> Http.send NewMetrics
-- VIEW --
view : Session -> Model -> Html Msg
view session model =
div [ id "page" ]
[ h1 [] [ text "Status" ]
, case model.metrics of
Nothing ->
div [] [ text "Loading metrics..." ]
Just metrics ->
div []
[ framePanel "General Metrics"
[ viewMetric model.sysMem
, viewMetric model.heapSize
, viewMetric model.heapUsed
, viewMetric model.heapObjects
, viewMetric model.goRoutines
, viewMetric model.webSockets
]
, framePanel "SMTP Metrics"
[ viewMetric model.smtpConnOpen
, viewMetric model.smtpConnTotal
, viewMetric model.smtpReceivedTotal
, viewMetric model.smtpErrorsTotal
, viewMetric model.smtpWarnsTotal
]
, framePanel "Storage Metrics"
[ viewMetric model.retentionDeletesTotal
, viewMetric model.retainedCount
, viewMetric model.retainedSize
]
]
]
viewMetric : Metric -> Html Msg
viewMetric metric =
div [ class "metric" ]
[ div [ class "label" ] [ text metric.label ]
, div [ class "value" ] [ text (metric.formatter metric.value) ]
, div [ class "graph" ]
[ metric.graph metric.history
, text ("(" ++ toString metric.minutes ++ "min)")
]
]
viewLiveMetric : String -> (Int -> String) -> Int -> Html a -> Html a
viewLiveMetric label formatter value graph =
div [ class "metric" ]
[ div [ class "label" ] [ text label ]
, div [ class "value" ] [ text (formatter value) ]
, div [ class "graph" ]
[ graph
, text "(10min)"
]
]
graphNull : Html a
graphNull =
div [] []
graphSize : Size
graphSize =
( 180, 16, 0, 0 )
areaStyle : Sparkline.Param a -> Sparkline.Param a
areaStyle =
Sparkline.Style
[ SvgAttrib.fill "rgba(50,100,255,0.3)"
, SvgAttrib.stroke "rgba(50,100,255,1.0)"
, SvgAttrib.strokeWidth "1.0"
]
barStyle : Sparkline.Param a -> Sparkline.Param a
barStyle =
Sparkline.Style
[ SvgAttrib.fill "rgba(50,200,50,0.7)"
]
zeroStyle : Sparkline.Param a -> Sparkline.Param a
zeroStyle =
Sparkline.Style
[ SvgAttrib.stroke "rgba(0,0,0,0.2)"
, SvgAttrib.strokeWidth "1.0"
]
{-| Bar graph to be used with updateRemoteTotal metrics (change instead of absolute values).
-}
graphChange : DataSet -> Html a
graphChange data =
let
-- Used with Domain to stop sparkline forgetting about zero; continue scrolling graph.
x =
case List.head data of
Nothing ->
0
Just point ->
Tuple.first point
in
sparkline graphSize
[ Sparkline.Bar 2.5 data |> barStyle
, Sparkline.ZeroLine |> zeroStyle
, Sparkline.Domain [ ( x, 0 ), ( x, 1 ) ]
]
{-| Zero based area graph, for charting absolute values relative to 0.
-}
graphZero : DataSet -> Html a
graphZero data =
let
-- Used with Domain to stop sparkline forgetting about zero; continue scrolling graph.
x =
case List.head data of
Nothing ->
0
Just point ->
Tuple.first point
in
sparkline graphSize
[ Sparkline.Area data |> areaStyle
, Sparkline.ZeroLine |> zeroStyle
, Sparkline.Domain [ ( x, 0 ), ( x, 1 ) ]
]
framePanel : String -> List (Html a) -> Html a
framePanel name html =
div [ class "metric-panel" ]
[ h2 [] [ text name ]
, div [ class "metrics" ] html
]
-- UTILS --
{-| Compute difference between each Int in numbers.
-}
changeList : List Int -> List Int
changeList numbers =
let
tail =
List.tail numbers |> Maybe.withDefault []
in
List.map2 (-) tail numbers
{-| Pad the front of a list with 0s to make it at least 60 elements long.
-}
zeroPadList : List Int -> List Int
zeroPadList numbers =
let
needed =
60 - List.length numbers
in
if needed > 0 then
(List.repeat needed 0) ++ numbers
else
numbers
{-| Format an Int with thousands separators.
-}
fmtInt : Int -> String
fmtInt n =
let
-- thousands recursively inserts thousands separators.
thousands str =
if String.length str <= 3 then
str
else
(thousands (String.slice 0 -3 str)) ++ "," ++ (String.right 3 str)
in
thousands (toString n)

13
ui/src/Ports.elm Normal file
View File

@@ -0,0 +1,13 @@
port module Ports exposing (onSessionChange, storeSession, windowTitle)
import Data.Session exposing (Persistent)
import Json.Encode exposing (Value)
port onSessionChange : (Value -> msg) -> Sub msg
port storeSession : Persistent -> Cmd msg
port windowTitle : String -> Cmd msg

84
ui/src/Route.elm Normal file
View File

@@ -0,0 +1,84 @@
module Route exposing (Route(..), fromLocation, href, modifyUrl, newUrl)
import Html exposing (Attribute)
import Html.Attributes as Attr
import Navigation exposing (Location)
import UrlParser as Url exposing ((</>), Parser, parseHash, s, string)
type Route
= Unknown String
| Home
| Mailbox String
| Message String String
| Monitor
| Status
matcher : Parser (Route -> a) a
matcher =
Url.oneOf
[ Url.map Home (s "")
, Url.map Message (s "m" </> string </> string)
, Url.map Mailbox (s "m" </> string)
, Url.map Monitor (s "monitor")
, Url.map Status (s "status")
]
routeToString : Route -> String
routeToString page =
let
pieces =
case page of
Unknown _ ->
[]
Home ->
[]
Mailbox name ->
[ "m", name ]
Message mailbox id ->
[ "m", mailbox, id ]
Monitor ->
[ "monitor" ]
Status ->
[ "status" ]
in
"/#/" ++ String.join "/" pieces
-- PUBLIC HELPERS
href : Route -> Attribute msg
href route =
Attr.href (routeToString route)
modifyUrl : Route -> Cmd msg
modifyUrl =
routeToString >> Navigation.modifyUrl
newUrl : Route -> Cmd msg
newUrl =
routeToString >> Navigation.newUrl
fromLocation : Location -> Route
fromLocation location =
if String.isEmpty location.hash then
Home
else
case parseHash matcher location of
Nothing ->
Unknown location.hash
Just route ->
route

123
ui/src/Views/Page.elm Normal file
View File

@@ -0,0 +1,123 @@
module Views.Page exposing (ActivePage(..), frame)
import Data.Session as Session exposing (Session)
import Html exposing (..)
import Html.Attributes
exposing
( attribute
, class
, classList
, href
, id
, placeholder
, type_
, selected
, value
)
import Html.Events as Events
import Route exposing (Route)
type ActivePage
= Other
| Mailbox
| Monitor
| Status
type alias FrameControls msg =
{ viewMailbox : String -> msg
, mailboxOnInput : String -> msg
, mailboxValue : String
, recentOptions : List String
, recentActive : String
}
frame : FrameControls msg -> Session -> ActivePage -> Html msg -> Html msg
frame controls session page content =
div [ id "app" ]
[ header []
[ ul [ class "navbar", attribute "role" "navigation" ]
[ li [ id "navbar-brand" ] [ a [ Route.href Route.Home ] [ text "@ inbucket" ] ]
, navbarLink page Route.Monitor [ text "Monitor" ]
, navbarLink page Route.Status [ text "Status" ]
, navbarRecent page controls
, li [ id "navbar-mailbox" ]
[ form [ Events.onSubmit (controls.viewMailbox controls.mailboxValue) ]
[ input
[ type_ "text"
, placeholder "mailbox"
, value controls.mailboxValue
, Events.onInput controls.mailboxOnInput
]
[]
]
]
]
, div [] [ text ("Status: " ++ session.flash) ]
]
, div [ id "navbg" ] [ text "" ]
, content
, footer []
[ div [ id "footer" ]
[ a [ href "https://www.inbucket.org" ] [ text "Inbucket" ]
, text " is an open source projected hosted at "
, a [ href "https://github.com/jhillyerd/inbucket" ] [ text "GitHub" ]
, text "."
]
]
]
navbarLink : ActivePage -> Route -> List (Html a) -> Html a
navbarLink page route linkContent =
li [ classList [ ( "navbar-active", isActive page route ) ] ]
[ a [ Route.href route ] linkContent ]
{-| Renders list of recent mailboxes, selecting the currently active mailbox.
-}
navbarRecent : ActivePage -> FrameControls msg -> Html msg
navbarRecent page controls =
let
recentItemLink mailbox =
a [ Route.href (Route.Mailbox mailbox) ] [ text mailbox ]
active =
page == Mailbox
-- Navbar tab title, is current mailbox when active.
title =
if active then
controls.recentActive
else
"Recent Mailboxes"
-- Items to show in recent list, doesn't include active mailbox.
items =
if active then
List.tail controls.recentOptions |> Maybe.withDefault []
else
controls.recentOptions
in
li
[ id "navbar-recent"
, classList [ ( "navbar-dropdown", True ), ( "navbar-active", active ) ]
]
[ span [] [ text title ]
, div [ class "navbar-dropdown-content" ] (List.map recentItemLink items)
]
isActive : ActivePage -> Route -> Bool
isActive page route =
case ( page, route ) of
( Monitor, Route.Monitor ) ->
True
( Status, Route.Status ) ->
True
_ ->
False

33
ui/src/index.js Normal file
View File

@@ -0,0 +1,33 @@
import './main.css';
import { Main } from './Main.elm';
import registerServiceWorker from './registerServiceWorker';
var app = Main.embed(document.getElementById('root'), sessionObject());
app.ports.storeSession.subscribe(function (session) {
localStorage.session = JSON.stringify(session);
});
app.ports.windowTitle.subscribe(function (title) {
document.title = title;
});
window.addEventListener("storage", function (event) {
if (event.storageArea === localStorage && event.key === "session") {
app.ports.onSessionChange.send(sessionObject());
}
}, false);
function sessionObject() {
var s = localStorage.session;
try {
if (s) {
return JSON.parse(s);
}
} catch (error) {
console.error(error);
}
return null;
}
registerServiceWorker();

377
ui/src/main.css Normal file
View File

@@ -0,0 +1,377 @@
/** GLOBAL */
:root {
--bg-color: #fff;
--primary-color: #333;
--low-color: #666;
--high-color: #337ab7;
--border-color: #ddd;
--placeholder-color: #9f9f9f;
--selected-color: #eee;
}
html, body, div, span, applet, object, iframe,
h1, h2, h3, h4, h5, h6, p, blockquote, pre,
a, abbr, acronym, address, big, cite, code,
del, dfn, em, img, ins, kbd, q, s, samp,
small, strike, strong, sub, sup, tt, var,
b, u, i, center,
dl, dt, dd, ol, ul, li,
fieldset, form, label, legend,
table, caption, tbody, tfoot, thead, tr, th, td,
article, aside, canvas, details, embed,
figure, figcaption, footer, header, hgroup,
menu, nav, output, ruby, section, summary,
time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
vertical-align: baseline;
}
body {
background-color: var(--bg-color);
}
body, input, table {
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.43;
color: var(--primary-color);
}
::placeholder {
color: var(--placeholder-color);
opacity: 1;
}
/** APP */
#app {
display: grid;
justify-content: center;
grid-gap: 20px;
grid-template:
"lpad head rpad" auto
"lpad page rpad" 1fr
"foot foot foot" auto / minmax(20px, auto) 1fr minmax(20px, auto);
height: 100vh;
}
@media (max-width: 999px) {
#app {
grid-template:
"head head head" auto
"lpad page rpad" 1fr
"foot foot foot" auto / 1px 1fr 1px;
height: auto;
}
.desktop {
display: none;
}
}
header {
grid-area: head;
}
#page {
grid-area: page;
}
footer {
background-color: var(--selected-color);
display: flex;
justify-content: center;
grid-area: foot;
}
#footer {
margin: 10px auto;
}
h1 {
font-size: 30px;
font-weight: 500;
}
/** NAV BAR */
.navbar,
#navbg {
height: 50px;
}
.navbar {
display: flex;
line-height: 20px;
list-style: none;
padding: 0;
text-shadow: 0 -1px 0 rgba(0,0,0,0.2);
}
.navbar li {
color: #9d9d9d;
}
.navbar a,
.navbar-dropdown span {
color: #9d9d9d;
display: inline-block;
padding: 15px;
text-decoration: none;
}
li.navbar-active {
background-color: #080808;
}
li.navbar-active a,
li.navbar-active span,
.navbar a:hover {
color: #ffffff;
}
#navbar-brand {
font-size: 18px;
margin-left: -15px;
}
#navbar-recent {
margin: 0 auto;
}
#navbar-mailbox {
padding: 8px 0 !important;
}
#navbar-mailbox input {
border: 1px solid var(--border-color);
border-radius: 4px;
padding: 5px 10px;
margin-top: 1px;
width: 250px;
}
.navbar-dropdown-content {
background-color: var(--bg-color);
border: 1px solid var(--border-color);
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0,0,0,.05);
display: none;
min-width: 160px;
position: absolute;
text-shadow: none;
z-index: 1;
}
.navbar-dropdown:hover .navbar-dropdown-content {
display: block;
}
.navbar-dropdown-content a {
color: var(--primary-color) !important;
display: block;
padding: 5px 15px;
}
.navbar-dropdown-content a:hover {
background-color: var(--selected-color);
}
#navbg {
background-color: #222;
background-image: linear-gradient(to bottom, #3c3c3c 0, #222 100%);
grid-column: 1 / 4;
grid-row: 1;
width: 100%;
z-index: -1;
}
/** BUTTONS */
.button-bar button {
background-color: #337ab7;
background-image: linear-gradient(to bottom, #337ab7 0, #265a88 100%);
border: none;
border-radius: 4px;
color: #fff;
font-size: 12px;
font-style: normal;
font-weight: 400;
height: 30px;
margin: 0 4px 0 0;
padding: 5px;
text-align: center;
text-decoration: none;
text-shadow: 0 -1px 0 rgba(0,0,0,0.2);
width: 8em;
}
.button-bar button.danger {
background-color: #d9534f;
background-image: linear-gradient(to bottom, #d9534f 0, #c12e2a 100%);
}
/** MAILBOX */
.mailbox {
display: grid;
grid-area: page;
grid-gap: 20px;
grid-template-areas:
"list"
"mesg";
justify-self: center;
}
@media (min-width: 1000px) {
.mailbox {
grid-template-columns:
minmax(200px, 300px)
minmax(650px, 1000px);
grid-template-areas:
"list mesg";
grid-template-rows: 1fr;
}
}
#message-list {
grid-area: list;
}
.message-list-entry {
border-color: var(--border-color);
border-width: 1px;
border-style: none solid solid solid;
cursor: pointer;
padding: 5px 8px;
}
.message-list-entry.selected {
background-color: var(--selected-color);
}
.message-list-entry:first-child {
border-style: solid;
}
.message-list-entry .subject {
color: var(--high-color);
}
.message-list-entry.unseen .subject {
font-weight: bold;
}
.message-list-entry .from,
.message-list-entry .date {
color: var(--low-color);
font-size: 85%;
}
/** MESSAGE */
#message {
grid-area: mesg;
}
#message-header {
border: 1px solid var(--border-color);
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0,0,0,.05);
padding: 10px;
margin: 10px 0;
}
#message-header dt {
color: var(--low-color);
font-weight: bold;
}
#message-header dd {
color: var(--low-color);
padding-left: 10px;
}
@media (min-width: 1000px) {
#message-header {
display: grid;
grid-template: auto / 5em 1fr;
}
#message-header dt {
grid-column: 1;
text-align: right;
}
#message-header dd {
grid-column: 2;
}
}
/** STATUS */
.metric-panel {
border: 1px solid var(--border-color);
border-radius: 4px;
box-shadow: 0 1px 2px rgba(0,0,0,.05);
margin: 20px 0;
}
.metric-panel h2 {
background-image: linear-gradient(to bottom,#f5f5f5 0,#e8e8e8 100%);
font-size: 16px;
font-weight: 500;
padding: 10px;
}
.metric-panel .metrics {
padding: 7px 10px;
}
.metric-panel .metric {
display: flex;
flex-wrap: wrap;
margin: 3px 0;
}
.metric .label {
flex-basis: 15em;
font-weight: 700;
}
.metric .value {
flex-basis: 15em;
}
.metric .graph {
flex-basis: 25em;
}
/** MONITOR **/
#monitor {
border-collapse: collapse;
width: 100%;
}
#monitor th {
border-bottom: 2px solid var(--border-color);
text-align: left;
padding: 5px;
}
#monitor td {
border-bottom: 1px solid var(--border-color);
font-size: 12px;
padding: 5px;
}
#monitor tr:hover {
background-color: var(--selected-color);
cursor: pointer;
}

View File

@@ -0,0 +1,108 @@
// In production, we register a service worker to serve assets from local cache.
// 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 the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
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 default function register() {
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);
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/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (!isLocalhost) {
// Is not local host. Just register service worker
registerValidSW(swUrl);
} else {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} 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.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// 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.
if (
response.status === 404 ||
response.headers.get('content-type').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);
}
})
.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();
});
}
}

22
ui/tests/Tests.elm Normal file
View File

@@ -0,0 +1,22 @@
module Tests exposing (..)
import Test exposing (..)
import Expect
-- Check out http://package.elm-lang.org/packages/elm-community/elm-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!"
]

17
ui/tests/elm-package.json Normal file
View File

@@ -0,0 +1,17 @@
{
"version": "1.0.0",
"summary": "Test Suites",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [
".",
"../src"
],
"exposed-modules": [],
"dependencies": {
"elm-lang/core": "5.0.0 <= v < 6.0.0",
"elm-community/elm-test": "4.0.0 <= v < 5.0.0",
"elm-lang/html": "2.0.0 <= v < 3.0.0"
},
"elm-version": "0.18.0 <= v < 0.19.0"
}