-
Notifications
You must be signed in to change notification settings - Fork 6
/
property-form.component.ts
595 lines (485 loc) · 23 KB
/
property-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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
import { Component, EventEmitter, Inject, Input, OnInit, Output } from '@angular/core';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
import {
ApiResponseError,
ClassDefinition,
Constants,
CreateResourceProperty,
IHasProperty,
KnoraApiConnection,
ListNodeInfo,
PropertyDefinition,
ReadOntology,
ResourceClassDefinitionWithAllLanguages,
ResourcePropertyDefinitionWithAllLanguages,
StringLiteral,
UpdateOntology,
UpdateResourceClassCardinality,
UpdateResourcePropertyComment,
UpdateResourcePropertyGuiElement,
UpdateResourcePropertyLabel
} from '@dasch-swiss/dsp-js';
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 { AutocompleteItem } from 'src/app/workspace/search/advanced-search/resource-and-property-selection/search-select-property/specify-property-value/operator';
import { DefaultProperties, DefaultProperty, PropertyCategory, PropertyInfoObject } from '../default-data/default-properties';
import { OntologyService } from '../ontology.service';
@Component({
selector: 'app-property-form',
templateUrl: './property-form.component.html',
styleUrls: ['./property-form.component.scss']
})
export class PropertyFormComponent implements OnInit {
/**
* propertyInfo contains default property type information
* and in case of 'edit' mode also the ResourcePropertyDefintion
*/
@Input() propertyInfo: PropertyInfoObject;
/**
* iri of resClassIri; will be used to set cardinality
*/
@Input() resClassIri?: string;
/**
* info if the cardinality can be fully set or not
* (depending on canReplaceCardinalityOfResourceClass request)
*/
@Input() canSetFullCardinality?: boolean = true;
/**
* position of property in case of cardinality update
*/
@Input() guiOrder?: number = 0;
/**
* output closeDialog of property form component to update parent component
*/
@Output() closeDialog: EventEmitter<any> = new EventEmitter<any>();
/**
* form group, errors and validation messages
*/
propertyForm: FormGroup;
formErrors = {
'name': '',
'label': '',
'guiAttr': ''
};
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.',
},
'guiAttr': {
'required': 'Gui attribute is required.',
}
};
ontology: ReadOntology;
lastModificationDate: string;
// selection of default property types
defaultProperties: PropertyCategory[] = DefaultProperties.data;
// selection of possible property types in case of edit prop
restrictedPropertyTypes: PropertyCategory[];
showGuiAttr = false;
guiAttrIcon = 'tune';
// list of project specific lists (TODO: probably we have to add default knora lists?!)
lists: ListNodeInfo[];
// resource classes in this ontology
resourceClasses: ClassDefinition[] = [];
loading = false;
error = false;
labels: StringLiteral[] = [];
labelsTouched: boolean;
comments: StringLiteral[] = [];
guiAttributes: string[] = [];
// list of existing property names
existingNames: [RegExp] = [
new RegExp('anEmptyRegularExpressionWasntPossible')
];
dspConstants = Constants;
constructor(
@Inject(DspApiConnectionToken) private _dspApiConnection: KnoraApiConnection,
private _cache: CacheService,
private _errorHandler: ErrorHandlerService,
private _fb: FormBuilder,
private _os: OntologyService
) { }
ngOnInit() {
this.loading = true;
this._cache.get('currentOntology').subscribe(
(response: ReadOntology) => {
this.ontology = response;
this.lastModificationDate = response.lastModificationDate;
// set various lists to select from
// a) in case of link value:
// set list of resource classes from response; needed for linkValue
this.resourceClasses = response.getAllClassDefinitions();
const resourceProperties = response.getAllPropertyDefinitions();
// set list of all existing resource property names to avoid same name twice
resourceProperties.forEach((resProp: PropertyDefinition) => {
const name = this._os.getNameFromIri(resProp.id);
this.existingNames.push(
new RegExp('(?:^|W)' + name.toLowerCase() + '(?:$|W)')
);
});
// add all resource classes to the same list
this.resourceClasses.forEach((resClass: ClassDefinition) => {
const name = this._os.getNameFromIri(resClass.id);
this.existingNames.push(
new RegExp('(?:^|W)' + name.toLowerCase() + '(?:$|W)')
);
});
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
// b) in case of list value:s
// set list of lists; needed for listValue
this._cache.get('currentOntologyLists').subscribe(
(response: ListNodeInfo[]) => {
this.lists = response;
}
);
this.buildForm();
}
buildForm() {
let disablePropType = true;
// if property definition exists
// we are in edit mode: prepare form to edit label and/or comment
// and to edit gui element (which is part of property type)
if (this.propertyInfo.propDef) {
this.labels = this.propertyInfo.propDef.labels;
this.comments = this.propertyInfo.propDef.comments;
this.guiAttributes = this.propertyInfo.propDef.guiAttributes;
// prepare list of restricted property types
this.restrictedPropertyTypes = [{
group: this.propertyInfo.propType.group,
elements: []
}];
// filter property types by group
const restrictedElements: DefaultProperty[] = this.filterPropertyTypesByGroup(this.propertyInfo.propType.group);
// slice array
// this slice value will be kept
// because there was the idea to shorten the array of restricted elements
// in case e.g. richtext can't be changed to simple text, then we shouldn't list the simple text item
const slice = 0;
// there's only the object type "text", where we can change the gui element;
disablePropType = (this.propertyInfo.propType.objectType !== Constants.TextValue);
this.restrictedPropertyTypes[0].elements = restrictedElements.slice(slice);
} else {
this.restrictedPropertyTypes = this.defaultProperties;
}
this.propertyForm = this._fb.group({
'name': new FormControl({
value: (this.propertyInfo.propDef ? this._os.getNameFromIri(this.propertyInfo.propDef.id) : ''),
disabled: this.propertyInfo.propDef
}, [
Validators.required,
existingNamesValidator(this.existingNames),
Validators.pattern(CustomRegex.ID_NAME_REGEX)
]),
'propType': new FormControl({
value: this.propertyInfo.propType,
disabled: disablePropType || this.resClassIri
}),
'guiAttr': new FormControl({
value: this.guiAttributes
}),
'multiple': new FormControl({
value: '', // --> TODO: will be set in update cardinality task
disabled: this.propertyInfo.propType.objectType === Constants.BooleanValue
// --> TODO: here we also have to check, if it can be updated (update cardinality task);
// case updateCardinality: disabled if !canSetFullCardinality && multiple.value !== true
}),
'required': new FormControl({
value: '', // --> TODO: will be set in update cardinality task
disabled: !this.canSetFullCardinality
})
});
this.updateAttributeField(this.propertyInfo.propType);
this.propertyForm.valueChanges
.subscribe(data => this.onValueChanged(data));
}
/**
* this method is for the form error handling
*
* @param data Data which changed.
*/
onValueChanged(data?: any) {
if (!this.propertyForm) {
return;
}
Object.keys(this.formErrors).map(field => {
this.formErrors[field] = '';
const control = this.propertyForm.get(field);
if (control && control.dirty && !control.valid) {
const messages = this.validationMessages[field];
Object.keys(control.errors).map(key => {
this.formErrors[field] += messages[key] + ' ';
});
}
});
}
handleData(data: StringLiteral[], type: 'label' | 'comment') {
switch (type) {
case 'label':
this.labels = data;
const messages = this.validationMessages[type];
this.formErrors[type] = '';
if (this.labelsTouched && !this.labels.length) {
this.formErrors[type] = messages['required'];
}
break;
case 'comment':
this.comments = data;
break;
}
}
/**
* filter a list while typing in auto complete input field
* @param list List of options
* @param label Value to filter by
* @returns Filtered list of options
*/
filter(list: AutocompleteItem[], label: string) {
return list.filter(prop =>
prop.label?.toLowerCase().includes(label.toLowerCase())
);
}
/**
* filters property types by group; it's used
* in case of editing a property to restrict
* the list of property types and elements
* @param group
* @returns an array of elements
*/
filterPropertyTypesByGroup(group: string): DefaultProperty[] {
const groups: PropertyCategory[] = this.defaultProperties.filter(item => item.group === group);
return (groups.length ? groups[0].elements : []);
}
updateAttributeField(type: DefaultProperty) {
// reset value of guiAttr
this.propertyForm.controls['guiAttr'].setValue(undefined);
// set gui attribute value depending on gui element and existing property (edit mode)
if (this.propertyInfo.propDef) {
// the gui attribute can't be changed (at the moment?);
// disable the input and set the validator as not required
this.propertyForm.controls['guiAttr'].disable();
switch (type.guiEle) {
// prop type is a list
case Constants.SalsahGui + Constants.HashDelimiter + 'List':
case Constants.SalsahGui + Constants.HashDelimiter + 'Radio':
this.showGuiAttr = true;
// gui attribute value for lists looks as follow: hlist=<http://rdfh.ch/lists/00FF/73d0ec0302>
// get index from guiAttr array where value starts with hlist=
const i = this.guiAttributes.findIndex(element => element.includes('hlist'));
// find content beteween pointy brackets to get list iri
const re = /\<([^)]+)\>/;
const listIri = this.guiAttributes[i].match(re)[1];
this.propertyForm.controls['guiAttr'].setValue(listIri);
break;
// prop type is resource pointer
case Constants.SalsahGui + Constants.HashDelimiter + 'Searchbox':
this.showGuiAttr = true;
this.propertyForm.controls['guiAttr'].setValue(this.propertyInfo.propDef.objectType);
break;
default:
this.showGuiAttr = false;
}
} else {
// depending on the selected property type,
// we have to define gui element attributes
// e.g. iri of list or connected resource class
switch (type.objectType) {
case Constants.ListValue:
case Constants.LinkValue:
this.showGuiAttr = true;
this.propertyForm.controls['guiAttr'].setValidators([
Validators.required
]);
// this.propertyForm.controls['guiAttr'].updateValueAndValidity();
this.propertyForm.updateValueAndValidity();
break;
default:
this.showGuiAttr = false;
}
}
this.loading = false;
}
submitData() {
this.loading = true;
// the property exist already; update label, comment and/or gui element
if (this.propertyInfo.propDef) {
if (this.resClassIri) {
// set cardinality with existing property in res class
this.setCardinality(this.propertyInfo.propDef);
} else {
// edit property mode: update res property info (label and comment) or gui element and attribute
// label
const onto4Label = new UpdateOntology<UpdateResourcePropertyLabel>();
onto4Label.id = this.ontology.id;
onto4Label.lastModificationDate = this.lastModificationDate;
const updateLabel = new UpdateResourcePropertyLabel();
updateLabel.id = this.propertyInfo.propDef.id;
updateLabel.labels = this.labels;
onto4Label.entity = updateLabel;
// comment
const onto4Comment = new UpdateOntology<UpdateResourcePropertyComment>();
onto4Comment.id = this.ontology.id;
const updateComment = new UpdateResourcePropertyComment();
updateComment.id = this.propertyInfo.propDef.id;
updateComment.comments = (this.comments.length ? this.comments : this.labels);
onto4Comment.entity = updateComment;
this._dspApiConnection.v2.onto.updateResourceProperty(onto4Label).subscribe(
(classLabelResponse: ResourcePropertyDefinitionWithAllLanguages) => {
this.lastModificationDate = classLabelResponse.lastModificationDate;
onto4Comment.lastModificationDate = this.lastModificationDate;
this._dspApiConnection.v2.onto.updateResourceProperty(onto4Comment).subscribe(
(classCommentResponse: ResourcePropertyDefinitionWithAllLanguages) => {
this.lastModificationDate = classCommentResponse.lastModificationDate;
const onto4guiEle = new UpdateOntology<UpdateResourcePropertyGuiElement>();
onto4guiEle.id = this.ontology.id;
onto4guiEle.lastModificationDate = this.lastModificationDate;
const updateGuiEle = new UpdateResourcePropertyGuiElement();
updateGuiEle.id = this.propertyInfo.propDef.id;
updateGuiEle.guiElement = this.propertyForm.controls['propType'].value.guiEle;
const guiAttr = this.propertyForm.controls['guiAttr'].value;
if (guiAttr) {
updateGuiEle.guiAttributes = this.setGuiAttribute(guiAttr);
}
onto4guiEle.entity = updateGuiEle;
this._dspApiConnection.v2.onto.replaceGuiElementOfProperty(onto4guiEle).subscribe(
(guiEleResponse: ResourcePropertyDefinitionWithAllLanguages) => {
this.lastModificationDate = guiEleResponse.lastModificationDate;
// close the dialog box
this.loading = false;
this.closeDialog.emit();
},
(error: ApiResponseError) => {
this.error = true;
this.loading = false;
this._errorHandler.showMessage(error);
}
);
},
(error: ApiResponseError) => {
this.error = true;
this.loading = false;
this._errorHandler.showMessage(error);
}
);
},
(error: ApiResponseError) => {
this.error = true;
this.loading = false;
this._errorHandler.showMessage(error);
}
);
}
} else {
// create mode: new property incl. gui type and attribute
// submit property
// set resource property name / id: randomized string
// const uniquePropName: string = this._os.setUniqueName(this.ontology.id);
const onto = new UpdateOntology<CreateResourceProperty>();
onto.id = this.ontology.id;
onto.lastModificationDate = this.lastModificationDate;
// prepare payload for property
const newResProp = new CreateResourceProperty();
newResProp.name = this.propertyForm.controls['name'].value;
newResProp.label = this.labels;
newResProp.comment = (this.comments.length ? this.comments : this.labels);
const guiAttr = this.propertyForm.controls['guiAttr'].value;
if (guiAttr) {
newResProp.guiAttributes = this.setGuiAttribute(guiAttr);
}
newResProp.guiElement = this.propertyInfo.propType.guiEle;
newResProp.subPropertyOf = [this.propertyInfo.propType.subPropOf];
if (this.propertyInfo.propType.subPropOf === Constants.HasLinkTo || this.propertyInfo.propType.subPropOf === Constants.KnoraApiV2 + Constants.HashDelimiter + 'isPartOf') {
newResProp.objectType = guiAttr;
newResProp.subjectType = this.resClassIri;
} else {
newResProp.objectType = this.propertyInfo.propType.objectType;
}
onto.entity = newResProp;
this._dspApiConnection.v2.onto.createResourceProperty(onto).subscribe(
(response: ResourcePropertyDefinitionWithAllLanguages) => {
this.lastModificationDate = response.lastModificationDate;
if (this.resClassIri && response.lastModificationDate) {
// set cardinality
this.setCardinality(response);
} else {
// close the dialog box
this.loading = false;
this.closeDialog.emit();
}
},
(error: ApiResponseError) => {
this.error = true;
this.loading = false;
this._errorHandler.showMessage(error);
}
);
}
}
setCardinality(prop: ResourcePropertyDefinitionWithAllLanguages) {
const onto = new UpdateOntology<UpdateResourceClassCardinality>();
onto.lastModificationDate = this.lastModificationDate;
onto.id = this.ontology.id;
const addCard = new UpdateResourceClassCardinality();
addCard.id = this.resClassIri;
addCard.cardinalities = [];
const propCard: IHasProperty = {
propertyIndex: prop.id,
cardinality: this._os.translateCardinality(this.propertyForm.value.multiple, this.propertyForm.value.required),
guiOrder: this.guiOrder // add new property to the end of current list of properties
};
addCard.cardinalities.push(propCard);
onto.entity = addCard;
this._dspApiConnection.v2.onto.addCardinalityToResourceClass(onto).subscribe(
(res: ResourceClassDefinitionWithAllLanguages) => {
this.lastModificationDate = res.lastModificationDate;
// close the dialog box
this.loading = false;
this.closeDialog.emit();
},
(error: ApiResponseError) => {
this.error = true;
this.loading = false;
this._errorHandler.showMessage(error);
}
);
}
setGuiAttribute(guiAttr: string): string[] {
let guiAttributes: string[];
switch (this.propertyInfo.propType.guiEle) {
case Constants.SalsahGui + Constants.HashDelimiter + 'Colorpicker':
guiAttributes = ['ncolors=' + guiAttr];
break;
case Constants.SalsahGui + Constants.HashDelimiter + 'List':
case Constants.SalsahGui + Constants.HashDelimiter + 'Pulldown':
case Constants.SalsahGui + Constants.HashDelimiter + 'Radio':
guiAttributes = ['hlist=<' + guiAttr + '>'];
break;
case Constants.SalsahGui + Constants.HashDelimiter + 'SimpleText':
// --> TODO could have two guiAttr fields: size and maxlength
// we suggest to use default value for size; we do not support this guiAttr in DSP-App
guiAttributes = ['maxlength=' + guiAttr];
break;
case Constants.SalsahGui + Constants.HashDelimiter + 'Spinbox':
// --> TODO could have two guiAttr fields: min and max
guiAttributes = ['min=' + guiAttr, 'max=' + guiAttr];
break;
case Constants.SalsahGui + Constants.HashDelimiter + 'Textarea':
// --> TODO could have four guiAttr fields: width, cols, rows, wrap
// we suggest to use default values; we do not support this guiAttr in DSP-App
guiAttributes = ['width=100%'];
break;
}
return guiAttributes;
}
}