Compare commits

...

6 Commits

47 changed files with 18648 additions and 4 deletions

16
Cargo.lock generated
View File

@ -211,6 +211,8 @@ dependencies = [
"libsqlite3-sys",
"rocket",
"rocket_contrib",
"serde",
"serde_json",
]
[[package]]
@ -978,6 +980,20 @@ name = "serde"
version = "1.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5317f7588f0a5078ee60ef675ef96735a1442132dc645eb1d12c018620ed8cd3"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.114"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2a0be94b04690fbaed37cddffc5c134bf537c8e3329d53e982fe04c374978f8e"
dependencies = [
"proc-macro2 1.0.18",
"quote 1.0.7",
"syn 1.0.34",
]
[[package]]
name = "serde_json"

View File

@ -13,4 +13,6 @@ anyhow = "1.0"
chrono = "0.4"
diesel = { version = "1.4.5", features = ["sqlite"] }
dotenv = "0.15.0"
libsqlite3-sys = { version = "0.18.0", features = ["bundled"] }
libsqlite3-sys = { version = "0.18.0", features = ["bundled"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

41
frontend/.eslintrc.js Normal file
View File

@ -0,0 +1,41 @@
module.exports = {
env: {
browser: true
},
plugins: ["@typescript-eslint"],
extends: [
"eslint:recommended",
"plugin:@typescript-eslint/eslint-recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"plugin:react/recommended",
"plugin:react-hooks/recommended",
"plugin:prettier/recommended",
"prettier/@typescript-eslint",
"prettier/react"
],
parser: "@typescript-eslint/parser",
parserOptions: {
ecmaFeatures: {
jsx: true
},
project: "./tsconfig.eslint.json",
},
rules: {
"react/no-unknown-property": ["error", { ignore: ["class"] }],
},
settings: {
react: {
pragma: "h",
version: "detect"
},
},
overrides: [
{
files: ["*.js"],
rules: {
"@typescript-eslint/explicit-function-return-type": "off",
}
}
]
};

3
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
node_modules
/build
/*.log

4
frontend/.prettierignore Normal file
View File

@ -0,0 +1,4 @@
package.json
package-lock.json
yarn.lock
build

1
frontend/.prettierrc Normal file
View File

@ -0,0 +1 @@
tabWidth: 4

19
frontend/README.md Normal file
View File

@ -0,0 +1,19 @@
# frontend
## CLI Commands
* `npm install`: Installs dependencies
* `npm run dev`: Run a development, HMR server
* `npm run serve`: Run a production-like server
* `npm run build`: Production-ready build
* `npm run lint`: Pass TypeScript files using TSLint
* `npm run test`: Run Jest and Enzyme with
[`enzyme-adapter-preact-pure`](https://github.com/preactjs/enzyme-adapter-preact-pure) for
your tests
For detailed explanation on how things work, checkout the [CLI Readme](https://github.com/developit/preact-cli/blob/master/README.md).

11
frontend/jest.config.js Normal file
View File

@ -0,0 +1,11 @@
module.exports = {
preset: "jest-preset-preact",
setupFiles: [
"<rootDir>/src/tests/__mocks__/setupTests.js",
"<rootDir>/src/tests/__mocks__/browserMocks.js"
],
testURL: "http://localhost:8080",
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/src/tests/__mocks__/fileMocks.js",
}
}

17858
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

58
frontend/package.json Normal file
View File

@ -0,0 +1,58 @@
{
"private": true,
"name": "frontend",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"build": "preact build",
"serve": "sirv build --port 8080 --cors --single",
"dev": "preact watch",
"lint": "eslint 'src/**/*.{js,jsx,ts,tsx}'",
"test": "jest ./tests"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.{css,md,scss}": "prettier --write",
"*.{js,jsx,ts,tsx}": "eslint --fix"
},
"eslintIgnore": [
"build/*"
],
"dependencies": {
"moment": "^2.27.0",
"preact": "^10.3.1",
"preact-jsx-chai": "^3.0.0",
"preact-markup": "^2.0.0",
"preact-render-to-string": "^5.1.4",
"preact-router": "^3.2.1",
"react-charts": "^2.0.0-beta.7"
},
"devDependencies": {
"@teamsupercell/typings-for-css-modules-loader": "^2.2.0",
"@types/enzyme": "^3.10.5",
"@types/jest": "^25.1.2",
"@types/webpack-env": "^1.15.1",
"@typescript-eslint/eslint-plugin": "^2.25.0",
"@typescript-eslint/parser": "^2.25.0",
"css-loader": "^3.5.3",
"enzyme": "^3.11.0",
"enzyme-adapter-preact-pure": "^2.2.0",
"eslint": "^6.8.0",
"eslint-config-prettier": "^6.10.1",
"eslint-plugin-prettier": "^3.1.2",
"eslint-plugin-react": "^7.19.0",
"eslint-plugin-react-hooks": "^3.0.0",
"husky": "^4.2.1",
"jest": "^25.1.0",
"jest-preset-preact": "^1.0.0",
"lint-staged": "^10.0.7",
"preact-cli": "^3.0.0-rc.16",
"prettier": "^1.19.1",
"sirv-cli": "^1.0.0-next.3",
"typescript": "^3.7.5"
}
}

