/
resource-class-info.component.ts
517 lines (411 loc) · 19 KB
/
resource-class-info.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
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { Component, EventEmitter, Inject, Input, OnInit, Output } from '@angular/core';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import {
ApiResponseError,
CanDoResponse,
ClassDefinition,
Constants,
IHasProperty,
KnoraApiConnection,
PropertyDefinition,
ReadOntology,
ResourceClassDefinitionWithAllLanguages,
ResourcePropertyDefinitionWithAllLanguages,
UpdateOntology,
UpdateResourceClassCardinality
} 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 { DialogComponent } from 'src/app/main/dialog/dialog.component';
import { ErrorHandlerService } from 'src/app/main/services/error-handler.service';
import { NotificationService } from 'src/app/main/services/notification.service';
import { SortingService } from 'src/app/main/services/sorting.service';
import { DefaultProperties, DefaultProperty, PropertyCategory, PropertyInfoObject } from '../default-data/default-properties';
import { DefaultClass, DefaultResourceClasses } from '../default-data/default-resource-classes';
import { CardinalityInfo, OntologyProperties } from '../ontology.component';
import { OntologyService } from '../ontology.service';
export interface PropToDisplay extends IHasProperty {
propDef?: PropertyDefinition;
}
export interface PropToAdd {
ontologyId: string;
ontologyLabel: string;
properties: PropertyInfoObject[];
}
@Component({
selector: 'app-resource-class-info',
templateUrl: './resource-class-info.component.html',
styleUrls: ['./resource-class-info.component.scss']
})
export class ResourceClassInfoComponent implements OnInit {
// open / close res class card
@Input() expanded = false;
@Input() resourceClass: ClassDefinition;
@Input() projectCode: string;
@Input() projectStatus: boolean;
@Input() ontologies: ReadOntology[] = [];
@Input() lastModificationDate?: string;
// event emitter when the lastModificationDate changed; bidirectional binding with lastModificationDate parameter
@Output() lastModificationDateChange: EventEmitter<string> = new EventEmitter<string>();
// event emitter when the lastModificationDate changed; bidirectional binding with lastModificationDate parameter
@Output() ontoPropertiesChange: EventEmitter<PropertyDefinition[]> = new EventEmitter<PropertyDefinition[]>();
// to update the resource class itself (edit or delete)
@Output() editResourceClass: EventEmitter<DefaultClass> = new EventEmitter<DefaultClass>();
@Output() deleteResourceClass: EventEmitter<DefaultClass> = new EventEmitter<DefaultClass>();
// to update the cardinality we need the information about property (incl. propType) and resource class
@Output() updateCardinality: EventEmitter<string> = new EventEmitter<string>();
ontology: ReadOntology;
// list of all ontologies with their properties
ontoProperties: OntologyProperties[] = [];
cardinalityUpdateEnabled: boolean;
classCanBeDeleted: boolean;
classCanReplaceCardinality: boolean;
// list of properties that can be displayed (not all of the props should be displayed)
propsToDisplay: PropToDisplay[] = [];
subClassOfLabel = '';
// list of default resource classes
defaultClasses: DefaultClass[] = DefaultResourceClasses.data;
// list of default property types
defaultProperties: PropertyCategory[] = DefaultProperties.data;
// list of existing ontology properties, which are not in this resource class
existingProperties: PropToAdd[];
// load single property (in case of property cardinality action)
loadProperty = false;
constructor(
@Inject(DspApiConnectionToken) private _dspApiConnection: KnoraApiConnection,
private _cache: CacheService,
private _dialog: MatDialog,
private _errorHandler: ErrorHandlerService,
private _notification: NotificationService,
private _ontoService: OntologyService,
private _sortingService: SortingService
) { }
ngOnInit(): void {
// grab the onto properties information to display
this.ontoProperties = [];
// get all project ontologies
this._cache.get('currentProjectOntologies').subscribe(
(ontologies: ReadOntology[]) => {
this.ontologies = ontologies;
ontologies.forEach(onto => {
const prepareList: OntologyProperties = {
ontology: onto.id,
properties: this.initOntoProperties(onto.getAllPropertyDefinitions())
};
this.ontoProperties.push(prepareList);
});
}
);
// get currently selected ontology
this._cache.get('currentOntology').subscribe(
(response: ReadOntology) => {
this.ontology = response;
this.lastModificationDate = this.ontology.lastModificationDate;
// translate iris from "sub class of" array
this.translateSubClassOfIri(this.resourceClass.subClassOf);
// prepare list of properties to display
this.preparePropsToDisplay(this.resourceClass.propertiesList);
// check if the class can be deleted
this.canBeDeleted();
// check if the cardinalities can be changed
this.canReplaceCardinality();
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
}
/**
* translates iris from "sub class of" array
* - display label from default resource classes (as part of DSP System Project)
* - in case the class is a subclass of another class in the same ontology: display this class label
* - in none of those cases display the name from the class IRI
*
* @param classIris
*/
translateSubClassOfIri(classIris: string[]) {
// reset the label
this.subClassOfLabel = '';
classIris.forEach((iri, index) => {
// get ontology iri from class iri
const splittedIri = iri.split('#');
const ontologyIri = splittedIri[0];
const className = splittedIri[1];
this.subClassOfLabel += (index > 0 ? ', ' : '');
// find default class for the current class iri
const defaultClass = this.defaultClasses.find(i => i.iri === iri);
if (defaultClass) {
this.subClassOfLabel += defaultClass.label;
this.cardinalityUpdateEnabled = true;
} else if (this.ontology.id === ontologyIri) {
// the class is not defined in the default classes
// but defined in the current ontology
// get class label from there
this.subClassOfLabel += this.ontology.classes[iri].label;
// in this case, the user can't update the cardinality incl. the gui order in this class
// we have to disable this update cardinality functionality
this.cardinalityUpdateEnabled = false;
} else {
// the ontology iri of the upper class couldn't be found
// display the class name
if (className) {
this.subClassOfLabel += className;
} else {
// iri is not kind of [ontologyIri]#[className]
this.subClassOfLabel += iri.split('/').filter(e => e).slice(-1);
}
// in this case, the user can't update the cardinality incl. the gui order in this class
// we have to disable this update cardinality functionality
this.cardinalityUpdateEnabled = false;
}
});
}
initOntoProperties(allOntoProperties: PropertyDefinition[]): PropertyDefinition[] {
// reset the ontology properties
const listOfProperties = [];
// display only the properties which are not a subjectType of Standoff
allOntoProperties.forEach(resProp => {
const standoff = (resProp.subjectType ? resProp.subjectType.includes('Standoff') : false);
if (resProp.objectType !== Constants.LinkValue && !standoff) {
listOfProperties.push(resProp);
}
});
// sort properties by label
// --> TODO: add sort functionallity to the gui
return this._sortingService.keySortByAlphabetical(listOfProperties, 'label');
}
/**
* prepares props to display
* Not all props should be displayed; there are some system / API-specific
* properties which have to be filtered.
*
* @param props
*/
preparePropsToDisplay(classProps: PropToDisplay[]) {
// reset existing properties to select from
this.existingProperties = [];
classProps.forEach((hasProp: PropToDisplay) => {
const ontoIri = hasProp.propertyIndex.split(Constants.HashDelimiter)[0];
// ignore http://api.knora.org/ontology/knora-api/v2 and ignore http://www.w3.org/2000/01/rdf-schema
if (ontoIri !== Constants.KnoraApiV2 && ontoIri !== Constants.Rdfs) {
// get property definition from list of project ontologies
const index = this.ontoProperties.findIndex((item: OntologyProperties) => item.ontology === ontoIri);
hasProp.propDef = this.ontoProperties[index].properties.find((obj: ResourcePropertyDefinitionWithAllLanguages) =>
obj.id === hasProp.propertyIndex &&
((obj.subjectType && !obj.subjectType.includes('Standoff')) && obj.objectType !== Constants.LinkValue || !obj.isLinkValueProperty)
);
// propDef was found, add hasProp to the properties list which has to be displayed in this resource class
if (hasProp.propDef) {
if (this.propsToDisplay.indexOf(hasProp) === -1) {
this.propsToDisplay.push(hasProp);
}
// and remove from list of existing properties to avoid double cardinality entries
// because the prop displayed in the class cannot be added a second time,
// so we have to hide it from the list of "Add existing property"
const delProp = this.ontoProperties[index].properties.indexOf(hasProp.propDef, 0);
if (delProp > -1) {
this.ontoProperties[index].properties.splice(delProp, 1);
}
}
}
});
this.ontoProperties.forEach((op: OntologyProperties, i: number) => {
this.existingProperties.push({
ontologyId: op.ontology,
ontologyLabel: this.ontologies[i].label,
properties: []
});
op.properties.forEach((availableProp: ResourcePropertyDefinitionWithAllLanguages) => {
const superProp = this._ontoService.getSuperProperty(availableProp);
if (superProp) {
if (availableProp.subPropertyOf.indexOf(superProp) === -1) {
availableProp.subPropertyOf.push(superProp);
}
}
let propType: DefaultProperty;
// find corresponding default property to have more prop info
this._ontoService.getDefaultPropType(availableProp).subscribe(
(prop: DefaultProperty) => {
propType = prop;
}
);
const propToAdd: PropertyInfoObject = {
propType: propType,
propDef: availableProp
};
this.existingProperties[i].properties.push(propToAdd);
});
});
}
canBeDeleted() {
// check if the class can be deleted
this._dspApiConnection.v2.onto.canDeleteResourceClass(this.resourceClass.id).subscribe(
(response: CanDoResponse) => {
this.classCanBeDeleted = response.canDo;
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
}
canReplaceCardinality() {
this._dspApiConnection.v2.onto.canReplaceCardinalityOfResourceClass(this.resourceClass.id).subscribe(
(response: CanDoResponse) => {
this.classCanReplaceCardinality = response.canDo;
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
}
addNewProperty(propType: DefaultProperty) {
const cardinality: CardinalityInfo = {
resClass: this.resourceClass,
property: {
propType: propType
}
};
this.updateCard(cardinality);
}
addExistingProperty(prop: PropertyInfoObject) {
const cardinality: CardinalityInfo = {
resClass: this.resourceClass,
property: {
propType: prop.propType,
propDef: prop.propDef,
}
};
this.updateCard(cardinality);
}
/**
* removes property from resource class
* @param property
*/
removeProperty(property: DefaultClass) {
this.loadProperty = true;
const onto = new UpdateOntology<UpdateResourceClassCardinality>();
onto.lastModificationDate = this.lastModificationDate;
onto.id = this.ontology.id;
const delCard = new UpdateResourceClassCardinality();
delCard.id = this.resourceClass.id;
delCard.cardinalities = [];
delCard.cardinalities = this.propsToDisplay.filter(prop => (prop.propertyIndex === property.iri));
onto.entity = delCard;
this._dspApiConnection.v2.onto.deleteCardinalityFromResourceClass(onto).subscribe(
(res: ResourceClassDefinitionWithAllLanguages) => {
this.lastModificationDate = res.lastModificationDate;
this.lastModificationDateChange.emit(this.lastModificationDate);
this.preparePropsToDisplay(this.propsToDisplay);
this.updateCardinality.emit(this.ontology.id);
// display success message
this._notification.openSnackBar(`You have successfully removed "${property.label}" from "${this.resourceClass.label}".`);
this.loadProperty = false;
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(<ApiResponseError>error);
}
);
}
/**
* updates cardinality
* @param card cardinality info object
*/
updateCard(card: CardinalityInfo) {
if (card) {
const classLabel = card.resClass.label;
let mode: 'createProperty' | 'updateCardinality' = 'createProperty';
let propLabel = card.property.propType.group + ': ' + card.property.propType.label;
let title = 'Add new property of type "' + propLabel + '" to class "' + classLabel + '"';
if (card.property.propDef) {
// the property exists already
mode = 'updateCardinality';
propLabel = card.property.propDef.label;
title = 'Add existing property "' + propLabel + '" to class "' + classLabel + '"';
}
const dialogConfig: MatDialogConfig = {
width: '640px',
maxHeight: '80vh',
position: {
top: '112px'
},
data: {
propInfo: card.property,
title: title,
subtitle: 'Customize property and cardinality',
mode: mode,
parentIri: card.resClass.id,
position: this.propsToDisplay.length + 1,
canBeUpdated: this.classCanReplaceCardinality
}
};
const dialogRef = this._dialog.open(
DialogComponent,
dialogConfig
);
dialogRef.afterClosed().subscribe(result => {
// update the view: list of properties in resource class
this.updateCardinality.emit(this.ontology.id);
});
}
}
/**
* drag and drop property line
*/
drop(event: CdkDragDrop<string[]>) {
// set sort order for child component
moveItemInArray(this.propsToDisplay, event.previousIndex, event.currentIndex);
if (event.previousIndex !== event.currentIndex) {
// the dropped property item has a new index (= gui order)
// send the new gui-order to the api by
// preparing the UpdateOntology object first
const onto = new UpdateOntology<UpdateResourceClassCardinality>();
onto.lastModificationDate = this.lastModificationDate;
onto.id = this.ontology.id;
const addCard = new UpdateResourceClassCardinality();
addCard.id = this.resourceClass.id;
addCard.cardinalities = [];
this.propsToDisplay.forEach((prop, index) => {
const propCard: IHasProperty = {
propertyIndex: prop.propertyIndex,
cardinality: prop.cardinality,
guiOrder: index + 1
};
addCard.cardinalities.push(propCard);
});
onto.entity = addCard;
// send the request to the api
this._dspApiConnection.v2.onto.replaceGuiOrderOfCardinalities(onto).subscribe(
(responseGuiOrder: ResourceClassDefinitionWithAllLanguages) => {
this.lastModificationDate = responseGuiOrder.lastModificationDate;
// successful request: update the view
this.lastModificationDateChange.emit(this.lastModificationDate);
// display success message
this._notification.openSnackBar(`You have successfully changed the order of properties in the resource class "${this.resourceClass.label}".`);
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
}
}
/**
* opens resource instances in new tab using gravsearch
* @param iri
*/
openResource(iri: string) {
// open resource instances in new tab:
// it's important not to indent the gravsearch.
const gravsearch = `
PREFIX knora-api: <http://api.knora.org/ontology/knora-api/v2#>
CONSTRUCT {
?mainRes knora-api:isMainResource true .
} WHERE {
?mainRes a knora-api:Resource .
?mainRes a <${iri}> .
}
OFFSET 0`;
const doSearchRoute = `/search/gravsearch/${encodeURIComponent(gravsearch)}`;
window.open(doSearchRoute, '_blank');
}
}