Compare commits

...

10 Commits

Author SHA1 Message Date
Sebastian Seedorf
37eb1e37ee Dropdown foreign bug fixes 2017-06-09 16:44:58 +02:00
Sebastian Seedorf
cc49a89ea4 Dropdown foreign implementation 2017-06-09 14:56:35 +02:00
Sebastian Seedorf
1db9e839d3 Finished value service 2017-06-08 15:27:41 +02:00
Sebastian Seedorf
05fd2586fd Remote question and value service 2017-06-07 15:52:04 +02:00
Sebastian Seedorf
3a36f948d1 Added checkbox input 2017-06-07 10:41:08 +02:00
Sebastian Seedorf
abdcfd31d1 submits only visible items 2017-06-06 16:18:01 +02:00
Sebastian Seedorf
fc2c3f029a Specialization, Textbox 2017-06-06 15:45:08 +02:00
Sebastian Seedorf
006f618c36 added validation, error messages, help tooptips, async question loading and textarea input 2017-06-02 17:36:32 +02:00
Sebastian Seedorf
fe28064e10 Merging completed 2017-05-30 09:39:56 +02:00
Sebastian Seedorf
720f8df85f Merging 2017-05-30 09:33:32 +02:00
26 changed files with 1477 additions and 521 deletions

2
.idea/modules.xml generated
View File

@@ -2,7 +2,7 @@
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/AngularCounterInput.iml" filepath="$PROJECT_DIR$/.idea/AngularCounterInput.iml" />
<module fileurl="file://$PROJECT_DIR$/.idea/AngularDynFormModule.iml" filepath="$PROJECT_DIR$/.idea/AngularDynFormModule.iml" />
</modules>
</component>
</project>

View File

@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="TypeScriptCompiler">
<option name="isCompilerEnabled" value="true" />
<option name="useConfig" value="true" />
<option name="showAllErrors" value="true" />
</component>
</project>

1114
.idea/workspace.xml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1 +1,5 @@
<button (click)="loadValues()">Refesh</button>
<hr>
<h1>{{formName}}</h1>
<p>{{formDescription}}</p>
<dyn-form [questions]="formQuestions" (onSubmit)="submit($event)" [value]="formValue" [type]="'insert'"></dyn-form>

View File

