Use strict TypeScript, enable TSLint, update all types to work in strict mode.

This commit is contained in:
Jason Miller
2018-03-29 15:42:07 -04:00
parent 9977e5b8c6
commit 5e6500d196
16 changed files with 396 additions and 265 deletions

9
.editorconfig Normal file
View File

@@ -0,0 +1,9 @@
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

18
global.d.ts vendored
View File

@@ -0,0 +1,18 @@
declare const __webpack_public_path__: string;
interface NodeModule {
hot: any;
}
declare namespace JSX {
interface Element { }
interface IntrinsicElements { div: any; }
}
declare module 'preact-i18n';
declare module 'preact-material-components-drawer';
declare module 'material-radial-progress';
declare module 'classnames' {
export default function classnames(...args: any[]): string;
}

View File

@@ -11,6 +11,10 @@
"eslintConfig": { "eslintConfig": {
"extends": "eslint-config-developit", "extends": "eslint-config-developit",
"rules": { "rules": {
"indent": [
2,
2
],
"react/prefer-stateless-function": 0 "react/prefer-stateless-function": 0
} }
}, },
@@ -37,6 +41,8 @@
"eslint": "^4.18.2", "eslint": "^4.18.2",
"eslint-config-developit": "^1.1.1", "eslint-config-developit": "^1.1.1",
"extract-text-webpack-plugin": "^4.0.0-beta.0", "extract-text-webpack-plugin": "^4.0.0-beta.0",
"fork-ts-checker-notifier-webpack-plugin": "^0.4.0",
"fork-ts-checker-webpack-plugin": "^0.4.1",
"html-webpack-plugin": "^3.0.6", "html-webpack-plugin": "^3.0.6",
"if-env": "^1.0.4", "if-env": "^1.0.4",
"mini-css-extract-plugin": "^0.2.0", "mini-css-extract-plugin": "^0.2.0",
@@ -48,6 +54,9 @@
"script-ext-html-webpack-plugin": "^2.0.0", "script-ext-html-webpack-plugin": "^2.0.0",
"style-loader": "^0.20.3", "style-loader": "^0.20.3",
"ts-loader": "^4.0.1", "ts-loader": "^4.0.1",
"tslint": "^5.9.1",
"tslint-config-semistandard": "^7.0.0",
"tslint-react": "^3.5.1",
"typescript": "^2.7.2", "typescript": "^2.7.2",
"typescript-loader": "^1.1.3", "typescript-loader": "^1.1.3",
"typings-for-css-modules-loader": "^1.7.0", "typings-for-css-modules-loader": "^1.7.0",

View File