47
frontend/preact.config.js Normal file
View File

@ -0,0 +1,47 @@
import { resolve } from "path";
export default {
/**
* Function that mutates the original webpack config.
* Supports asynchronous changes when a promise is returned (or it's an async function).
*
* @param {object} config - original webpack config.
* @param {object} env - options passed to the CLI.
* @param {WebpackConfigHelpers} helpers - object with useful helpers for working with the webpack config.
* @param {object} options - this is mainly relevant for plugins (will always be empty in the config), default to an empty object
**/
webpack(config, env, helpers, options) {
config.module.rules[4].use.splice(1, 0, {
loader: "@teamsupercell/typings-for-css-modules-loader",
options: {
banner:
"// This file is automatically generated from your CSS. Any edits will be overwritten.",
disableLocalsExport: true
}
});
// Use any `index` file, not just index.js
config.resolve.alias["preact-cli-entrypoint"] = resolve(
process.cwd(),
"src",
"index"
);
config.resolve.alias["react"] = "preact/compat";
config.resolve.alias["react-dom"] = "preact/compat";
if (config.devServer){
config.devServer.proxy = [{
// proxy requests matching a pattern:
path: '/api/**',
// where to proxy to:
target: 'http://localhost:8000',
// optionally change Origin: and Host: headers to match target:
changeOrigin: true,
changeHost: true,
}];
}
}
};

File diff suppressed because one or more lines are too long

5
frontend/src/.babelrc Normal file
View File