@@ -1,6 +1,7 @@
import {Component, Inject} from '@angular/core';
import {Component, Input, OnChanges, SimpleChanges} from '@angular/core';
import {QuestionInterface} from './modules/dyn-form/types/question.interface';
import {QuestionService} from './modules/dyn-form/services/question.service';
import {FormService} from './modules/dyn-form/services/form.service';
import {ValueService} from './modules/dyn-form/services/value.service';
@Component({
selector: 'my-app',
@@ -8,16 +9,40 @@ import {QuestionService} from './modules/dyn-form/services/question.service';
})
export class AppComponent {
public formQuestions: QuestionInterface[] = [];
public formQuestions: QuestionInterface[] = null;
public formValue: Object = null;
public formName: string = "";
public formDescription ="";
private uri: string = '/crf/fields';
constructor(private questionService: QuestionService) {
this.questionService.getQuestions((res, err) => {
this.formQuestions = res;
constructor(private questionService: FormService, private valueService: ValueService) {
this.loadValues();
}
private loadValues() {
console.log(this.uri);
this.questionService.getForm(this.uri, (res, err) => {
if (err)
console.error(err);
else {
this.formQuestions = res.questions;
this.formName = res.name;
this.formDescription = res.description;
console.log("questions", this.formQuestions);
}
});
this.valueService.getValue(this.uri, 3, (res, err) => {
if (err)
console.error(err);
else {
this.formValue = res;
console.log("values", this.formValue);
}
});
}
submit(value: any) {
public submit(value: any) {
console.log('send', value);
this.valueService.postValues(this.uri, value, (data, err) => console.log("posted", data, err));
}
}

View File

@@ -1,4 +1,4 @@
import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Component, EventEmitter, Input, OnChanges, Output, SimpleChanges} from '@angular/core';
import {QuestionInterface} from './types/question.interface';
import {FormControl, FormGroup} from '@angular/forms';
@@ -6,33 +6,52 @@ import {FormControl, FormGroup} from '@angular/forms';
selector: 'dyn-form',
template: `
<form (ngSubmit)="submit()" [formGroup]="form">
<dyn-question *ngFor="let question of questions" [hidden]="question.properties.methods && question.properties.methods.indexOf(type)==-1" [question]="question" [form]="form" [type]="type"></dyn-question>
<div *ngFor="let question of questions">
<dyn-question *ngIf="!(question.properties.methods && question.properties.methods.indexOf(type)==-1 || question.properties.spezialization && form.value.type!=question.properties.spezialization)" [ngSwitch]="question.type"
[question]="question" [form]="form" [type]="type" (onChange)="valueChange.emit(form.value)"></dyn-question>
</div>
<div class="form-row">
<button type="submit">Save</button>
<button [disabled]="form.invalid && type!='delete'" type="submit">Save</button>
</div>
</form>
`
})
export class DynFormComponent implements OnInit {
export class DynFormComponent implements OnChanges {
@Input() questions: QuestionInterface[];
@Input() value: any;
@Input() type: "'insert'|'update'|'delete'|'view'";
@Input() value: {[_:string]: any};
@Input() type: 'insert'|'update'|'delete'|'view';
@Output() valueChange: EventEmitter<any> = new EventEmitter<any>();
@Output() onSubmit: EventEmitter<any> = new EventEmitter<any>();
private form: FormGroup;
public ngOnInit () {
public ngOnChanges(changes: SimpleChanges) {
if (changes['questions']) {
let controls = {};
for(let i = 0; i < this.questions.length; i++) {
for(let i = 0; this.questions && i < this.questions.length; i++) {
let key = this.questions[i].properties.key;
controls[key] = new FormControl(this.value[key]);
controls[key] = new FormControl();
}
this.form = new FormGroup(controls);
}
if ((changes['questions'] || changes['value']) && this.form && this.value) {
this.form.patchValue(this.value);
}
}
private submit() {
console.log("isValid", this.form.valid);
this.onSubmit.emit(this.form.value);
if (this.form.valid || this.type=='delete') {
let vals = {};
let type: string = this.form.value.type;
for (let question of this.questions) {
let specType = question.properties.specialization;
let methods = question.properties.methods;
let key = question.properties.key;
if (!(methods && methods.indexOf(this.type)==-1 || specType && type!=specType) && (this.type!='delete' || question.type=='hidden')) {
vals[key] = this.form.value[key];
}
}
this.onSubmit.emit(vals);
}
}
}

View File

@@ -4,10 +4,15 @@ import { NgModule } from '@angular/core';
import { DynFormComponent } from './dyn-form.component';
import {DynQuestionComponent} from './dyn-question.component';
import {CounterInputComponent} from './inputs/counter-input.component';
import {KeysPipe, TagInputComponent} from './inputs/tag-input.component';
import {TagInputComponent} from './inputs/tag-input.component';
import {HiddenInputComponent} from './inputs/hidden-input.component';
import {DropdownInputComponent} from './inputs/dropdown-input.component';
import {QuestionService} from './services/question.service';
import {FormService} from './services/form.service';
import {TextareaInputComponent} from './inputs/textarea-input.component';
import {ValueService} from './services/value.service';
import {KeysPipe} from './types/keys.pipe';
import {TextboxInputComponent} from './inputs/textbox-input.component';
import {CheckboxInputComponent} from './inputs/checkbox-input.component';
@NgModule({
@@ -25,10 +30,14 @@ import {QuestionService} from './services/question.service';
TagInputComponent,
HiddenInputComponent,
DropdownInputComponent,
TextareaInputComponent,
TextboxInputComponent,
CheckboxInputComponent,
KeysPipe
],
providers: [
QuestionService
FormService,
ValueService
],
})
export class DynFormModule { }

View File

@@ -1,12 +1,15 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {QuestionInterface} from './types/question.interface';
import {FormGroup} from '@angular/forms';
import {FormGroup, ValidationErrors} from '@angular/forms';
@Component({
selector: 'dyn-question',
template: `
<div [ngSwitch]="question.type" [formGroup]="form">
<label [for]="question.properties.key">{{question.properties.label}}</label>
<div [ngSwitch]="question.type" [formGroup]="form" [hidden]="type=='delete'">
<label [for]="question.properties.key">{{question.properties.label ? question.properties.label + (question.constraints.optional ? '' : ' *') : ''}}</label>
<i [hidden]="question.description" class="help circle icon" (mouseover)="onHover(true)" (mouseout)="onHover(false)">Help</i>
<a [hidden]="!hoverState" class="ui pointing red basic label">{{question.description}}</a><br>
<tag-input *ngSwitchCase="'flag'"
[formControlName]="question.properties.key" [id]="question.properties.key"
[nullable]="question.constraints.optional" [readonly]="type=='view'"
@@ -19,8 +22,26 @@ import {FormGroup} from '@angular/forms';
<dropdown-input *ngSwitchCase="'dropdown'"
[formControlName]="question.properties.key" [id]="question.properties.key"
[nullable]="question.constraints.optional" [readonly]="type=='view'"
[items]="question.properties.options"
[items]="question.properties.options" [foreign]="question.properties.foreign"
(ngModelChange)="change()"></dropdown-input>
<textarea-input *ngSwitchCase="'textarea'"
[formControlName]="question.properties.key" [id]="question.properties.key"
[nullable]="question.constraints.optional" [readonly]="type=='view'"
(ngModelChange)="change()"></textarea-input>
<textbox-input *ngSwitchCase="'textbox'"
[formControlName]="question.properties.key" [id]="question.properties.key"
[nullable]="question.constraints.optional" [readonly]="type=='view'"
[type]="question.properties.type" [constraints]="question.constraints"
[placeholder]="question.properties.placeholder"
(ngModelChange)="change()"></textbox-input>
<checkbox-input *ngSwitchCase="'checkbox'"
[formControlName]="question.properties.key" [id]="question.properties.key"
[nullable]="question.constraints.optional" [readonly]="type=='view'"
(ngModelChange)="change()"></checkbox-input>
<ul [hidden]="!errorList.length">
<li *ngFor="let error of errorList">{{error}}</li>
</ul>
</div>
`
})
@@ -29,8 +50,26 @@ export class DynQuestionComponent {
@Input() type: "'insert'|'update'|'delete'|'view'";
@Input() form: FormGroup;
@Output() onChange: EventEmitter<any> = new EventEmitter<any>();
public hoverState: any = false;
private errorList: Array<string> = [];
onHover(state: boolean) {
this.hoverState = state;
}
change() {
setTimeout(() => {
this.errorList = [];
let control = this.form.controls[this.question.properties.key];
if (control.untouched || control.valid)
return null;
let errors: ValidationErrors = control.errors;
for (let key in errors) {
if (errors.hasOwnProperty(key)) {
this.errorList.push(errors[key].message);
}
}
this.onChange.emit();
}, 0);
}
}

View File

@@ -0,0 +1,60 @@
import {Component, forwardRef, Input} from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, ValidationErrors } from '@angular/forms';
import {CustomInputComponent} from "./custom-input.component";
@Component({
selector: 'checkbox-input',
template:
`
<label *ngIf="!readonly"><input type="radio" [checked]="value===true" (change)="onChange(true)">Yes</label><br *ngIf="!readonly"/>
<label *ngIf="!readonly"><input type="radio" [checked]="value===false" (change)="onChange(false)">No</label><br *ngIf="!readonly"/>
<label *ngIf="!readonly && nullable"><input type="radio" [checked]="value===null" (change)="onChange(null)">N/A</label>
<span *ngIf="readonly">{{value ? "Yes" : (value===false ? "No" : "N/A")}}</span>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => CheckboxInputComponent),
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => CheckboxInputComponent),
multi: true,
}]
})
export class CheckboxInputComponent extends CustomInputComponent {
@Input() readonly: boolean = false;
@Input() nullable: boolean = false;
// set initial value
public writeValue(obj: any): void {
if (obj) {
this.value = true;
} else if (obj===false) {
this.value = false;
} else {
this.value = null;
}
if (this.value !== obj)
setTimeout(() => super.change(true), 0);
}
// validates the form, returns null when valid else the validation object
public validate(c: FormControl): ValidationErrors {
if (!this.initComplete)
return null;
return this.nullable || (this.value) || (this.value===false) ? null : {notNullable: {
valid: false,
message: "This field is required!"
}};
}
// on button click
protected onChange(newValue: boolean): void {
this.value = newValue;
super.change();
}
}

View File

@@ -1,4 +1,4 @@
import { Component, forwardRef } from '@angular/core';
import {Component, forwardRef} from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, ValidationErrors } from '@angular/forms';
import {CustomInputComponent} from "./custom-input.component";
@@ -6,9 +6,9 @@ import {CustomInputComponent} from "./custom-input.component";
selector: 'counter-input',
template:
`
<button (click)="onChange(-1)" (blur)="onBlur()">-</button>
<button (click)="onChange(-1)">-</button>
{{value}}
<button (click)="onChange(1)" (blur)="onBlur()">+</button>
<button (click)="onChange(1)">+</button>
`,
providers: [
{
@@ -23,6 +23,7 @@ import {CustomInputComponent} from "./custom-input.component";
}]
})
export class CounterInputComponent extends CustomInputComponent {
// set initial value
public writeValue(obj: any): void {
if (obj) {
@@ -33,9 +34,12 @@ export class CounterInputComponent extends CustomInputComponent {
// validates the form, returns null when valid else the validation object
public validate(c: FormControl): ValidationErrors {
if (!this.initComplete)
return null;
return (!this.parseError) ? null : {
numberParseError: {
valid: false,
message: "Not a valid number!"
},
};
}
@@ -47,9 +51,4 @@ export class CounterInputComponent extends CustomInputComponent {
super.change();
}
// on touched
protected onBlur(): void {
super.blur();
}
}

View File

@@ -1,10 +1,21 @@
import {ControlValueAccessor, FormControl, ValidationErrors, Validator} from '@angular/forms';
import {AfterViewInit} from '@angular/core';
export abstract class CustomInputComponent implements ControlValueAccessor, Validator {
export abstract class CustomInputComponent implements ControlValueAccessor, Validator, AfterViewInit {
protected value: any;
protected parseError: boolean;
private propagateChange: (_: any) => void = () => {};
private propagateTouch: () => void = () => {};
protected initComplete: boolean = false;
private isTouched: boolean = false;
private initialChangeDone = false;
public ngAfterViewInit() {
setTimeout(() => {
this.initComplete = true;
this.change();
}, 0);
}
// set initial value
public abstract writeValue(obj: any): void;
@@ -23,12 +34,19 @@ export abstract class CustomInputComponent implements ControlValueAccessor, Vali
public abstract validate(c: FormControl): ValidationErrors;
// on change
protected change(): void {
protected change(noTouch?: boolean): void {
if (!noTouch && this.initialChangeDone) {
this.touch();
}
this.propagateChange(this.value);
this.initialChangeDone = true;
}
// on touch
protected blur(): void {
// on change
protected touch(): void {
if (!this.isTouched) {
this.propagateTouch();
this.isTouched = true;
}
}
}

View File

@@ -1,18 +1,7 @@
import {Component, forwardRef, Inject, Input, OnChanges, Pipe, PipeTransform, SimpleChanges} from '@angular/core';
import {Component, forwardRef, Input, OnChanges, SimpleChanges} from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, ValidationErrors } from '@angular/forms';
import {CustomInputComponent} from "./custom-input.component";
import {HelloService} from '../../../services/hello.service';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value: Object, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
import {ValueService} from '../services/value.service';
@Component({
selector: 'dropdown-input',
@@ -33,34 +22,64 @@ export class KeysPipe implements PipeTransform {
provide: NG_VALIDATORS,
useExisting: forwardRef(() => DropdownInputComponent),
multi: true,
}]
},
ValueService
]
})
export class DropdownInputComponent extends CustomInputComponent implements OnChanges {
@Input() readonly: boolean = false;
@Input() nullable: boolean = false;
@Input() items: Array<{key: string, value: string}> = [];
@Input() foreign: {uri: string, keys: string, values: string, options?: {key: string, value: string}[]};
private listedItems: Array<{key: string, value: string}> = [];
private foreignItems: Array<{key: string, value: string}> = [];
private pendingForeign: boolean = false;
private constVal: string;
constructor(private helloService: HelloService) {
constructor(private valueService: ValueService) {
super();
helloService.sayHello();
}
// set initial value
public writeValue(obj: any): void {
console.log("init: ", obj);
this.value = obj;
console.log("write", this.value);
this.updateConst();
}
public ngOnChanges(changes: SimpleChanges) {
if (changes['items'] || changes['nullable']) {
if (this.nullable)
this.listedItems = [{key: "", value: "N/A"}, {key: null, value: "N/A"}].concat(this.items);
else
this.listedItems = [].concat(this.items);
if (changes['items'] || changes['nullable'] || changes['readonly']) {
this.setListedItems();
}
if (changes['foreign'] && this.foreign) {
this.pendingForeign = true;
this.valueService.getValues(this.foreign.uri, {}, (res, err) => {
this.foreignItems = [];
for (let item of res as any) {
this.foreignItems.push({key: item[this.foreign.keys], value: item[this.foreign.values]});
}
this.setListedItems();
setTimeout(() => {
const val = this.value;
this.value = "UNLIKY_VLAUEdrtwe53wrsdsfrsr3drw34rerw3raxdwgxcjlb234r";
setTimeout(() => {
this.value = val;
this.change(false);
this.pendingForeign = false;
console.log("after timeout", this.value);
}, 0);
}, 0);
});
}
}
private setListedItems() {
if (this.nullable)
this.listedItems = [{key: "", value: "N/A"}, {key: null, value: "N/A"}].concat(this.items || []).concat(this.foreignItems || []);
else
this.listedItems = [].concat(this.items || []).concat(this.foreignItems || []);
console.log(this.listedItems, this.value);
this.updateConst();
}
@@ -73,26 +92,41 @@ export class DropdownInputComponent extends CustomInputComponent implements OnCh
}
}
}
console.log(this.readonly, this.listedItems, this.value, this.constVal);
}
// validates the form, returns null when valid else the validation object
public validate(c: FormControl): ValidationErrors {
console.log(this.initComplete, this.value, this.listedItems);
if (!this.initComplete)
return null;
if (this.value===null) {
return this.nullable ? null : {notNullable: {valid: false}};
return this.nullable ? null : {notNullable: {
valid: false,
message: "This field is required!"
}};
}
for (let i=0; i<this.items.length; i++) {
if (this.items[i].key==this.value)
for (let i=0; i<this.listedItems.length; i++) {
if (this.listedItems[i].key==this.value)
return null;
}
return {invalidValue: {valid: false}};
return {invalidValue: {
valid: false,
message: "This value is invalid. Please select another value!"
}};
}
// on button click
protected onChange(value: any): boolean {
this.value = value;
console.log("change", this.value);
super.change();
this.change();
return false;
}
protected touch() {
console.log("hehehe", this.pendingForeign);
if (!this.pendingForeign)
super.touch();
}
}

View File

@@ -1,18 +1,7 @@
import {Component, forwardRef, Input, Pipe, PipeTransform} from '@angular/core';
import {Component, forwardRef, Input} from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, ValidationErrors } from '@angular/forms';
import {CustomInputComponent} from "./custom-input.component";
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value: Object, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}
@Component({
selector: 'tag-input',
template:
@@ -58,10 +47,9 @@ export class TagInputComponent extends CustomInputComponent {
this.value[key] = (this.nullable ? null : false);
}
}
console.log("writeValue", isUpdated, this.value);
if (isUpdated) {
setTimeout(() => super.change(), 0);
setTimeout(() => this.change(true), 0);
}
}
@@ -86,7 +74,7 @@ export class TagInputComponent extends CustomInputComponent {
this.value = Object.assign({}, this.value);
this.value[key] = value;
super.change();
this.change();
return false;
}
}

View File

@@ -0,0 +1,54 @@
import {Component, forwardRef, Input} from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, ValidationErrors } from '@angular/forms';
import {CustomInputComponent} from "./custom-input.component";
@Component({
selector: 'textarea-input',
template:
`
<textarea *ngIf="!readonly" (keyup)="onChange($event)">{{value}}</textarea>
<span *ngIf="readonly">{{value}}</span>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TextareaInputComponent),
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => TextareaInputComponent),
multi: true,
}]
})
export class TextareaInputComponent extends CustomInputComponent {
@Input() readonly: boolean = false;
@Input() nullable: boolean = false;
// set initial value
public writeValue(obj: any): void {
if (obj) {
this.value = obj + '';
} else {
this.value = '';
}
}
// validates the form, returns null when valid else the validation object
public validate(c: FormControl): ValidationErrors {
if (!this.initComplete)
return null;
return this.nullable || (this.value) ? null : {notNullable: {
valid: false,
message: "This field is required!"
}};
}
// on button click
protected onChange($event: KeyboardEvent): void {
this.value = $event.target['value'];
super.change();
}
}

