Merge pull request #9 from realModusOperandi/angular-port

Port frontend to angular
This commit is contained in:
Liam Westby 2018-02-06 22:57:01 -06:00 committed by GitHub
commit 38105a5e56
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
51 changed files with 14712 additions and 0 deletions

2
.gitignore vendored
View File

@ -11,3 +11,5 @@ build
/*/.settings/org.eclipse.wst.common.component
/*/.settings/org.eclipse.wst.common.project.facet.core.xml
/*/.settings/org.eclipse.buildship.core.prefs
/frontend/src/main/webapp/*
!/frontend/src/main/webapp/WEB-INF

12
frontend/.classpath Normal file
View File

@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src/main/java"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8/"/>
<classpathentry kind="con" path="org.eclipse.jst.j2ee.internal.web.container"/>
<classpathentry kind="con" path="org.eclipse.buildship.core.gradleclasspathcontainer">
<attributes>
<attribute name="org.eclipse.jst.component.nondependency" value=""/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="bin"/>
</classpath>

View File

@ -0,0 +1,59 @@
eclipse.preferences.version=1
editor_save_participant_org.eclipse.jdt.ui.postsavelistener.cleanup=true
org.eclipse.jdt.ui.ignorelowercasenames=true
org.eclipse.jdt.ui.importorder=java;javax;org;com;
org.eclipse.jdt.ui.javadoc=true
org.eclipse.jdt.ui.ondemandthreshold=99
org.eclipse.jdt.ui.staticondemandthreshold=99
sp_cleanup.add_default_serial_version_id=true
sp_cleanup.add_generated_serial_version_id=false
sp_cleanup.add_missing_annotations=true
sp_cleanup.add_missing_deprecated_annotations=true
sp_cleanup.add_missing_methods=false
sp_cleanup.add_missing_nls_tags=false
sp_cleanup.add_missing_override_annotations=true
sp_cleanup.add_missing_override_annotations_interface_methods=true
sp_cleanup.add_serial_version_id=false
sp_cleanup.always_use_blocks=true
sp_cleanup.always_use_parentheses_in_expressions=false
sp_cleanup.always_use_this_for_non_static_field_access=false
sp_cleanup.always_use_this_for_non_static_method_access=false
sp_cleanup.convert_to_enhanced_for_loop=false
sp_cleanup.correct_indentation=false
sp_cleanup.format_source_code=true
sp_cleanup.format_source_code_changes_only=false
sp_cleanup.make_local_variable_final=false
sp_cleanup.make_parameters_final=false
sp_cleanup.make_private_fields_final=false
sp_cleanup.make_type_abstract_if_missing_method=false
sp_cleanup.make_variable_declarations_final=true
sp_cleanup.never_use_blocks=false
sp_cleanup.never_use_parentheses_in_expressions=true
sp_cleanup.on_save_use_additional_actions=true
sp_cleanup.organize_imports=true
sp_cleanup.qualify_static_field_accesses_with_declaring_class=false
sp_cleanup.qualify_static_member_accesses_through_instances_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_through_subtypes_with_declaring_class=true
sp_cleanup.qualify_static_member_accesses_with_declaring_class=false
sp_cleanup.qualify_static_method_accesses_with_declaring_class=false
sp_cleanup.remove_private_constructors=true
sp_cleanup.remove_trailing_whitespaces=true
sp_cleanup.remove_trailing_whitespaces_all=true
sp_cleanup.remove_trailing_whitespaces_ignore_empty=false
sp_cleanup.remove_unnecessary_casts=true
sp_cleanup.remove_unnecessary_nls_tags=true
sp_cleanup.remove_unused_imports=true
sp_cleanup.remove_unused_local_variables=false
sp_cleanup.remove_unused_private_fields=true
sp_cleanup.remove_unused_private_members=false
sp_cleanup.remove_unused_private_methods=true
sp_cleanup.remove_unused_private_types=true
sp_cleanup.sort_members=false
sp_cleanup.sort_members_all=false
sp_cleanup.use_blocks=false
sp_cleanup.use_blocks_only_for_return_and_throw=false
sp_cleanup.use_parentheses_in_expressions=false
sp_cleanup.use_this_for_non_static_field_access=false
sp_cleanup.use_this_for_non_static_field_access_only_if_necessary=true
sp_cleanup.use_this_for_non_static_method_access=false
sp_cleanup.use_this_for_non_static_method_access_only_if_necessary=true

83
frontend/build.gradle Normal file
View File

@ -0,0 +1,83 @@
apply plugin: 'com.moowork.node'
buildscript {
ext {
gradleNodeVersion = '1.2.0'
}
repositories {
mavenCentral()
maven { url 'https://plugins.gradle.org/m2' }
}
dependencies {
classpath "com.moowork.gradle:gradle-node-plugin:$gradleNodeVersion"
}
}
ext {
httpPort = 12000
httpsPort = 12005
applicationName = "${war.archiveName}"
}
war {
archiveName = "${baseName}.${extension}"
dependsOn 'copyFrontend'
}
node {
version = '9.5.0'
npmVersion = '5.6.0'
download = true
workDir = file("${rootDir}/frontend/prebuild/node")
nodeModulesDir = file("${rootDir}/frontend/prebuild")
}
task cleanClient(type: Delete) {
group 'build client'
delete fileTree(dir: "${rootDir}/frontend/src/main/webapp/", exclude: [ '**/WEB-INF/**'])
}
task cleanNpm(type: Delete) {
group 'build client'
dependsOn 'clean'
delete "${rootDir}/frontend/prebuild/node", "${rootDir}/frontend/prebuild/node_modules"
}
task npmUpdate {
group 'build client'
dependsOn 'npm_update'
}
task buildStandaloneClient(type: NpmTask, dependsOn: npmInstall) {
group 'build client'
description = 'Compile client side folder for development'
args = ['run', 'build']
}
task copyFrontend(type: Copy) {
group 'build client'
dependsOn 'cleanClient', 'buildStandaloneClient'
from fileTree("${rootDir}/frontend/prebuild/dist")
into "${rootDir}/frontend/src/main/webapp"
}
liberty {
server {
name = 'frontendServer'
apps = [file('build/libs/frontend.war')]
bootstrapProperties = ['httpPort': httpPort, 'httpsPort': httpsPort, 'application.name': applicationName]
}
}
libertyStart.doLast {
println "Application available at: http://localhost:${httpPort}/"
}
task open {
doLast {
java.awt.Desktop.desktop.browse "http://localhost:${httpPort}/".toURI()
}
}

View File

@ -0,0 +1,64 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"project": {
"name": "frontend"
},
"apps": [
{
"root": "src",
"outDir": "dist",
"assets": [
"assets",
"favicon.ico"
],
"index": "index.html",
"main": "main.ts",
"polyfills": "polyfills.ts",
"test": "test.ts",
"tsconfig": "tsconfig.app.json",
"testTsconfig": "tsconfig.spec.json",
"prefix": "app",
"styles": [
"styles.css",
"../node_modules/bootstrap/dist/css/bootstrap.min.css"
],
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js"
],
"environmentSource": "environments/environment.ts",
"environments": {
"dev": "environments/environment.ts",
"prod": "environments/environment.prod.ts"
}
}
],
"e2e": {
"protractor": {
"config": "./protractor.conf.js"
}
},
"lint": [
{
"project": "src/tsconfig.app.json",
"exclude": "**/node_modules/**"
},
{
"project": "src/tsconfig.spec.json",
"exclude": "**/node_modules/**"
},
{
"project": "e2e/tsconfig.e2e.json",
"exclude": "**/node_modules/**"
}
],
"test": {
"karma": {
"config": "./karma.conf.js"
}
},
"defaults": {
"styleExt": "css",
"component": {}
}
}

View File

@ -0,0 +1,13 @@
# Editor configuration, see http://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
max_line_length = off
trim_trailing_whitespace = false

44
frontend/prebuild/.gitignore vendored Normal file
View File

@ -0,0 +1,44 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# compiled output
/dist
/dist-server
/tmp
/out-tsc
# dependencies
/node_modules
/node
# IDEs and editors
/.idea
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# IDE - VSCode
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
# misc
/.sass-cache
/connect.lock
/coverage
/libpeerconnection.log
npm-debug.log
testem.log
/typings
# e2e
/e2e/*.js
/e2e/*.map
# System Files
.DS_Store
Thumbs.db

View File

@ -0,0 +1,27 @@
# Frontend
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.6.4.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/).
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md).

View File

@ -0,0 +1,284 @@
'use strict'; // necessary for es6 output in node
import { browser, element, by, ElementFinder, ElementArrayFinder } from 'protractor';
import { promise } from 'selenium-webdriver';
const expectedH1 = 'Tour of Heroes';
const expectedTitle = `${expectedH1}`;
const targetHero = { id: 15, name: 'Magneta' };
const targetHeroDashboardIndex = 3;
const nameSuffix = 'X';
const newHeroName = targetHero.name + nameSuffix;
class Hero {
id: number;
name: string;
// Factory methods
// Hero from string formatted as '<id> <name>'.
static fromString(s: string): Hero {
return {
id: +s.substr(0, s.indexOf(' ')),
name: s.substr(s.indexOf(' ') + 1),
};
}
// Hero from hero list <li> element.
static async fromLi(li: ElementFinder): Promise<Hero> {
let stringsFromA = await li.all(by.css('a')).getText();
let strings = stringsFromA[0].split(' ');
return { id: +strings[0], name: strings[1] };
}
// Hero id and name from the given detail element.
static async fromDetail(detail: ElementFinder): Promise<Hero> {
// Get hero id from the first <div>
let _id = await detail.all(by.css('div')).first().getText();
// Get name from the h2
let _name = await detail.element(by.css('h2')).getText();
return {
id: +_id.substr(_id.indexOf(' ') + 1),
name: _name.substr(0, _name.lastIndexOf(' '))
};
}
}
describe('Tutorial part 6', () => {
beforeAll(() => browser.get(''));
function getPageElts() {
let navElts = element.all(by.css('app-root nav a'));
return {
navElts: navElts,
appDashboardHref: navElts.get(0),
appDashboard: element(by.css('app-root app-dashboard')),
topHeroes: element.all(by.css('app-root app-dashboard > div h4')),
appHeroesHref: navElts.get(1),
appHeroes: element(by.css('app-root app-heroes')),
allHeroes: element.all(by.css('app-root app-heroes li')),
selectedHeroSubview: element(by.css('app-root app-heroes > div:last-child')),
heroDetail: element(by.css('app-root app-hero-detail > div')),
searchBox: element(by.css('#search-box')),
searchResults: element.all(by.css('.search-result li'))
};
}
describe('Initial page', () => {
it(`has title '${expectedTitle}'`, () => {
expect(browser.getTitle()).toEqual(expectedTitle);
});
it(`has h1 '${expectedH1}'`, () => {
expectHeading(1, expectedH1);
});
const expectedViewNames = ['Dashboard', 'Heroes'];
it(`has views ${expectedViewNames}`, () => {
let viewNames = getPageElts().navElts.map((el: ElementFinder) => el.getText());
expect(viewNames).toEqual(expectedViewNames);
});
it('has dashboard as the active view', () => {
let page = getPageElts();
expect(page.appDashboard.isPresent()).toBeTruthy();
});
});
describe('Dashboard tests', () => {
beforeAll(() => browser.get(''));
it('has top heroes', () => {
let page = getPageElts();
expect(page.topHeroes.count()).toEqual(4);
});
it(`selects and routes to ${targetHero.name} details`, dashboardSelectTargetHero);
it(`updates hero name (${newHeroName}) in details view`, updateHeroNameInDetailView);
it(`cancels and shows ${targetHero.name} in Dashboard`, () => {
element(by.buttonText('go back')).click();
browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6
let targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex);
expect(targetHeroElt.getText()).toEqual(targetHero.name);
});
it(`selects and routes to ${targetHero.name} details`, dashboardSelectTargetHero);
it(`updates hero name (${newHeroName}) in details view`, updateHeroNameInDetailView);
it(`saves and shows ${newHeroName} in Dashboard`, () => {
element(by.buttonText('save')).click();
browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6
let targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex);
expect(targetHeroElt.getText()).toEqual(newHeroName);
});
});
describe('Heroes tests', () => {
beforeAll(() => browser.get(''));
it('can switch to Heroes view', () => {
getPageElts().appHeroesHref.click();
let page = getPageElts();
expect(page.appHeroes.isPresent()).toBeTruthy();
expect(page.allHeroes.count()).toEqual(10, 'number of heroes');
});
it('can route to hero details', async () => {
getHeroLiEltById(targetHero.id).click();
let page = getPageElts();
expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail');
let hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name.toUpperCase());
});
it(`updates hero name (${newHeroName}) in details view`, updateHeroNameInDetailView);
it(`shows ${newHeroName} in Heroes list`, () => {
element(by.buttonText('save')).click();
browser.waitForAngular();
let expectedText = `${targetHero.id} ${newHeroName}`;
expect(getHeroAEltById(targetHero.id).getText()).toEqual(expectedText);
});
it(`deletes ${newHeroName} from Heroes list`, async () => {
const heroesBefore = await toHeroArray(getPageElts().allHeroes);
const li = getHeroLiEltById(targetHero.id);
li.element(by.buttonText('x')).click();
const page = getPageElts();
expect(page.appHeroes.isPresent()).toBeTruthy();
expect(page.allHeroes.count()).toEqual(9, 'number of heroes');
const heroesAfter = await toHeroArray(page.allHeroes);
// console.log(await Hero.fromLi(page.allHeroes[0]));
const expectedHeroes = heroesBefore.filter(h => h.name !== newHeroName);
expect(heroesAfter).toEqual(expectedHeroes);
// expect(page.selectedHeroSubview.isPresent()).toBeFalsy();
});
it(`adds back ${targetHero.name}`, async () => {
const newHeroName = 'Alice';
const heroesBefore = await toHeroArray(getPageElts().allHeroes);
const numHeroes = heroesBefore.length;
element(by.css('input')).sendKeys(newHeroName);
element(by.buttonText('add')).click();
let page = getPageElts();
let heroesAfter = await toHeroArray(page.allHeroes);
expect(heroesAfter.length).toEqual(numHeroes + 1, 'number of heroes');
expect(heroesAfter.slice(0, numHeroes)).toEqual(heroesBefore, 'Old heroes are still there');
const maxId = heroesBefore[heroesBefore.length - 1].id;
expect(heroesAfter[numHeroes]).toEqual({id: maxId + 1, name: newHeroName});
});
});
describe('Progressive hero search', () => {
beforeAll(() => browser.get(''));
it(`searches for 'Ma'`, async () => {
getPageElts().searchBox.sendKeys('Ma');
browser.sleep(1000);
expect(getPageElts().searchResults.count()).toBe(4);
});
it(`continues search with 'g'`, async () => {
getPageElts().searchBox.sendKeys('g');
browser.sleep(1000);
expect(getPageElts().searchResults.count()).toBe(2);
});
it(`continues search with 'e' and gets ${targetHero.name}`, async () => {
getPageElts().searchBox.sendKeys('n');
browser.sleep(1000);
let page = getPageElts();
expect(page.searchResults.count()).toBe(1);
let hero = page.searchResults.get(0);
expect(hero.getText()).toEqual(targetHero.name);
});
it(`navigates to ${targetHero.name} details view`, async () => {
let hero = getPageElts().searchResults.get(0);
expect(hero.getText()).toEqual(targetHero.name);
hero.click();
let page = getPageElts();
expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail');
let hero2 = await Hero.fromDetail(page.heroDetail);
expect(hero2.id).toEqual(targetHero.id);
expect(hero2.name).toEqual(targetHero.name.toUpperCase());
});
});
async function dashboardSelectTargetHero() {
let targetHeroElt = getPageElts().topHeroes.get(targetHeroDashboardIndex);
expect(targetHeroElt.getText()).toEqual(targetHero.name);
targetHeroElt.click();
browser.waitForAngular(); // seems necessary to gets tests to pass for toh-pt6
let page = getPageElts();
expect(page.heroDetail.isPresent()).toBeTruthy('shows hero detail');
let hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(targetHero.name.toUpperCase());
}
async function updateHeroNameInDetailView() {
// Assumes that the current view is the hero details view.
addToHeroName(nameSuffix);
let page = getPageElts();
let hero = await Hero.fromDetail(page.heroDetail);
expect(hero.id).toEqual(targetHero.id);
expect(hero.name).toEqual(newHeroName.toUpperCase());
}
});
function addToHeroName(text: string): promise.Promise<void> {
let input = element(by.css('input'));
return input.sendKeys(text);
}
function expectHeading(hLevel: number, expectedText: string): void {
let hTag = `h${hLevel}`;
let hText = element(by.css(hTag)).getText();
expect(hText).toEqual(expectedText, hTag);
};
function getHeroAEltById(id: number): ElementFinder {
let spanForId = element(by.cssContainingText('li span.badge', id.toString()));
return spanForId.element(by.xpath('..'));
}
function getHeroLiEltById(id: number): ElementFinder {
let spanForId = element(by.cssContainingText('li span.badge', id.toString()));
return spanForId.element(by.xpath('../..'));
}
async function toHeroArray(allHeroes: ElementArrayFinder): Promise<Hero[]> {
let promisedHeroes = await allHeroes.map(Hero.fromLi);
// The cast is necessary to get around issuing with the signature of Promise.all()
return <Promise<any>> Promise.all(promisedHeroes);
}

View File

@ -0,0 +1,11 @@
import { browser, by, element } from 'protractor';
export class AppPage {
navigateTo() {
return browser.get('/');
}
getParagraphText() {
return element(by.css('app-root h1')).getText();
}
}

View File

@ -0,0 +1,14 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/e2e",
"baseUrl": "./",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"jasminewd2",
"node"
]
}
}

View File

@ -0,0 +1,33 @@
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('@angular/cli/plugins/karma')
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
angularCli: {
environment: 'dev'
},
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};

13103
frontend/prebuild/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,54 @@
{
"name": "frontend",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build --prod",
"test": "ng test",
"lint": "ng lint",
"e2e": "ng e2e"
},
"private": true,
"dependencies": {
"@angular/animations": "^5.1.0",
"@angular/cli": "^1.7.0-beta.1",
"@angular/common": "^5.1.0",
"@angular/compiler": "^5.1.0",
"@angular/core": "^5.1.0",
"@angular/forms": "^5.1.0",
"@angular/http": "^5.1.0",
"@angular/platform-browser": "^5.1.0",
"@angular/platform-browser-dynamic": "^5.1.0",
"@angular/router": "^5.1.0",
"@ng-bootstrap/ng-bootstrap": "^1.0.0",
"angular-in-memory-web-api": "^0.5.3",
"autoprefixer": "^7.2.5",
"bootstrap": "^4.0.0",
"core-js": "^2.4.1",
"jquery": "^3.3.1",
"rxjs": "^5.5.6",
"zone.js": "^0.8.19"
},
"devDependencies": {
"@angular/compiler-cli": "^5.1.0",
"@angular/language-service": "^5.1.0",
"@types/jasmine": "~2.8.3",
"@types/jasminewd2": "~2.0.2",
"@types/node": "~6.0.60",
"codelyzer": "^4.0.1",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "~2.0.0",
"karma-chrome-launcher": "~2.2.0",
"karma-cli": "~1.0.1",
"karma-coverage-istanbul-reporter": "^1.2.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.1.2",
"ts-node": "~3.2.0",
"tslint": "~5.9.1",
"typescript": "~2.5.3"
}
}

View File

@ -0,0 +1,33 @@
// Protractor configuration file, see link for more information
// https://github.com/angular/protractor/blob/master/lib/config.ts
const { SpecReporter } = require('jasmine-spec-reporter');
exports.config = {
allScriptsTimeout: 11000,
specs: [
'./e2e/**/*.e2e-spec.ts'
],
capabilities: {
'browserName': 'chrome',
// For Travis CI only
chromeOptions: {
binary: process.env.CHROME_BIN,
args: ['--no-sandbox']
}
},
directConnect: true,
baseUrl: 'http://localhost:4200/',
framework: 'jasmine',
jasmineNodeOpts: {
showColors: true,
defaultTimeoutInterval: 30000,
print: function() {}
},
onPrepare() {
require('ts-node').register({
project: 'e2e/tsconfig.e2e.json'
});
jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
}
};

