frontend: initial

master
Lauren Liberda 2021-07-25 18:01:11 +02:00
parent f1dd5e5dc8
commit 9ddfb7eef5
16 changed files with 4460 additions and 120 deletions

2
.eslintignore Normal file
View File

@ -0,0 +1,2 @@
node_modules
dist

1
frontend/.gitignore vendored Normal file
View File

@ -0,0 +1 @@
generated

View File

@ -0,0 +1,16 @@
<table class='table is-fullwidth'>
<tbody>
<tr>
<th>name</th>
<td>{{name}}</td>
</tr>
<tr>
<th>notes</th>
<td>{{notes}}</td>
</tr>
<tr>
<th>ean13</th>
<td>{{ean13}}</td>
</tr>
</tbody>
</table>

View File

@ -0,0 +1,24 @@
<div class='table-container'>
<table class='table is-striped is-hoverable is-fullwidth'>
<thead>
<tr>
<th>Name</th>
<th>EAN-13</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{{#each nodes}}
<tr>
<td>{{name}}</td>
<td>{{ean13}}</td>
<td><button class='item-open-details button is-light is-small' data-id='{{id}}'>details</button></td>
</tr>
{{/each}}
</tbody>
</table>
</div>
<nav class='pagination' role='navigation' aria-label='pagination'>
<a class='pagination-previous' id='items-previous' {{#unless previousPage}}disabled{{/unless}} >previous</a>
<a class='pagination-next' id='items-next' {{#unless nextPage}}disabled{{/unless}}>next</a>
</nav>

View File

@ -0,0 +1 @@
<h1>Loading...</h1>

View File

@ -0,0 +1,17 @@
<div id='main' class='container'></div>
<div id='modal' class='modal'>
<div id='modal-background' class='modal-background'></div>
<div class='modal-card'>
<header class='modal-card-head'>
<p id='modal-title' class='modal-card-title'></p>
<button id='modal-close' class='delete' aria-label='close'></button>
</header>
<section id='modal-body' class='modal-card-body'>
<!-- Content ... -->
</section>
<footer class='modal-card-foot'>
</footer>
</div>
</div>

7
frontend/src/handlebars.d.ts vendored Normal file
View File

@ -0,0 +1,7 @@
declare module '*.hbs' {
interface main {
(values?: { [key: string]: any }): string;
}
var hbs: main;
export default hbs;
}

144
frontend/src/main.ts Normal file
View File

@ -0,0 +1,144 @@
import './style.scss';
import { Query } from './generated/graphql';
import root from './components/root.hbs';
import loading from './components/loading.hbs';
import itemList from './components/itemList.hbs';
import itemDetails from './components/itemDetails.hbs';
async function request<T = Query>(
query: string,
variables?: { [key: string]: any },
): Promise<T> {
return fetch('/api/graphql', {
method: 'POST',
body: JSON.stringify({ query, variables }),
headers: new Headers({
'Content-Type': 'application/json',
}),
})
.then((res) => res.json())
.then((res) => res.data);
}
const itemListCursors: (string | null)[] = [null];
async function loadItemList(cursor?: string | null) {
document.querySelector('#main')!.innerHTML = loading();
const loaded = await request(
`
query ($cursor: ID) {
itemList(cursor: $cursor) {
nodes {
id
ean13
name
}
cursor
hasNextPage
}
}
`,
{
cursor,
},
);
if (
loaded.itemList.cursor &&
!itemListCursors.includes(loaded.itemList.cursor)
) {
itemListCursors.push(loaded.itemList.cursor);
}
const hasPreviousPage = itemListCursors.length > 2;
document.querySelector('#main')!.innerHTML = itemList({
...loaded.itemList,
previousPage: hasPreviousPage,
nextPage: loaded.itemList.hasNextPage,
});
const itemsNext = document.querySelector('#items-next') as HTMLAnchorElement;
if (loaded.itemList.hasNextPage) {
itemsNext.addEventListener('click', () =>
loadItemList(loaded.itemList.cursor),
);
}
const itemsPrevious = document.querySelector(
'#items-previous',
) as HTMLAnchorElement;
if (hasPreviousPage) {
itemsPrevious.addEventListener('click', () => {
itemListCursors.pop();
loadItemList(itemListCursors[itemListCursors.length - 2]);
});
}
(
Array.from(
document.querySelectorAll('.item-open-details'),
) as HTMLButtonElement[]
).forEach((butt) =>
butt.addEventListener('click', () => showItemDetails(butt.dataset.id!)),
);
}
async function showModal(state: boolean = true) {
const cl = (document.querySelector('#modal') as HTMLDivElement).classList;
if (state) {
cl.add('is-active');
} else {
cl.remove('is-active');
}
}
async function showItemDetails(id: string) {
(document.querySelector('#modal-title') as HTMLParagraphElement).innerHTML =
'Item details';
(document.querySelector('#modal-body') as HTMLDivElement).innerHTML =
loading();
showModal(true);
const loaded = await request(
`
query ($id: ID!) {
item(id: $id) {
id
ean13
name
notes
parent {
id
ean13
name
}
ancestors {
id
ean13
name
}
children {
id
ean13
name
}
descendants {
id
ean13
name
}
}
}
`,
{
id,
},
);
(document.querySelector('#modal-body') as HTMLDivElement).innerHTML =
itemDetails(loaded.item!);
}
window.addEventListener('load', () => {
document.body.innerHTML = root();
['#modal-close', '#modal-background'].forEach((el) =>
(document.querySelector(el) as HTMLButtonElement).addEventListener(
'click',
() => showModal(false),
),
);
loadItemList();
});

2
frontend/src/style.scss Normal file
View File

@ -0,0 +1,2 @@
$family-sans-serif: sans-serif;
@import '~bulma/bulma';

73
frontend/tsconfig.json Normal file
View File

@ -0,0 +1,73 @@
{
"include": ["./src/**/*.ts"],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "esnext" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */,
"module": "esnext" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', 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": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each 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. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "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. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "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. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* 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. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* 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. */
/* Advanced Options */
"skipLibCheck": true /* Skip type checking of declaration files. */,
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}

6
gql-codegen.yml Normal file
View File

@ -0,0 +1,6 @@
overwrite: true
schema: './dist/schema.gql'
generates:
frontend/src/generated/graphql.ts:
plugins:
- 'typescript'

View File

@ -6,10 +6,16 @@
"license": "UNLICENSED",
"scripts": {
"prebuild": "rimraf dist",
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"build": "yarn build:backend && yarn build:gql && yarn build:frontend",
"build:frontend": "webpack build --mode production",
"build:backend": "nest build",
"build:gql": "yarn build:gql:backend && yarn build:gql:frontend",
"build:gql:backend": "ts-node scripts/generate-gql-sdl.ts",
"build:gql:frontend": "graphql-codegen --config gql-codegen.yml",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\" \"frontend/src/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:dev:frontend": "webpack watch --mode development",
"start:debug": "nest start --debug --watch",
"start:prod": "yarn migration:run && node dist/src/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
@ -20,6 +26,13 @@
"test:e2e": "jest --config ./test/jest-e2e.json",
"migration:run": "typeorm migration:run"
},
"browserslist": [
"> 10%",
"last 3 Firefox versions",
"last 3 Chrome versions",
"Firefox 60",
"not dead"
],
"dependencies": {
"@nestjs/common": "^7.6.15",
"@nestjs/config": "^1.0.0",
@ -38,24 +51,49 @@
"typeorm": "^0.2.34"
},
"devDependencies": {
"@babel/core": "^7.14.8",
"@babel/preset-env": "^7.14.8",
"@graphql-codegen/cli": "1.21.7",
"@graphql-codegen/typescript": "1.23.0",
"@nestjs/cli": "^7.6.0",
"@nestjs/schematics": "^7.3.0",
"@nestjs/serve-static": "^2.2.2",
"@nestjs/testing": "^7.6.15",
"@types/dotenv": "^8.2.0",
"@types/jest": "^26.0.22",
"@types/node": "^14.14.36",
"@typescript-eslint/eslint-plugin": "^4.19.0",
"@typescript-eslint/parser": "^4.19.0",
"babel-loader": "^8.2.2",
"bulma": "^0.9.3",
"css-loader": "^6.2.0",
"eslint": "^7.22.0",
"eslint-config-prettier": "^8.1.0",
"eslint-plugin-prettier": "^3.3.1",
"extract-text-webpack-plugin": "^4.0.0-beta.0",
"fastify-static": "^4.2.2",
"graphql": "^15.5.1",
"handlebars": "^4.7.7",
"handlebars-loader": "^1.7.1",
"html-webpack-plugin": "^5.3.2",
"jest": "^26.6.3",
"mini-css-extract-plugin": "^2.1.0",
"postcss": "^8.3.6",
"postcss-loader": "^6.1.1",
"postcss-preset-env": "^6.7.0",
"prettier": "^2.2.1",
"sass": "^1.35.2",
"sass-loader": "^12.1.0",
"source-map-loader": "^3.0.0",
"style-loader": "^3.2.1",
"ts-jest": "^26.5.4",
"ts-loader": "^8.0.18",
"ts-node": "^9.1.1",
"tsconfig-paths": "^3.9.0",
"typescript": "^4.2.3"
"typescript": "^4.2.3",
"webpack": "^5.46.0",
"webpack-cli": "^4.7.2",
"webpack-dev-server": "^3.11.2"
},
"jest": {
"moduleFileExtensions": [

View File

@ -0,0 +1,30 @@
import fs from 'fs';
import path from 'path';
import { NestFactory } from '@nestjs/core';
import {
FastifyAdapter,
NestFastifyApplication,
} from '@nestjs/platform-fastify';
import {
GraphQLSchemaBuilderModule,
GraphQLSchemaFactory,
} from '@nestjs/graphql';
import { printSchema } from 'graphql';
import { ItemsResolver } from '../src/items/items.resolver';
async function generateSchema() {
const app = await NestFactory.create<NestFastifyApplication>(
GraphQLSchemaBuilderModule,
new FastifyAdapter(),
);
await app.init();
const gqlSchemaFactory = app.get(GraphQLSchemaFactory);
const schema = await gqlSchemaFactory.create([ItemsResolver]);
fs.writeFileSync(
path.join(path.dirname(__dirname), 'dist', 'schema.gql'),
printSchema(schema),
);
}
generateSchema();

View File

@ -2,6 +2,7 @@ import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { GraphQLModule } from '@nestjs/graphql';
import { ConfigModule } from '@nestjs/config';
import { ServeStaticModule } from '@nestjs/serve-static';
import { getConnectionOptions } from 'typeorm';
import path from 'path';
import { ItemsModule } from './items/items.module';
@ -24,6 +25,9 @@ import { ItemsModule } from './items/items.module';
path: '/api/graphql',
autoSchemaFile: path.join(__dirname, 'schema.gql'),
}),
ServeStaticModule.forRoot({
rootPath: path.join(path.dirname(__dirname), 'frontend'),
}),
],
controllers: [],
providers: [],

70
webpack.config.js Normal file
View File

@ -0,0 +1,70 @@
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
cache: true,
entry: './frontend/src/main.ts',
output: {
path: path.resolve(__dirname, 'dist', 'frontend'),
filename: 'main.bundle.js',
},
module: {
rules: [
{
test: /\.ts$/,
exclude: /node_modules/,
use: [
{
loader: 'babel-loader',
options: {
presets: ['@babel/env'],
},
},
{
loader: 'ts-loader',
},
],
},
{
test: /\.hbs$/,
use: {
loader: 'handlebars-loader',
},
},
{
test: /\.scss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
},
{
loader: 'css-loader',
},
{
loader: 'postcss-loader',
options: {
postcssOptions: {
plugins: ['postcss-preset-env'],
},
},
},
{
loader: 'sass-loader',
options: {
sourceMap: true,
},
},
],
},
],
},
plugins: [
new HtmlWebpackPlugin({
title: 'metropolis',
}),
new MiniCssExtractPlugin({
filename: 'css/style.css',
}),
],
};

4139
yarn.lock

File diff suppressed because it is too large Load Diff