View File

@@ -0,0 +1,80 @@
import {Component, forwardRef, Input} from '@angular/core';
import { NG_VALUE_ACCESSOR, NG_VALIDATORS, FormControl, ValidationErrors } from '@angular/forms';
import {CustomInputComponent} from "./custom-input.component";
import {QuestionInterface, QuestionInterfaceCnstr} from '../types/question.interface';
@Component({
selector: 'textbox-input',
template:
`
<input *ngIf="!readonly" (keyup)="onChange($event)" [value]="value" [type]="type" [placeholder]="placeholder"/>
<span *ngIf="readonly && value">{{value}}</span>
<span *ngIf="readonly && !value"><em>No value specified!</em></span>
`,
providers: [
{
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => TextboxInputComponent),
multi: true,
},
{
provide: NG_VALIDATORS,
useExisting: forwardRef(() => TextboxInputComponent),
multi: true,
}]
})
export class TextboxInputComponent extends CustomInputComponent {
@Input() readonly: boolean = false;
@Input() nullable: boolean = false;
@Input() constraints: QuestionInterfaceCnstr = null;
@Input() type: string;
@Input() placeholder: string;
// set initial value
public writeValue(obj: any): void {
if (obj) {
this.value = obj + '';
} else {
this.value = '';
}
}
// validates the form, returns null when valid else the validation object
public validate(c: FormControl): ValidationErrors {
if (!this.initComplete)
return null;
if (!this.nullable && !this.value)
return {notNullable: {
valid: false,
message: "This field is required!"
}};
if (!this.constraints)
return null;
if (this.constraints.maxLength && this.constraints.maxLength <= this.value.length) {
return {tooLong: {
valid: false,
message: "Length is limited to "+this.constraints.maxLength+" characters."
}};
}
if (this.constraints.maxValue) {
let valueInt = parseInt(this.value, 10);
if (isNaN(valueInt))
return {noNumber: {
valid: false,
message: "This value is not a number "+this.constraints.maxValue+"."
}};
if (this.constraints.maxValue <= valueInt) {
return {tooLarge: {
valid: false,
message: "Maximal allowed value is "+this.constraints.maxValue+"."
}};
}
}
}
// on button click
protected onChange($event: KeyboardEvent): void {
this.value = $event.target['value'];
super.change();
}
}