View File

@ -0,0 +1,17 @@
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { GameComponent } from './game/game.component';
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'game', component: GameComponent },
{ path: '', redirectTo: '/login', pathMatch: 'full'}
];
@NgModule({
imports: [ RouterModule.forRoot(routes, {enableTracing: true}) ],
exports: [ RouterModule ]
})
export class AppRoutingModule {}

View File

@ -0,0 +1 @@

View File

@ -0,0 +1 @@
<router-outlet></router-outlet>

View File

@ -0,0 +1,27 @@
import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
}).compileComponents();
}));
it('should create the app', async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it(`should have as title 'app'`, async(() => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app.title).toEqual('app');
}));
it('should render title in a h1 tag', async(() => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').textContent).toContain('Welcome to app!');
}));
});

View File

@ -0,0 +1,10 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Liberty Bikes';
}

View File

@ -0,0 +1,26 @@
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { LoginComponent } from './login/login.component';
import { GameComponent } from './game/game.component';
@NgModule({
imports: [
BrowserModule,
AppRoutingModule,
NgbModule.forRoot()
],
declarations: [
AppComponent,
LoginComponent,
GameComponent,
],
providers: [ ],
bootstrap: [ AppComponent ]
})
export class AppModule { }

View File

@ -0,0 +1,7 @@
#gameroot {
background-image: url('/assets/images/tron_grid.jpg');
}
#gameroot div {
background-color: white;
}