@@ -1,5 +1,5 @@
import { h, Component } from 'preact'; import { h, Component } from 'preact';
import { updater, toggle, When } from '../../lib/util'; import { When, bind } from '../../lib/util';
import Fab from '../fab'; import Fab from '../fab';
import Header from '../header'; import Header from '../header';
// import Drawer from 'async!../drawer'; // import Drawer from 'async!../drawer';
@@ -8,20 +8,20 @@ import Home from '../home';
import * as style from './style.scss'; import * as style from './style.scss';
type Props = { type Props = {
url?: String url?: string
} };
type FileObj = { export type FileObj = {
id: any, id: number,
data: any, data?: string,
error: Error | DOMError | String, error?: Error | DOMError | String,
file: File, file: File,
loading: Boolean loading: boolean
}; };
type State = { type State = {
showDrawer: Boolean, showDrawer: boolean,
showFab: Boolean, showFab: boolean,
files: FileObj[] files: FileObj[]
}; };
@@ -34,62 +34,73 @@ export default class App extends Component<Props, State> {
files: [] files: []
}; };
loadFile = (file: File) => { enableDrawer = false;
let fileObj = {
@bind
openDrawer() {
this.setState({ showDrawer: true });
}
@bind
closeDrawer() {
this.setState({ showDrawer: false });
}
@bind
toggleDrawer() {
this.setState({ showDrawer: !this.state.showDrawer });
}
@bind
openFab() {
this.setState({ showFab: true });
}
@bind
closeFab() {
this.setState({ showFab: false });
}
@bind
toggleFab() {
this.setState({ showFab: !this.state.showFab });
}
@bind
loadFile(file: File) {
let fileObj: FileObj = {
id: ++counter, id: ++counter,
file, file,
error: null, error: undefined,
loading: true, loading: true,
data: null data: undefined
}; };
this.setState({ this.setState({
files: [fileObj] files: [fileObj]
}); });
let fr = new FileReader(); let done = () => {
// fr.readAsArrayBuffer();
fr.onerror = () => {
let files = this.state.files.slice(); let files = this.state.files.slice();
files.splice(0, files.indexOf(fileObj), { files[files.indexOf(fileObj)] = Object.assign({}, fileObj, {
...fileObj,
error: fr.error, error: fr.error,
loading: false loading: false,
}); data: fr.result
this.setState({ files });
};
fr.onloadend = () => {
let files = this.state.files.slice();
files.splice(0, files.indexOf(fileObj), {
...fileObj,
data: fr.result,
loading: false
}); });
this.setState({ files }); this.setState({ files });
}; };
let fr = new FileReader();
fr.onerror = fr.onloadend = done;
fr.readAsDataURL(file); fr.readAsDataURL(file);
}; }
enableDrawer = false; render({ url }: Props, { showDrawer, showFab, files }: State) {
openDrawer = updater(this, 'showDrawer', true);
closeDrawer = updater(this, 'showDrawer', false);
toggleDrawer = updater(this, 'showDrawer', toggle);
openFab = updater(this, 'showFab', true);
closeFab = updater(this, 'showFab', false);
toggleFab = updater(this, 'showFab', toggle);
render({ url }, { showDrawer, showFab, files }) {
if (showDrawer) this.enableDrawer = true; if (showDrawer) this.enableDrawer = true;
if (showFab===true) showFab = files.length>0; if (showFab === true) showFab = files.length > 0;
return ( return (
<div id="app" class={style.app}> <div id="app" class={style.app}>
<Fab showing={showFab} /> <Fab showing={showFab} />
<Header toggleDrawer={this.toggleDrawer} loadFile={this.loadFile} /> <Header class={style.header} toggleDrawer={this.toggleDrawer} loadFile={this.loadFile} />
{/* Avoid loading & rendering the drawer until the first time it is shown. */} {/* Avoid loading & rendering the drawer until the first time it is shown. */}
<When value={showDrawer}> <When value={showDrawer}>
@@ -103,9 +114,6 @@ export default class App extends Component<Props, State> {
<div class={style.content}> <div class={style.content}>
<Home files={files} /> <Home files={files} />
</div> </div>
{/* This ends up in the body when prerendered, which makes it load async. */}
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
</div> </div>
); );
} }

View File

@@ -1,51 +0,0 @@
import { h, Component } from 'preact';
import MdlDrawer from 'preact-material-components-drawer';
import 'preact-material-components/Drawer/style.css';
import List from 'preact-material-components/List';
// import 'preact-material-components/List/style.css';
import { Text } from 'preact-i18n';
import style from './style';
export default class Drawer extends Component {
state = {
rendered: false
};
setRendered = () => {
this.setState({ rendered: true });
};
render({ showing, openDrawer, closeDrawer }, { rendered }) {
if (showing && !rendered) {
setTimeout(this.setRendered, 20);
showing = false;
}
return (
<MdlDrawer open={showing} onOpen={openDrawer} onClose={closeDrawer}>
<MdlDrawer.Header class="mdc-theme--primary-bg">
<img class={style.logo} alt="logo" src="/assets/icon.png" />
</MdlDrawer.Header>
<MdlDrawer.Content class={style.list}>
<List>
<List.LinkItem href="/">
<List.ItemIcon>verified_user</List.ItemIcon>
<Text id="SIGN_IN">Sign In</Text>
</List.LinkItem>
<List.LinkItem href="/register">
<List.ItemIcon>account_circle</List.ItemIcon>
<Text id="REGISTER">Register</Text>
</List.LinkItem>
</List>
</MdlDrawer.Content>
<div class={style.bottom}>
<List.LinkItem href="/preferences">
<List.ItemIcon>settings</List.ItemIcon>
<Text id="PREFERENCES">Preferences</Text>
</List.LinkItem>
</div>
</MdlDrawer>
);
}
}

View File

@@ -0,0 +1,63 @@
import { h, Component } from 'preact';
import MdlDrawer from 'preact-material-components-drawer';
import 'preact-material-components/Drawer/style.css';
import List from 'preact-material-components/List';
// import 'preact-material-components/List/style.css';
import { Text } from 'preact-i18n';
import * as style from './style.scss';
import { bind } from '../../lib/util';
type Props = {
showing: boolean,
openDrawer(): void,
closeDrawer(): void
};
type State = {
rendered: boolean
};
export default class Drawer extends Component<Props, State> {
state: State = {
rendered: false
};
@bind
setRendered() {
this.setState({ rendered: true });
}
render({ showing, openDrawer, closeDrawer }: Props, { rendered }: State) {
if (showing && !rendered) {
setTimeout(this.setRendered, 20);
showing = false;
}
return (
<MdlDrawer open={showing} onOpen={openDrawer} onClose={closeDrawer}>
<MdlDrawer.Header class="mdc-theme--primary-bg">
<img class={style.logo} alt="logo" src="/assets/icon.png" />
</MdlDrawer.Header>
<MdlDrawer.Content>
<List>
<List.LinkItem href="/">
<List.ItemIcon>verified_user</List.ItemIcon>
<Text id="SIGN_IN">Sign In</Text>
</List.LinkItem>
<List.LinkItem href="/register">
<List.ItemIcon>account_circle</List.ItemIcon>
<Text id="REGISTER">Register</Text>
</List.LinkItem>
</List>
</MdlDrawer.Content>
<div class={style.bottom}>
<List.LinkItem href="/preferences">
<List.ItemIcon>settings</List.ItemIcon>
<Text id="PREFERENCES">Preferences</Text>
</List.LinkItem>
</div>
</MdlDrawer>
);
}
}

View File

@@ -1,4 +1,5 @@
import { h, Component } from 'preact'; import { h, Component } from 'preact';
import { bind } from '../../lib/util';
import Icon from 'preact-material-components/Icon'; import Icon from 'preact-material-components/Icon';
import 'preact-material-components/Icon/style.css'; import 'preact-material-components/Icon/style.css';
import Fab from 'preact-material-components/Fab'; import Fab from 'preact-material-components/Fab';
@@ -8,6 +9,7 @@ import * as style from './style.scss';
type Props = { type Props = {
showing: boolean showing: boolean
}; };
type State = { type State = {
loading: boolean loading: boolean
}; };
@@ -17,17 +19,23 @@ export default class AppFab extends Component<Props, State> {
loading: false loading: false
}; };
handleClick = () => { @bind
setLoading(loading: boolean) {
this.setState({ loading });
}
@bind
handleClick() {
console.log('TODO: Save the file to disk.'); console.log('TODO: Save the file to disk.');
this.setState({ loading: true }); this.setState({ loading: true });
setTimeout( () => { setTimeout(() => {
this.setState({ loading: false }); this.setState({ loading: false });
}, 1000); }, 1000);
}; }
render({ showing }, { loading }) { render({ showing }: Props, { loading }: State) {
return ( return (
<Fab ripple secondary exited={showing===false} class={style.fab} onClick={this.handleClick}> <Fab ripple secondary exited={showing === false} class={style.fab} onClick={this.handleClick}>
{ loading ? ( { loading ? (
<RadialProgress primary class={style.progress} /> <RadialProgress primary class={style.progress} />
) : ( ) : (

View File

@@ -2,43 +2,45 @@ import { h, Component } from 'preact';
import Toolbar from 'preact-material-components/Toolbar'; import Toolbar from 'preact-material-components/Toolbar';
import cx from 'classnames'; import cx from 'classnames';
import * as style from './style.scss'; import * as style from './style.scss';
import { bind } from '../../lib/util';
type Props = { type Props = {
toggleDrawer?(), 'class'?: string,
showHeader?(), showHeader?: boolean,
showFab?(), toggleDrawer?(): void,
loadFile?(File) showFab?(): void,
loadFile(f: File): void
}; };
type State = { type State = {};
};
export default class Header extends Component<Props, State> { export default class Header extends Component<Props, State> {
input: HTMLInputElement; input?: HTMLInputElement;
setInputRef = c => { @bind
this.input = c; setInputRef(c?: Element) {
}; this.input = c as HTMLInputElement;
}
upload = () => { @bind
this.input.click(); upload() {
}; this.input!.click();
}
handleFiles = () => { @bind
let files = this.input.files; handleFiles() {
if (files.length) { let files = this.input!.files;
if (files && files.length) {
this.props.loadFile(files[0]); this.props.loadFile(files[0]);
} }
}; }
render({ toggleDrawer, showHeader, showFab }) { render({ class: c, toggleDrawer, showHeader = false, showFab }: Props) {
return ( return (
<Toolbar fixed class={cx(style.toolbar, 'inert', showHeader===false && style.minimal)}> <Toolbar fixed class={cx(c, style.toolbar, 'inert', !showHeader && style.minimal)}>
<Toolbar.Row> <Toolbar.Row>
<Toolbar.Title class={style.title}> <Toolbar.Title class={style.title}>
<img class={style.logo} src="/assets/icon.png" /> <Toolbar.Icon title="Upload" ripple onClick={this.upload}>file_upload</Toolbar.Icon>
<Toolbar.Icon ripple onClick={this.upload}>file_upload</Toolbar.Icon>
</Toolbar.Title> </Toolbar.Title>
<Toolbar.Section align-end> <Toolbar.Section align-end>
<Toolbar.Icon ripple onClick={toggleDrawer}>menu</Toolbar.Icon> <Toolbar.Icon ripple onClick={toggleDrawer}>menu</Toolbar.Icon>

View File

@@ -3,12 +3,12 @@ import { h, Component } from 'preact';
// import Switch from 'preact-material-components/Switch'; // import Switch from 'preact-material-components/Switch';
// import 'preact-material-components/Switch/style.css'; // import 'preact-material-components/Switch/style.css';
import * as style from './style.scss'; import * as style from './style.scss';
import { FileObj } from '../app';
type Props = { type Props = {
files: { files: FileObj[]
data: any
}[]
}; };
type State = { type State = {
active: boolean active: boolean
}; };
@@ -19,14 +19,14 @@ export default class Home extends Component<Props, State> {
}; };
componentDidMount() { componentDidMount() {
setTimeout( () => { setTimeout(() => {
this.setState({ active: true }); this.setState({ active: true });
}); });
} }
render({ files }, { active }) { render({ files }: Props, { active }: State) {
return ( return (
<div class={style.home+' '+(active ? style.active : '')}> <div class={style.home + ' ' + (active ? style.active : '')}>
{ files && files[0] && ( { files && files[0] && (
<img src={files[0].data} /> <img src={files[0].data} />
) } ) }

View File

@@ -1,18 +0,0 @@
import './style';
import './lib/fix-pmc';
import App from './components/app';
export default App;
if (typeof window!=='undefined') {
addEventListener('click', e => {
let { target } = e;
do {
if (target.nodeName === 'A') {
history.pushState(null, null, target.pathname);
e.preventDefault();
return false;
}
} while ((target = target.parentNode));
});
}

32
src/index.tsx Normal file
View File

@@ -0,0 +1,32 @@
import { h, render } from 'preact';
import './lib/fix-pmc';
import './style';
import App from './components/app';
// Find the outermost Element in our server-rendered HTML structure.
let root = document.querySelector('[prerender]') || undefined;
// "attach" the client-side rendering to it, updating the DOM in-place instead of replacing:
root = render(<App />, document.body, root);
// In production, this entire condition is removed.
if (process.env.NODE_ENV === 'development') {
// Enable support for React DevTools and some helpful console warnings:
require('preact/debug');
// When an update to any module is received, re-import the app and trigger a full re-render:
module.hot.accept('./components/app', () => {
import('./components/app').then(({ default: App }) => {
root = render(<App />, document.body, root);
});
});
} else if ('serviceWorker' in navigator && location.protocol === 'https:') {
addEventListener('load', () => {
navigator.serviceWorker.register(__webpack_public_path__ + 'sw.js');
});
}
/** @todo SSR */
// if (typeof module==='object') {
// module.exports = app;
// }

View File

@@ -1,19 +0,0 @@
import { Component } from 'preact';
export function updater(obj, property, value) {
return e => {
let update = {};
update[property] = typeof value === 'function' ? value(obj.state[property], e) : value;
obj.setState(update);
};
}
export const toggle = value => !value;
export class When extends Component {
state = { ready: !!this.props.value };
render({ value, children: [child] }, { ready }) {
if (value && !ready) this.setState({ ready: true });
return ready ? (typeof child === 'function' ? child() : child) : null;
}
}

39
src/lib/util.ts Normal file
View File

@@ -0,0 +1,39 @@
import { Component, ComponentProps } from 'preact';
type WhenProps = ComponentProps<When> & {
value: boolean,
children?: (JSX.Element | (() => JSX.Element))[]
};
type WhenState = {
ready: boolean
};
export class When extends Component<WhenProps, WhenState> {
state: WhenState = {
ready: !!this.props.value
};
render({ value, children = [] }: WhenProps, { ready }: WhenState) {
let child = children[0];
if (value && !ready) this.setState({ ready: true });
return ready ? (typeof child === 'function' ? child() : child) : null;
}
}
/**
* A decorator that binds values to their class instance.
* @example
* class C {
* @bind
* foo () {
* return this;
* }
* }
* let f = new C().foo;
* f() instanceof C; // true
*/
export function bind(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
descriptor.value = descriptor.value.bind(target);
return descriptor;
}

View File

@@ -1,16 +1,16 @@
{ {
"compileOnSave": false, "compileOnSave": false,
"compilerOptions": { "compilerOptions": {
"strict": true,
"target": "es2017", "target": "es2017",
"module": "esnext", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "node",
"experimentalDecorators": true,
"noUnusedLocals": true,
"sourceMap": true, "sourceMap": true,
"jsx": "react", "jsx": "react",
"jsxFactory": "h", "jsxFactory": "h",
"allowJs": true, "allowJs": false,
"baseUrl": ".", "baseUrl": "."
"paths": {
"async!*": ["*"]
}
} }
} }

16
tslint.json Normal file
View File

@@ -0,0 +1,16 @@
{
"extends": [
"tslint-config-semistandard",
"tslint-react"
],
"rules": {
"quotemark": [true, "single", "jsx-double", "avoid-escape"],
"no-use-before-declare": false,
"no-floating-promises": false,
"space-before-function-paren": [true, false],
"jsx-boolean-value": [true, "never"],
"jsx-no-multiline-js": false,
"jsx-no-bind": true,
"jsx-no-lambda": true
}
}

View File

@@ -1,6 +1,8 @@
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
const webpack = require('webpack'); const webpack = require('webpack');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
const ForkTsCheckerNotifierWebpackPlugin = require('fork-ts-checker-notifier-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin'); const CleanWebpackPlugin = require('clean-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin'); const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const MiniCssExtractPlugin = require('mini-css-extract-plugin');
@@ -54,6 +56,10 @@ module.exports = function(_, env) {
loader: 'ts-loader', loader: 'ts-loader',
// Don't transpile anything in node_modules: // Don't transpile anything in node_modules:
exclude: nodeModules, exclude: nodeModules,
options: {
// Offload type checking to ForkTsCheckerWebpackPlugin for better performance:
transpileOnly: true
}
}, },
{ {
test: /\.(tsx?|jsx?)$/, test: /\.(tsx?|jsx?)$/,
@@ -112,6 +118,15 @@ module.exports = function(_, env) {
] ]
}, },
plugins: [ plugins: [
// Runs tslint & type checking in a worker pool
new ForkTsCheckerWebpackPlugin({
tslint: true,
// wait for type chec
async: !isProd,
formatter: 'codeframe'
}),
new ForkTsCheckerNotifierWebpackPlugin({ excludeWarnings: true }),
// Pretty progressbar showing build progress: // Pretty progressbar showing build progress:
new ProgressBarPlugin({ new ProgressBarPlugin({
format: '\u001b[90m\u001b[44mBuild\u001b[49m\u001b[39m [:bar] \u001b[32m\u001b[1m:percent\u001b[22m\u001b[39m (:elapseds) \u001b[2m:msg\u001b[22m', format: '\u001b[90m\u001b[44mBuild\u001b[49m\u001b[39m [:bar] \u001b[32m\u001b[1m:percent\u001b[22m\u001b[39m (:elapseds) \u001b[2m:msg\u001b[22m',