View File

@@ -0,0 +1,109 @@
import { Injectable } from '@angular/core';
import {HttpCachedService} from '../../../services/http-cached.service';
import {QuestionInterface} from '../types/question.interface';
import {ResponseInterface} from '../../../services/response.interface';
import { Response } from '@angular/http';
import {FormInterface} from '../types/form.interface';
@Injectable()
export class FormService {
private readonly PREFIX = "/form";
constructor(private httpCachedService: HttpCachedService) {
}
public getForm(path: string, cb: (res: FormInterface, err: any) => void) {
this.httpCachedService.getJSON(this.PREFIX+path, {}, (data: ResponseInterface, e: Response | any) => {
if (e) {
cb(null, e);
return;
}
if (data.meta.code != 0) {
cb(null, data.meta);
return;
}
let form: FormInterface = data.data;
form.questions = FormService.orderItems(form.questions);
form.filters = FormService.orderItems(form.filters);
cb(data.data, e);
});
}
public getQuestions(cb: (res: QuestionInterface[], err: any) => void) {
setTimeout(() => cb(FormService.orderItems([
{
type: 'flag',
description: 'This is a help tooltip',
properties: {
key: 'flags',
label: 'Form Type Flags',
order: 3,
// dropdown && flags
options: [{key: 'alpha', value: 'A'}, {key: 'beta', value: 'B'}, {key: 'gamma', value: 'C'}, {key: 'delta', value: 'D'}]
}, constraints: {
optional: true
}
}, {
type: 'dropdown',
description: 'Cool dropdown',
properties: {
key: 'type',
label: 'Dropdown',
order: 2,
methods: ['insert'],
// dropdown
options: [{key: 'hello', value: 'Hallo'}, {key: 'world', value: 'World'}, {key: 'and', value: 'And'}, {key: 'u', value: 'You'}]
}, constraints: {
optional: false
}
}, {
type: 'hidden',
description: 'ID',
properties: {
key: 'ID',
order: 1
}, constraints: {
optional: false
}
}, {
type: 'textbox',
description: 'This is a very long box. Fill it!',
properties: {
key: 'textarea',
label: 'Textareaaaa',
order: 4,
specialization: 'world',
methods: ['insert']
}, constraints: {
optional: false
}
}, {
type: 'checkbox',
description: 'This is a very long box. Fill it!',
properties: {
key: 'checki',
label: 'To be or not to be?',
order: 5
}, constraints: {
optional: false
}
}
]), null), 10);
}
private static orderItems(list: QuestionInterface[]): QuestionInterface[] {
function compare(a: any, b: any) {
if (a.properties.order < b.properties.order)
return -1;
if (a.properties.order > b.properties.order)
return 1;
return 0;
}
list.sort(compare);
return list;
}
}