View File

@ -0,0 +1,26 @@
<div id="gameroot" class="container-fluid">
<div class="offset-md-2 col-md-7">
<div class="panel panel-primary">
<div class="panel-heading">
<h1>Liberty Bikes Game</h1>
</div>
<div class="panel-body">
<div class="col-md-6" style="display:inline-block">
<canvas id="myCanvas" width="600" height="600" style="border:1px solid #000000; background:url('assets/images/tron_floor.jpg')"></canvas>
<br>
<br>
</div>
<ul id="playerList" class='list-group col-md-4 ' style="display:inline-block">
</ul>
</div>
<div class="panel-footer">
<button type="button" class="btn btn-success" (click)="startGame()">Start Game</button>
<button type="button" class="btn btn-danger" (click)="pauseGame()">Pause Game</button>
<button type="button" class="btn btn-warning" (click)="requeue()">Requeue</button>
</div>
</div>
</div>
<div id="output"></div>
</div>
<script type="text/javascript" src="websocket.js"></script>
<script type="text/javascript" src="whiteboard.js"></script>

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { GameComponent } from './game.component';
describe('GameComponent', () => {
let component: GameComponent;
let fixture: ComponentFixture<GameComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ GameComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(GameComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,29 @@
import { Component, OnInit } from '@angular/core';
import { Whiteboard } from './whiteboard';
@Component({
selector: 'app-game',
templateUrl: './game.component.html',
styleUrls: ['./game.component.css']
})
export class GameComponent implements OnInit {
gameBoard: Whiteboard;
constructor() { }
ngOnInit() {
this.gameBoard = new Whiteboard();
}
startGame() {
this.gameBoard.startGame();
}
pauseGame() {
this.gameBoard.pauseGame();
}
requeue() {
this.gameBoard.requeue();
}
}

View File

@ -0,0 +1,75 @@
import { Whiteboard } from './whiteboard';
export class GameWebsocket {
roundId: string;
baseUri: string;
wsUri: string;
websocket: WebSocket;
whiteboard: Whiteboard;
output: HTMLElement;
constructor(whiteboard: Whiteboard) {
this.roundId = localStorage.getItem('roundId');
this.baseUri = `ws://${document.location.hostname}:8080/round/ws`;
this.wsUri = `${this.baseUri}/${this.roundId}`;
this.websocket = new WebSocket(this.wsUri);
this.whiteboard = whiteboard;
this.output = document.getElementById('output');
this.websocket.onmessage = (evt: MessageEvent): any => {
this.onMessage(evt);
};
this.websocket.onerror = (evt: MessageEvent): any => {
this.onError(evt);
};
this.websocket.onopen = (evt: MessageEvent): any => {
this.onConnect(evt);
};
}
sendText(json: string) {
console.log(`sending text: ${json}`);
this.websocket.send(json);
}
sendBinary(bytes: any) {
console.log(`sending binary: ${bytes.toString()}`);
this.websocket.send(bytes);
}
onMessage(evt: MessageEvent) {
console.log(`received: ${evt.data}`);
if (typeof evt.data === 'string') {
const json = JSON.parse(evt.data);
if (json.playerlist) {
this.whiteboard.updatePlayerList(json);
} else if (json.requeue) {
this.roundId = json.requeue;
localStorage.setItem('roundId', this.roundId);
location.reload();
} else {
this.whiteboard.drawImageText(evt.data);
}
} else {
this.whiteboard.drawImageBinary(evt.data);
}
}
onError(evt: MessageEvent) {
this.writeToScreen(`<span style="color: red;">ERROR:</span> ${evt.data}`);
}
onConnect(evt: MessageEvent) {
const name = localStorage.getItem('username');
this.sendText(JSON.stringify({'playerjoined': name}));
}
writeToScreen(message: string) {
const pre = document.createElement('p');
pre.style.wordWrap = 'break-word';
pre.innerHTML = message;
this.output.appendChild(pre);
}
}

View File

@ -0,0 +1,114 @@
import * as $ from 'jquery';
import { GameWebsocket } from './websocket';
export class Whiteboard {
canvas: any;
context: any;
gamesocket: GameWebsocket;
constructor() {
this.canvas = document.getElementById('myCanvas');
this.context = this.canvas.getContext('2d');
this.gamesocket = new GameWebsocket(this);
window.onkeydown = (e: KeyboardEvent): any => {
const key = e.keyCode ? e.keyCode : e.which;
if (key === 38) {
this.gamesocket.sendText(JSON.stringify({ direction: 'UP' }));
} else if (key === 40) {
this.gamesocket.sendText(JSON.stringify({ direction: 'DOWN' }));
} else if (key === 37) {
this.gamesocket.sendText(JSON.stringify({ direction: 'LEFT' }));
} else if (key === 39) {
this.gamesocket.sendText(JSON.stringify({ direction: 'RIGHT' }));
}
};
}
getCurrentPos(evt) {
const rect = this.canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
drawImageText(image) {
const json = JSON.parse(image);
this.context.fillStyle = json.color;
switch (json.shape) {
case 'circle':
this.context.beginPath();
this.context.arc(
json.coords.x,
json.coords.y,
5,
0,
2 * Math.PI,
false
);
this.context.fill();
break;
case 'square':
default:
this.context.fillRect(json.coords.x, json.coords.y, 5, 5);
break;
}
}
drawImageBinary(blob) {
const bytes = new Uint8Array(blob);
const imageData = this.context.createImageData(
this.canvas.width,
this.canvas.height
);
for (let i = 8; i < imageData.data.length; i++) {
imageData.data[i] = bytes[i];
}
this.context.putImageData(imageData, 0, 0);
}
updatePlayerList(json) {
let list = '<li class="list-group-item active">Players</li>';
for (const player of json.playerlist) {
list += `
<li class="list-group-item">
<span style="color: ${player.color}; font-size: 5;">${player.name}</span>: ${this.getStatus(player.status)}
</li>
`;
}
$('#playerList').html(list);
}
getStatus(status) {
if (status === 'Connected') {
return '<span class=\'label label-primary\'>Connected</span>';
}
if (status === 'Alive' || status === 'Winner') {
return `<span class='label label-success'>${status}</span>`;
}
if (status === 'Dead') {
return '<span class=\'label label-danger\'>Dead</span>';
}
if (status === 'Disconnected') {
return '<span class=\'label label-default\'>Disconnected</span>';
}
}
startGame() {
this.gamesocket.sendText(JSON.stringify({ message: 'GAME_START' }));
}
pauseGame() {
this.gamesocket.sendText(JSON.stringify({ message: 'GAME_PAUSE' }));
}
requeue() {
this.gamesocket.sendText(JSON.stringify({ message: 'GAME_REQUEUE' }));
}
}

View File

@ -0,0 +1,30 @@
<div class="container-fluid">
<div class="row">
<div class="col-auto">
<h1>Liberty Bikes</h1>
</div>
</div>
<div class="row">
<div class="col-md-2 offset-md-1">
Enter Username:
</div>
<div class="col-md-4">
<input type="text" id="username" name="username">
</div>
</div>
<div class="row">
<div class="col-md-2 offset-md-1">
Enter Round ID:
</div>
<div class="col-md-4">
<input type="text" id="roundid" name="roundid">
</div>
</div>
<div class="row">
<div class="col-md-2 offset-md-1">
<input type="submit" class="btn btn-success" value="Login" (click)="joinRound()">
<input type="submit" class="btn btn-success" value="Create Round" (click)="createRound()">
</div>
</div>
</div>

View File

@ -0,0 +1,25 @@
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { LoginComponent } from './login.component';
describe('LoginComponent', () => {
let component: LoginComponent;
let fixture: ComponentFixture<LoginComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [ LoginComponent ]
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(LoginComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,29 @@
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import * as $ from 'jquery';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit() {}
createRound() {
$.post(`http://${document.location.hostname}:8080/round/create`, function(data) {
alert('Response is: ' + data);
});
}
joinRound() {
localStorage.setItem('username', $('#username').val());
localStorage.setItem('roundId', $('#roundid').val());
this.router.navigate(['/game']);
}
}

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 141 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

View File

@ -0,0 +1,3 @@
export const environment = {
production: true
};

View File

@ -0,0 +1,8 @@
// The file contents for the current environment will overwrite these during build.
// The build system defaults to the dev environment which uses `environment.ts`, but if you do
// `ng build --env=prod` then `environment.prod.ts` will be used instead.
// The list of which env maps to which file can be found in `.angular-cli.json`.
export const environment = {
production: false
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

@ -0,0 +1,14 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Frontend</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<app-root></app-root>
</body>
</html>

View File

@ -0,0 +1,12 @@
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule)
.catch(err => console.log(err));

View File

@ -0,0 +1,66 @@
/**
* This file includes polyfills needed by Angular and is loaded before the app.
* You can add your own extra polyfills to this file.
*
* This file is divided into 2 sections:
* 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
* 2. Application imports. Files imported after ZoneJS that should be loaded before your main
* file.
*
* The current setup is for so-called "evergreen" browsers; the last versions of browsers that
* automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
* Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
*
* Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
*/
/***************************************************************************************************
* BROWSER POLYFILLS
*/
/** IE9, IE10 and IE11 requires all of the following polyfills. **/
// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';
/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js'; // Run `npm install --save classlist.js`.
/** IE10 and IE11 requires the following for the Reflect API. */
// import 'core-js/es6/reflect';
/** Evergreen browsers require these. **/
// Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.
import 'core-js/es7/reflect';
/**
* Required to support Web Animations `@angular/platform-browser/animations`.
* Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
**/
// import 'web-animations-js'; // Run `npm install --save web-animations-js`.
/***************************************************************************************************
* Zone JS is required by default for Angular itself.
*/
import 'zone.js/dist/zone'; // Included with Angular CLI.
/***************************************************************************************************
* APPLICATION IMPORTS
*/

View File

@ -0,0 +1,65 @@
/* Master Styles */
h1 {
color: #369;
font-family: Arial, Helvetica, sans-serif;
font-size: 250%;
}
h2, h3 {
color: #444;
font-family: Arial, Helvetica, sans-serif;
font-weight: lighter;
}
body {
margin: 2em;
}
body, input[text], button {
color: #888;
font-family: Cambria, Georgia;
}
a {
cursor: pointer;
cursor: hand;
}
button {
font-family: Arial;
background-color: #eee;
border: none;
padding: 5px 10px;
border-radius: 4px;
cursor: pointer;
cursor: hand;
}
button:hover {
background-color: #cfd8dc;
}
button:disabled {
background-color: #eee;
color: #aaa;
cursor: auto;
}
/* Navigation link styles */
nav a {
padding: 5px 10px;
text-decoration: none;
margin-right: 10px;
margin-top: 10px;
display: inline-block;
background-color: #eee;
border-radius: 4px;
}
nav a:visited, a:link {
color: #607D8B;
}
nav a:hover {
color: #039be5;
background-color: #CFD8DC;
}
nav a.active {
color: #039be5;
}
/* everywhere else */
* {
font-family: Arial, Helvetica, sans-serif;
}

View File

@ -0,0 +1,32 @@
// This file is required by karma.conf.js and loads recursively all the .spec and framework files
import 'zone.js/dist/long-stack-trace-zone';
import 'zone.js/dist/proxy.js';
import 'zone.js/dist/sync-test';
import 'zone.js/dist/jasmine-patch';
import 'zone.js/dist/async-test';
import 'zone.js/dist/fake-async-test';
import { getTestBed } from '@angular/core/testing';
import {
BrowserDynamicTestingModule,
platformBrowserDynamicTesting
} from '@angular/platform-browser-dynamic/testing';
// Unfortunately there's no typing for the `__karma__` variable. Just declare it as any.
declare const __karma__: any;
declare const require: any;
// Prevent Karma from running prematurely.
__karma__.loaded = function () {};
// First, initialize the Angular testing environment.
getTestBed().initTestEnvironment(
BrowserDynamicTestingModule,
platformBrowserDynamicTesting()
);
// Then we find all the tests.
const context = require.context('./', true, /\.spec\.ts$/);
// And load the modules.
context.keys().map(context);
// Finally, start Karma to run the tests.
__karma__.start();

View File

@ -0,0 +1,14 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"baseUrl": "./",
"module": "es2015",
"types": []
},
"exclude": [
"test.ts",
"**/*.spec.ts",
"**/testing/*"
]
}

View File

@ -0,0 +1,20 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/spec",
"baseUrl": "./",
"module": "commonjs",
"target": "es5",
"types": [
"jasmine",
"node"
]
},
"files": [
"test.ts"
],
"include": [
"**/*.spec.ts",
"**/*.d.ts"
]
}

5
frontend/prebuild/src/typings.d.ts vendored Normal file
View File

@ -0,0 +1,5 @@
/* SystemJS module definition */
declare var module: NodeModule;
interface NodeModule {
id: string;
}

View File

@ -0,0 +1,19 @@
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
}
}

