/
resource-class-form.component.ts
379 lines (309 loc) · 12.7 KB
/
resource-class-form.component.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
import { AfterViewChecked, ChangeDetectorRef, Component, EventEmitter, Inject, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import {
ApiResponseError,
ClassDefinition,
CreateResourceClass,
KnoraApiConnection,
PropertyDefinition,
ReadOntology,
ResourceClassDefinitionWithAllLanguages,
StringLiteral,
UpdateOntology,
UpdateResourceClassComment,
UpdateResourceClassLabel
} from '@dasch-swiss/dsp-js';
import { StringLiteralV2 } from '@dasch-swiss/dsp-js/src/models/v2/string-literal-v2';
import { AppGlobal } from 'src/app/app-global';
import { CacheService } from 'src/app/main/cache/cache.service';
import { DspApiConnectionToken } from 'src/app/main/declarations/dsp-api-tokens';
import { existingNamesValidator } from 'src/app/main/directive/existing-name/existing-name.directive';
import { ErrorHandlerService } from 'src/app/main/error/error-handler.service';
import { CustomRegex } from 'src/app/workspace/resource/values/custom-regex';
import { OntologyService } from '../ontology.service';
// nested form components; solution from:
// https://medium.com/@joshblf/dynamic-nested-reactive-forms-in-angular-654c1d4a769a
@Component({
selector: 'app-resource-class-form',
templateUrl: './resource-class-form.component.html',
styleUrls: ['./resource-class-form.component.scss']
})
export class ResourceClassFormComponent implements OnInit, AfterViewChecked {
/**
* current project shortcode
*/
@Input() projectCode: string;
/**
* create mode: iri selected resource class is a subclass from knora base (baseClassIri)
* edit mode: iri of resource class
* e.g. knora-api:StillImageRepresentation
*/
@Input() iri: string;
/**
* name of resource class type e.g. Still image
* this will be used to update title of resource class form
*/
@Input() name: string;
/**
* edit mode (true); otherwise create mode
*/
@Input() edit: boolean;
/**
* emit event, when closing dialog
*/
@Output() closeDialog: EventEmitter<any> = new EventEmitter<any>();
/**
* update title and subtitle in dialog header (by switching from step 1 (resource class) to step 2 (properties))
*/
@Output() updateParent: EventEmitter<{ title: string; subtitle: string }> = new EventEmitter<{ title: string; subtitle: string }>();
// store name as resourceClassTitle on init; in this case it can't be overwritten in the next / prev navigation
resourceClassTitle: string;
// current ontology; will get it from cache by key 'currentOntology'
ontology: ReadOntology;
// success of sending data
success = false;
// message after successful post
successMessage: any = {
status: 200,
statusText: 'You have successfully updated the resource class and all properties'
};
// progress
loading: boolean;
// in case of an error
error: boolean;
// form group, form array (for properties) errors and validation messages
resourceClassForm: FormGroup;
// label and comment are stringLiterals
resourceClassLabels: StringLiteralV2[] = [];
resourceClassLabelsTouched: boolean;
resourceClassComments: StringLiteralV2[] = [];
resourceClassCommentsTouched: boolean;
// list of existing class names
existingNames: [RegExp] = [
new RegExp('anEmptyRegularExpressionWasntPossible')
];
// form errors on the following fields:
formErrors = {
'name': '',
'label': '',
'comment': ''
};
// in case of form error: show message
validationMessages = {
'name': {
'required': 'Name is required.',
'existingName': 'This name is already taken. Please choose another one.',
'pattern': 'Name shouldn\'t start with a number or v + number and spaces or special characters (except dash, dot and underscore) are not allowed.'
},
'label': {
'required': 'Label is required.'
},
'comment': {
'required': 'Comment is required.'
}
};
lastModificationDate: string;
// for the language selector
selectedLanguage = 'en';
languages: StringLiteral[] = AppGlobal.languagesList;
constructor(
@Inject(DspApiConnectionToken) private _dspApiConnection: KnoraApiConnection,
private _cache: CacheService,
private _cdr: ChangeDetectorRef,
private _errorHandler: ErrorHandlerService,
private _fb: FormBuilder,
private _os: OntologyService
) { }
ngOnInit() {
// set file representation or default resource class as title
this.resourceClassTitle = this.name;
this._cache.get('currentOntology').subscribe(
(response: ReadOntology) => {
this.ontology = response;
this.lastModificationDate = this.ontology.lastModificationDate;
const resourceClasses = response.getAllClassDefinitions();
const resourceProperties = response.getAllPropertyDefinitions();
// set list of all existing resource class names to avoid same name twice
resourceClasses.forEach((resClass: ClassDefinition) => {
const name = this._os.getNameFromIri(resClass.id);
this.existingNames.push(
new RegExp('(?:^|W)' + name.toLowerCase() + '(?:$|W)')
);
});
// add all resource properties to the same list
resourceProperties.forEach((resProp: PropertyDefinition) => {
const name = this._os.getNameFromIri(resProp.id);
this.existingNames.push(
new RegExp('(?:^|W)' + name.toLowerCase() + '(?:$|W)')
);
});
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
this.buildForm();
this._cdr.detectChanges();
}
ngAfterViewChecked() {
this._cdr.detectChanges();
}
//
// form handling:
buildForm() {
if (this.edit) {
// edit mode: res class info (label and comment)
// get resource class info
const resourceClasses: ResourceClassDefinitionWithAllLanguages[] = this.ontology.getClassDefinitionsByType(ResourceClassDefinitionWithAllLanguages);
Object.keys(resourceClasses).forEach(key => {
if (resourceClasses[key].id === this.iri) {
this.resourceClassLabels = resourceClasses[key].labels;
this.resourceClassComments = resourceClasses[key].comments;
}
});
}
this.resourceClassForm = this._fb.group({
name: new FormControl({
value: (this.edit ? this._os.getNameFromIri(this.iri) : ''),
disabled: this.edit
}, [
Validators.required,
existingNamesValidator(this.existingNames),
Validators.pattern(CustomRegex.ID_NAME_REGEX)
]),
label: new FormControl({
value: this.resourceClassLabels, disabled: false
}, [
Validators.required
]),
comment: new FormControl({
value: this.resourceClassComments, disabled: false
}, [
Validators.required
])
});
this.resourceClassForm.valueChanges.subscribe(data => this.onValueChanged(data));
}
onValueChanged(data?: any) {
if (!this.resourceClassForm) {
return;
}
Object.keys(this.formErrors).map(field => {
this.formErrors[field] = '';
const control = this.resourceClassForm.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
Object.keys(control.errors).map(key => {
this.formErrors[field] += messages[key] + ' ';
});
}
});
}
/**
* set stringLiterals for label or comment from dsp-string-literal-input
* @param {StringLiteral[]} data
* @param {string} type
*/
handleData(data: StringLiteral[], type: 'label' | 'comment') {
switch (type) {
case 'label':
this.resourceClassLabels = data;
this.handleError(this.resourceClassLabelsTouched, type);
break;
case 'comment':
this.resourceClassComments = data;
this.handleError(this.resourceClassCommentsTouched, type);
break;
}
}
/**
* error handle for string literals input
* @param touched
* @param type
*/
handleError(touched: boolean, type: 'label' | 'comment') {
const checkValue = (type === 'label' ? this.resourceClassLabels : this.resourceClassComments);
const messages = this.validationMessages[type];
this.formErrors[type] = '';
if (touched && !checkValue.length) {
this.formErrors[type] = messages['required'];
}
}
//
// submit
/**
* submit data to create resource class with properties and cardinalities
*/
submitData() {
this.loading = true;
if (this.edit) {
// edit mode: res class info (label and comment)
// label
const onto4Label = new UpdateOntology<UpdateResourceClassLabel>();
onto4Label.id = this.ontology.id;
onto4Label.lastModificationDate = this.lastModificationDate;
const updateLabel = new UpdateResourceClassLabel();
updateLabel.id = this.iri;
updateLabel.labels = this.resourceClassLabels;
onto4Label.entity = updateLabel;
// comment
const onto4Comment = new UpdateOntology<UpdateResourceClassComment>();
onto4Comment.id = this.ontology.id;
const updateComment = new UpdateResourceClassComment();
updateComment.id = this.iri;
updateComment.comments = this.resourceClassComments;
onto4Comment.entity = updateComment;
this._dspApiConnection.v2.onto.updateResourceClass(onto4Label).subscribe(
(classLabelResponse: ResourceClassDefinitionWithAllLanguages) => {
this.lastModificationDate = classLabelResponse.lastModificationDate;
onto4Comment.lastModificationDate = this.lastModificationDate;
this._dspApiConnection.v2.onto.updateResourceClass(onto4Comment).subscribe(
(classCommentResponse: ResourceClassDefinitionWithAllLanguages) => {
this.lastModificationDate = classCommentResponse.lastModificationDate;
// close the dialog box
this.loading = false;
this.closeDialog.emit();
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
} else {
// create mode
// submit resource class data to knora and create resource class incl. cardinality
const onto = new UpdateOntology<CreateResourceClass>();
onto.id = this.ontology.id;
onto.lastModificationDate = this.lastModificationDate;
const newResClass = new CreateResourceClass();
newResClass.name = this.resourceClassForm.controls['name'].value;
newResClass.label = this.resourceClassLabels;
newResClass.comment = this.resourceClassComments;
newResClass.subClassOf = [this.iri];
onto.entity = newResClass;
this._dspApiConnection.v2.onto.createResourceClass(onto).subscribe(
(classResponse: ResourceClassDefinitionWithAllLanguages) => {
// need lmd from classResponse
this.lastModificationDate = classResponse.lastModificationDate;
// close the dialog box
this.loading = false;
this.closeDialog.emit();
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
}
}
/**
* close dialog box and reset all forms
*/
closeMessage() {
this.resourceClassForm.reset();
this.closeDialog.emit();
}
}