View File

@@ -1,29 +0,0 @@
import { Injectable } from '@angular/core';
import {HttpCachedService} from '../../../services/http-cached.service';
import {QuestionInterface} from '../types/question.interface';
@Injectable()
export class QuestionService {
constructor(private httpCachedService: HttpCachedService) {
}
public getQuestions(cb: (res: QuestionInterface[], err: any) => void) {
setTimeout(() => cb([
{
type: "flag",
description: "This is a help tooltip",
properties: {
key: "flags",
label: "Form Type Flags",
order: 1,
// dropdown && flags
options: [{key: "alpha", value: "A"}, {key: "beta", value: "B"}]
},
constraints: {
optional: true
}
}
], null), 4000);
}
}

View File

@@ -0,0 +1,130 @@
import { Injectable } from '@angular/core';
import {HttpCachedService} from '../../../services/http-cached.service';
import {Response} from '@angular/http';
import {ResponseInterface} from '../../../services/response.interface';
@Injectable()
export class ValueService {
private readonly PREFIX = "";
constructor(private httpCachedService: HttpCachedService) {
}
public getValue(path: string, id: any, cb: (res: Object, err: any) => void) {
this.httpCachedService.getJSON(this.PREFIX+path+"/"+id, {}, (data: ResponseInterface, e: Response | any) => {
if (e) {
cb(null, e);
return;
}
if (data.meta.code != 0) {
cb(null, data.meta);
return;
}
cb(this.unflatObject(data.data[0]), null);
});
}
public getValues(path: string, filters: {[_:string]: any}, cb: (res: Object, err: any) => void) {
this.httpCachedService.getJSON(this.PREFIX+path, this.flatObject(filters), (data, e) => {
if (e) {
cb(null, e);
return;
}
if (data.meta.code != 0) {
cb(null, data.meta);
return;
}
let ret = data.data;
for (let i=0; i<ret.length; i++)
ret[i] = this.unflatObject(ret[i]);
cb(ret, null);
});
}
public postValues(path: string, values: {[_:string]: any}, cb: (res: Object, err: any) => void) {
this.httpCachedService.postJSON(this.PREFIX + path, {}, this.flatObject(values), (data, e) => {
if (e) {
cb(null, e);
return;
}
if (data.meta.code != 0) {
cb(null, data.meta);
return;
}
cb(this.unflatObject(data.data[0]), null);
});
}
public putValues(path: string, id: any, values: {[_:string]: any}, cb: (res: Object, err: any) => void) {
this.httpCachedService.putJSON(this.PREFIX+path+"/"+id, {}, this.flatObject(values), (data, e) => {
if (e) {
cb(null, e);
return;
}
if (data.meta.code != 0) {
cb(null, data.meta);
return;
}
cb(this.unflatObject(data.data[0]), null);
});
}
public deleteValues(path: string, id: any, cb: (res: Object, err: any) => void) {
this.httpCachedService.deleteJSON(this.PREFIX+path+"/"+id, {}, (data, e) => {
if (e) {
cb(null, e);
return;
}
if (data.meta.code != 0) {
cb(null, data.meta);
return;
}
cb(null, null);
});
}
private flatObject(obj: {[_:string]: any}, prefix: string = ''): {[_:string]: any} {
let ret: {[_:string]: any} = {};
if (Object.prototype.toString.call(obj) == "[object Object]") {
if (prefix)
prefix = prefix+'.';
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
ret = Object.assign(ret, this.flatObject(obj[key], prefix+key));
}
}
} else {
ret[prefix] = obj;
}
return ret;
}
private unflatObject(obj: {[_:string]: any}): {[_:string]: any} {
let ret: {[_:string]: any} = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
let strings: string[] = key.split('.');
ret = this.addValueToPath(ret, strings, obj[key]);
}
}
return ret;
}
private addValueToPath(obj: {[_:string]: any}, path: string[], value: any) {
let key = path.shift();
if (!path || !path.length)
return Object.assign(obj, {[key]: value});
if (!obj.hasOwnProperty(key))
obj[key] = {};
obj[key] = Object.assign(obj[key], this.addValueToPath(obj[key], path, value));
return obj;
}
}