View File

@ -0,0 +1,144 @@
{
"rulesDirectory": [
"node_modules/codelyzer"
],
"rules": {
"arrow-return-shorthand": true,
"callable-types": true,
"class-name": true,
"comment-format": [
true,
"check-space"
],
"curly": true,
"deprecation": {
"severity": "warn"
},
"eofline": true,
"forin": true,
"import-blacklist": [
true,
"rxjs",
"rxjs/Rx"
],
"import-spacing": true,
"indent": [
true,
"spaces"
],
"interface-over-type-literal": true,
"label-position": true,
"max-line-length": [
true,
140
],
"member-access": false,
"member-ordering": [
true,
{
"order": [
"static-field",
"instance-field",
"static-method",
"instance-method"
]
}
],
"no-arg": true,
"no-bitwise": true,
"no-console": [
true,
"debug",
"info",
"time",
"timeEnd",
"trace"
],
"no-construct": true,
"no-debugger": true,
"no-duplicate-super": true,
"no-empty": false,
"no-empty-interface": true,
"no-eval": true,
"no-inferrable-types": [
true,
"ignore-params"
],
"no-misused-new": true,
"no-non-null-assertion": true,
"no-shadowed-variable": true,
"no-string-literal": false,
"no-string-throw": true,
"no-switch-case-fall-through": true,
"no-trailing-whitespace": true,
"no-unnecessary-initializer": true,
"no-unused-expression": true,
"no-use-before-declare": true,
"no-var-keyword": true,
"object-literal-sort-keys": false,
"one-line": [
true,
"check-open-brace",
"check-catch",
"check-else",
"check-whitespace"
],
"prefer-const": true,
"quotemark": [
true,
"single"
],
"radix": true,
"semicolon": [
true,
"always"
],
"triple-equals": [
true,
"allow-null-check"
],
"typedef-whitespace": [
true,
{
"call-signature": "nospace",
"index-signature": "nospace",
"parameter": "nospace",
"property-declaration": "nospace",
"variable-declaration": "nospace"
}
],
"typeof-compare": true,
"unified-signatures": true,
"variable-name": false,
"whitespace": [
true,
"check-branch",
"check-decl",
"check-operator",
"check-separator",
"check-type"
],
"directive-selector": [
true,
"attribute",
"app",
"camelCase"
],
"component-selector": [
true,
"element",
"app",
"kebab-case"
],
"no-output-on-prefix": true,
"use-input-property-decorator": true,
"use-output-property-decorator": true,
"use-host-property-decorator": true,
"no-input-rename": true,
"no-output-rename": true,
"use-life-cycle-interface": true,
"use-pipe-transform-interface": true,
"component-class-suffix": true,
"directive-class-suffix": true
}
}

View File

@ -0,0 +1,12 @@
<server>
<featureManager>
<feature>webProfile-7.0</feature>
</featureManager>
<httpEndpoint id="defaultHttpEndpoint" httpPort="${httpPort}" httpsPort="${httpsPort}" />
<applicationManager autoExpand="true"/>
<webApplication location="${application.name}" contextRoot="/" >
</webApplication>
</server>

View File

@ -0,0 +1,11 @@
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<error-page>
<error-code>404</error-code>
<location>/</location>
</error-page>
</web-app>

View File

@ -16,4 +16,12 @@
<keyStore id="defaultKeyStore" password="Liberty"/>
<quickStartSecurity userName="admin" userPassword="admin"/>
<!-- This configuration allows cross-origin HTTP requests, such
as those from the front-end component (different port). -->
<cors domain="/round"
allowedOrigins="*"
allowedMethods="GET, DELETE, POST, PUT"
allowedHeaders="Accept, Content-Type, Authorization"
maxAge="3600" />
</server>

View File

@ -19,3 +19,4 @@ rootProject.name = 'liberty-bikes'
include 'auth-service'
include 'game-service'
include 'player-service'
include 'frontend'