@ -0,0 +1,5 @@
{
"presets": [
"preact-cli/babel"
]
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 626 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.8 KiB

View File

@ -0,0 +1,33 @@
import { FunctionalComponent, h } from "preact";
import { Route, Router, RouterOnChangeArgs } from "preact-router";
import Home from "../routes/home";
import Dataset from "../routes/dataset";
import NotFoundPage from '../routes/notfound';
import Header from "./header";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
if ((module as any).hot) {
// tslint:disable-next-line:no-var-requires
require("preact/debug");
}
const App: FunctionalComponent = () => {
let currentUrl: string;
const handleRoute = (e: RouterOnChangeArgs) => {
currentUrl = e.url;
};
return (
<div id="app">
<Header />
<Router onChange={handleRoute}>
<Route path="/" component={Home} />
<Route path="/view/:name" component={Dataset} />
<NotFoundPage default />
</Router>
</div>
);
};
export default App;

View File

@ -0,0 +1,18 @@
import { FunctionalComponent, h } from "preact";
import { Link } from "preact-router/match";
import * as style from "./style.css";
const Header: FunctionalComponent = () => {
return (
<header class={style.header}>
<h1>datalog viewer thing</h1>
<nav>
<Link activeClassName={style.active} href="/">
Home
</Link>
</nav>
</header>
);
};
export default Header;

View File

@ -0,0 +1,48 @@
.header {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 56px;
padding: 0;
background: #673AB7;
box-shadow: 0 0 5px rgba(0, 0, 0, 0.5);
z-index: 50;
}
.header h1 {
float: left;
margin: 0;
padding: 0 15px;
font-size: 24px;
line-height: 56px;
font-weight: 400;
color: #FFF;
}
.header nav {
float: right;
font-size: 100%;
}
.header nav a {
display: inline-block;
height: 56px;
line-height: 56px;
padding: 0 15px;
min-width: 50px;
text-align: center;
background: rgba(255,255,255,0);
text-decoration: none;
color: #FFF;
will-change: background-color;
}
.header nav a:hover,
.header nav a:active {
background: rgba(0,0,0,0.2);
}
.header nav a.active {
background: rgba(0,0,0,0.4);
}

View File

@ -0,0 +1,11 @@
// This file is automatically generated from your CSS. Any edits will be overwritten.
declare namespace StyleCssNamespace {
export interface IStyleCss {
active: string;
header: string;
}
}
declare const StyleCssModule: StyleCssNamespace.IStyleCss;
export = StyleCssModule;

4
frontend/src/index.js Normal file
View File

@ -0,0 +1,4 @@
import "./style/index.css";
import App from "./components/app.tsx";
export default App;

View File

@ -0,0 +1,21 @@
{
"name": "frontend",
"short_name": "frontend",
"start_url": "/",
"display": "standalone",
"orientation": "portrait",
"background_color": "#fff",
"theme_color": "#673ab8",
"icons": [
{
"src": "/assets/icons/android-chrome-192x192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "/assets/icons/android-chrome-512x512.png",
"type": "image/png",
"sizes": "512x512"
}
]
}

View File

@ -0,0 +1,86 @@
import { Component, h } from "preact";
import { useEffect, useState } from "preact/hooks";
import { Chart } from 'react-charts'
import * as style from "./style.css";
import moment from "moment";
export interface DatasetProps {
name: string,
}
export interface ApiDatapoint {
id: number,
devicename: string,
value: number,
timestamp: string,
}
export interface Datapoint {
y: number,
x: Date,
}
interface Series{
label: string,
data: Datapoint[],
}
export interface DatasetState {
label: string,
data: Series[] | undefined,
width: number,
height: number,
}
const axes = [
{primary: true, type: 'time', position: 'bottom' },
{type: 'linear', position: 'left'}
];
class Dataset extends Component<DatasetProps, DatasetState> {
constructor(){
super();
this.state = { data: undefined, label: "w", width: 0, height: 0 };
}
async componentDidMount() {
this.updateWindowDimensions();
window.addEventListener('resize', this.updateWindowDimensions);
var devicesResponse = await fetch(`/api/device/${this.props.name}`);
var apiData = await devicesResponse.json() as ApiDatapoint[];
var data = apiData.map((d) => {return {x: moment(d.timestamp).toDate(), y: d.value} as Datapoint});
this.setState({ data: [{data: data, label: "datapoint"}]});
}
// Lifecycle: Called just before our component will be destroyed
componentWillUnmount() {
// stop when not renderable
window.removeEventListener('resize', this.updateWindowDimensions);
}
updateWindowDimensions() {
this.setState({ width: window.innerWidth - 30, height: window.innerHeight - 150 }); // crudely account for heading / padding. yikes
}
render() {
if (this.state.data){
//var deviceLinks = this.state.data.map((d) => <div>{d.y},{d.x}</div>)
return <div class={style.profile}>
{this.props.name}
<div style={{width: this.state.width, height: this.state.height}}>
<Chart data={this.state.data} axes={axes} tooltip/>
</div>
</div>;
}
return <div class={style.profile}>
Loading data for {this.props.name}
</div>;
}
}
export default Dataset;

1
frontend/src/routes/dataset/libs.d.ts vendored Normal file
View File

@ -0,0 +1 @@
declare module 'react-charts'

View File

@ -0,0 +1,5 @@
.profile {
padding: 56px 20px;
min-height: 100%;
width: 100%;
}

View File

@ -0,0 +1,10 @@
// This file is automatically generated from your CSS. Any edits will be overwritten.
declare namespace StyleCssNamespace {
export interface IStyleCss {
profile: string;
}
}
declare const StyleCssModule: StyleCssNamespace.IStyleCss;
export = StyleCssModule;

View File

@ -0,0 +1,35 @@
import { Component, h } from "preact";
import { Link } from "preact-router/match";
import * as style from "./style.css";
export interface HomeProps {
}
export interface HomeState {
devices: string[],
}
class Home extends Component<HomeProps, HomeState> {
constructor(){
super();
this.state = { devices: [] };
}
async componentDidMount() {
var devicesResponse = await fetch('/api/devices');
this.setState({ devices: await devicesResponse.json() as string[] })
}
// Lifecycle: Called just before our component will be destroyed
componentWillUnmount() {
// stop when not renderable
}
render() {
var deviceLinks = this.state.devices.map((d) => <div><Link href={`/view/${d}`}>{d}</Link></div>)
return <div class={style.home}><span>{deviceLinks}</span></div>;
}
}
export default Home;

View File

@ -0,0 +1,5 @@
.home {
padding: 56px 20px;
min-height: 100%;
width: 100%;
}

10
frontend/src/routes/home/style.css.d.ts vendored Normal file
View File

@ -0,0 +1,10 @@
// This file is automatically generated from your CSS. Any edits will be overwritten.
declare namespace StyleCssNamespace {
export interface IStyleCss {
home: string;
}
}
declare const StyleCssModule: StyleCssNamespace.IStyleCss;
export = StyleCssModule;

View File

@ -0,0 +1,15 @@
import { FunctionalComponent, h } from "preact";
import { Link } from 'preact-router/match';
import * as style from "./style.css";
const Notfound: FunctionalComponent = () => {
return (
<div class={style.notfound}>
<h1>Error 404</h1>
<p>That page doesn't exist.</p>
<Link href="/"><h4>Back to Home</h4></Link>
</div>
);
};
export default Notfound;

View File

@ -0,0 +1,4 @@
.notfound {
padding: 0 5%;
margin: 100px 0;
}

View File

@ -0,0 +1,10 @@
// This file is automatically generated from your CSS. Any edits will be overwritten.
declare namespace StyleCssNamespace {
export interface IStyleCss {
notfound: string;
}
}
declare const StyleCssModule: StyleCssNamespace.IStyleCss;
export = StyleCssModule;

View File

@ -0,0 +1,20 @@
html, body {
height: 100%;
width: 100%;
padding: 0;
margin: 0;
background: #FAFAFA;
font-family: 'Helvetica Neue', arial, sans-serif;
font-weight: 400;
color: #444;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
* {
box-sizing: border-box;
}
#app {
height: 100%;
}

View File

@ -0,0 +1,21 @@
// Mock Browser API's which are not supported by JSDOM, e.g. ServiceWorker, LocalStorage
/**
* An example how to mock localStorage is given below 👇
*/
/*
// Mocks localStorage
const localStorageMock = (function() {
let store = {};
return {
getItem: (key) => store[key] || null,
setItem: (key, value) => store[key] = value.toString(),
clear: () => store = {}
};
})();
Object.defineProperty(window, 'localStorage', {
value: localStorageMock
}); */

View File

@ -0,0 +1,3 @@
// This fixed an error related to the CSS and loading gif breaking my Jest test
// See https://facebook.github.io/jest/docs/en/webpack.html#handling-static-assets
export default "test-file-stub";

View File

@ -0,0 +1,6 @@
import { configure } from "enzyme";
import Adapter from "enzyme-adapter-preact-pure";
configure({
adapter: new Adapter()
});

3
frontend/src/tests/declarations.d.ts vendored Normal file
View File

@ -0,0 +1,3 @@
// Enable enzyme adapter's integration with TypeScript
// See: https://github.com/preactjs/enzyme-adapter-preact-pure#usage-with-typescript
/// <reference types="enzyme-adapter-preact-pure" />

View File

@ -0,0 +1,12 @@
import { h } from "preact";
// See: https://github.com/preactjs/enzyme-adapter-preact-pure
import { shallow } from "enzyme";
import Header from "../components/header";
describe("Initial Test of the Header", () => {
test("Header renders 3 nav items", () => {
const context = shallow(<Header />);
expect(context.find("h1").text()).toBe("Preact App");
expect(context.find("Link").length).toBe(3);
});
});

View File

@ -0,0 +1,5 @@
// see https://github.com/typescript-eslint/typescript-eslint/issues/890
{
"extends": "./tsconfig.json",
"include": ["*.config.js", "src/**/*"]
}

57
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,57 @@
{
"compilerOptions": {
/* Basic Options */
"target": "ES5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
"module": "ESNext", /* Specify module code generation: 'none', commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation: */
"allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"jsxFactory": "h", /* Specify the JSX factory function to use when targeting react JSX emit, e.g. React.createElement or h. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
"esModuleInterop": true
},
"include": ["src/**/*.tsx", "src/**/*.ts"]
}

View File

@ -9,13 +9,20 @@ extern crate rocket_contrib;
#[macro_use]
extern crate anyhow;
#[macro_use]
extern crate serde;
extern crate chrono;
pub mod models;
pub mod schema;
use chrono::prelude::*;
use rocket::{http::RawStr, State};
use rocket::{
http::RawStr,
response::{NamedFile, Redirect},
State,
};
use std::{
collections::BTreeMap,
fmt::Display,
@ -35,6 +42,7 @@ use self::models::*;
#[database("sqlite_events")]
struct DbConn(diesel::SqliteConnection);
/*
#[get("/")]
fn index() -> Result<String, anyhow::Error> {
Ok(format!(
@ -42,6 +50,7 @@ fn index() -> Result<String, anyhow::Error> {
"aa"
))
}
*/
#[get("/log/<device_name>/<value>")]
fn log_new(device_name: &RawStr, value: &RawStr, conn: DbConn) -> Result<String, anyhow::Error> {
@ -75,10 +84,41 @@ fn log_get(device_name: &RawStr, conn: DbConn) -> Result<String, anyhow::Error>
Ok(lines)
}
#[get("/devices")]
fn devices_get(conn: DbConn) -> Result<String, anyhow::Error> {
use self::schema::events::dsl::*;
let devices = events
.select(devicename)
.distinct()
.load::<String>(&*conn)?;
Ok(serde_json::to_string(&devices)?)
}
#[get("/device/<name>")]
fn device_get(name: &RawStr, conn: DbConn) -> Result<String, anyhow::Error> {
use self::schema::events::dsl::*;
let results = events
.filter(devicename.eq(name.as_str()))
.load::<Event>(&*conn)?;
Ok(serde_json::to_string(&results)?)
}
#[catch(404)]
fn not_found() -> Option<NamedFile> {
NamedFile::open("frontend/build/index.html").ok()
}
fn main() {
rocket::ignite()
.attach(DbConn::fairing())
.mount("/", routes![index, log_new, log_get])
.mount(
"/",
rocket_contrib::serve::StaticFiles::from("frontend/build"),
)
.mount("/api", routes![log_new, log_get, devices_get, device_get])
.register(catchers![not_found])
.launch();
println!("after");

View File

@ -1,6 +1,7 @@
use super::schema::events;
use serde::Serialize;
#[derive(Queryable, Debug)]
#[derive(Queryable, Debug, Serialize)]
pub struct Event {
pub id: i32,
pub devicename: String,

94
static/index.html Normal file
View File

@ -0,0 +1,94 @@
<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v5.min.js"></script>
</head>
<body>
<p>Hello!</p>
<div id="scatter_area"></div>
<script>
let data = Object.assign(d3.csvParse(await FileAttachment("flights.csv").text(), d3.autoType), {y: "Flights"});
area = (data, x) => d3.area()
.curve(d3.curveStepAfter)
.x(d => x(d.date))
.y0(y(0))
.y1(d => y(d.value))
(data)
yAxis = (g, y) => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y).ticks(null, "s"))
.call(g => g.select(".domain").remove())
.call(g => g.select(".tick:last-of-type text").clone()
.attr("x", 3)
.attr("text-anchor", "start")
.attr("font-weight", "bold")
.text(data.y))
xAxis = (g, x) => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
y = d3.scaleLinear()
.domain([0, d3.max(data, d => d.value)]).nice()
.range([height - margin.bottom, margin.top])
x = d3.scaleUtc()
.domain(d3.extent(data, d => d.date))
.range([margin.left, width - margin.right])
margin = ({top: 20, right: 20, bottom: 30, left: 30})
height = 500
chart = {
const zoom = d3.zoom()
.scaleExtent([1, 32])
.extent([[margin.left, 0], [width - margin.right, height]])
.translateExtent([[margin.left, -Infinity], [width - margin.right, Infinity]])
.on("zoom", zoomed);
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height]);
const clip = DOM.uid("clip");
svg.append("clipPath")
.attr("id", clip.id)
.append("rect")
.attr("x", margin.left)
.attr("y", margin.top)
.attr("width", width - margin.left - margin.right)
.attr("height", height - margin.top - margin.bottom);
const path = svg.append("path")
.attr("clip-path", clip)
.attr("fill", "steelblue")
.attr("d", area(data, x));
const gx = svg.append("g")
.call(xAxis, x);
svg.append("g")
.call(yAxis, y);
svg.call(zoom)
.transition()
.duration(750)
.call(zoom.scaleTo, 4, [x(Date.UTC(2001, 8, 1)), 0]);
function zoomed() {
const xz = d3.event.transform.rescaleX(x);
path.attr("d", area(data, xz));
gx.call(xAxis, xz);
}
return svg.node();
}
</script>
</body>
</html>