View File

@@ -0,0 +1,8 @@
import {QuestionInterface} from './question.interface';
export interface FormInterface {
description: string,
uri: string,
name: string,
questions: QuestionInterface[],
filters: QuestionInterface[]
}

View File

@@ -0,0 +1,12 @@
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'keys'})
export class KeysPipe implements PipeTransform {
transform(value: Object, args:string[]) : any {
let keys = [];
for (let key in value) {
keys.push({key: key, value: value[key]});
}
return keys;
}
}

View File

@@ -1,5 +1,5 @@
export interface QuestionInterface {
type: "flag"|"textbox"|"textarea"|"hidden"|"dropdown",
type: "flag"|"textbox"|"textarea"|"hidden"|"dropdown"|"checkbox",
description: string,
properties: {
key: string,
@@ -7,7 +7,7 @@ export interface QuestionInterface {
order: number,
methods?: Array<string>,
spezialization?: string,
specialization?: string,
// textbox
type?: string,
@@ -19,7 +19,10 @@ export interface QuestionInterface {
// dropdown & flag
options?: {key: string, value: string}[],
},
constraints: {
constraints: QuestionInterfaceCnstr
}
export interface QuestionInterfaceCnstr {
optional: boolean,
// textbox - string
@@ -27,5 +30,4 @@ export interface QuestionInterface {
// textbox - number
maxValue?: number
}
}

View File

@@ -1,8 +0,0 @@
import { Injectable } from '@angular/core';
@Injectable()
export class HelloService {
sayHello(): void {
console.log("Hello world from my Service!");
}
}

View File

@@ -7,7 +7,7 @@ import { ResponseInterface } from './response.interface';
export class HttpCachedService extends HttpService {
private _stored: any = {}; // {data: ResponseInterface, e: Response}
get refreshTime() {
static get refreshTime() {
return 3*1000;
}
@@ -16,45 +16,44 @@ export class HttpCachedService extends HttpService {
}
getJSON(uri: string, query: {[propName: string]: any}, dataFunc: (data: ResponseInterface, e: Response | any) => void) {
var hash: string = this._hashRequest("GET", uri, query);
const hash: string = this._hashRequest('GET', uri, query);
if (this._stored.hasOwnProperty(hash)) {
if (this._stored[hash] instanceof Array) {
// pending request, add to event emitter
this._stored[hash].push(dataFunc);
} else {
// request alredy stored, send result
// request already stored, send result
dataFunc(this._stored[hash].data, this._stored[hash].e);
}
} else {
// fulfil request, no matching request stored
this._stored[hash] = [];
super.getJSON(uri, query, (data, e) => {
// request recieved, emit to caller and event subscriber
// request received, emit to caller and event subscriber
dataFunc(data, e);
for (var i = this._stored[hash].length - 1; i >= 0; i--) {
for (let i = this._stored[hash].length - 1; i >= 0; i--) {
this._stored[hash][i](data, e);
}
this._stored[hash] = {
data: data,
e: e
};
var that = this;
setTimeout(function() {
delete that._stored[hash];
}, this.refreshTime);
setTimeout(() => {
delete this._stored[hash];
}, HttpCachedService.refreshTime);
});
}
}
private _hashRequest(method: string, uri: string, query?: Object): string {
function objectToString(obj: Object = {}) {
var keys: string[] = [];
var result: string = '{';
for (var key in obj)
const keys: string[] = [];
let result: string = '{';
for (let key in obj)
if (obj.hasOwnProperty(key))
keys.push(key);
keys.sort();
for (var i = keys.length - 1; i >= 0; i--) {
for (let i = keys.length - 1; i >= 0; i--) {
result += keys[i]+':"'+obj[keys[i]]+'",'
}
result += '}';

View File

@@ -5,7 +5,7 @@ import { HttpBaseService } from './http-base.service';
@Injectable()
export class HttpService extends HttpBaseService {
get httpBase() {
return "http://ccrruby1-1:3085";
return "http://localhost:5000";
//return '/public/mocks';
}
get httpSuffix() {

View File

@@ -4,8 +4,8 @@
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"mapRoot":"/src/",
"sourceRoot":"/src/",
"mapRoot":"/",
"sourceRoot":"/src/app",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"lib": [ "es2015", "dom" ],