/
properties.component.ts
574 lines (499 loc) · 21.8 KB
/
properties.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
import { Component, EventEmitter, Inject, Input, OnChanges, OnDestroy, OnInit, Output } from '@angular/core';
import { MatDialog, MatDialogConfig } from '@angular/material/dialog';
import { PageEvent } from '@angular/material/paginator';
import {
ApiResponseData,
ApiResponseError,
CardinalityUtil,
Constants, CountQueryResponse,
DeleteResource,
DeleteResourceResponse,
DeleteValue,
IHasPropertyWithPropertyDefinition,
KnoraApiConnection,
PermissionUtil,
ProjectResponse,
PropertyDefinition,
ReadLinkValue,
ReadProject,
ReadResource,
ReadResourceSequence,
ReadTextValueAsXml,
ReadUser,
ReadValue,
ResourcePropertyDefinition,
UpdateResourceMetadata,
UpdateResourceMetadataResponse,
UserResponse
} from '@dasch-swiss/dsp-js';
import { Subscription } from 'rxjs';
import { DspApiConnectionToken } from 'src/app/main/declarations/dsp-api-tokens';
import { ConfirmationWithComment, DialogComponent } from 'src/app/main/dialog/dialog.component';
import { ErrorHandlerService } from 'src/app/main/error/error-handler.service';
import { NotificationService } from 'src/app/main/services/notification.service';
import { DspResource } from '../dsp-resource';
import { IncomingService } from '../incoming.service';
import { RepresentationConstants } from '../representation/file-representation';
import { UserService } from '../services/user.service';
import {
AddedEventValue,
DeletedEventValue,
Events,
UpdatedEventValues,
ValueOperationEventService
} from '../services/value-operation-event.service';
import { ValueService } from '../services/value.service';
// object of property information from ontology class, properties and property values
export interface PropertyInfoValues {
guiDef: IHasPropertyWithPropertyDefinition;
propDef: PropertyDefinition;
values: ReadValue[];
}
@Component({
selector: 'app-properties',
templateUrl: './properties.component.html',
styleUrls: ['./properties.component.scss']
})
export class PropertiesComponent implements OnInit, OnChanges, OnDestroy {
/**
* input `resource` of properties component:
* complete information about the current resource
*/
@Input() resource: DspResource;
/**
* input `displayProjectInfo` of properties component:
* display project info or not; "This resource belongs to project XYZ"
*/
@Input() displayProjectInfo: false;
/**
* does the logged-in user has system or project admin permissions?
*/
@Input() adminPermissions: false;
/**
* is the logged-in user project member?
*/
@Input() editPermissions: false;
/**
* output `referredProjectClicked` of resource view component:
* can be used to go to project page
*/
@Output() referredProjectClicked: EventEmitter<ReadProject> = new EventEmitter<ReadProject>();
/**
* output `referredProjectHovered` of resource view component:
* can be used for preview when hovering on project
*/
@Output() referredProjectHovered: EventEmitter<ReadProject> = new EventEmitter<ReadProject>();
/**
* output `referredResourceClicked` of resource view component:
* can be used to open resource
*/
@Output() referredResourceClicked: EventEmitter<ReadLinkValue> = new EventEmitter<ReadLinkValue>();
/**
* output `referredResourceHovered` of resource view component:
* can be used for preview when hovering on resource
*/
@Output() referredResourceHovered: EventEmitter<ReadLinkValue> = new EventEmitter<ReadLinkValue>();
lastModificationDate: string;
deletedResource = false;
addButtonIsVisible: boolean; // used to toggle add value button
addValueFormIsVisible: boolean; // used to toggle add value form field
propID: string; // used in template to show only the add value form of the corresponding value
valueOperationEventSubscriptions: Subscription[] = []; // array of ValueOperationEvent subscriptions
representationConstants = RepresentationConstants;
hasIncomingLinkIri = Constants.KnoraApiV2 + Constants.HashDelimiter + 'hasIncomingLinkValue';
project: ReadProject;
user: ReadUser;
incomingLinkResources: ReadResource[] = [];
pageEvent: PageEvent;
numberOffAllIncomingLinkRes: number;
loading = false;
showAllProps = false; // show or hide empty properties
constructor(
@Inject(DspApiConnectionToken) private _dspApiConnection: KnoraApiConnection,
private _dialog: MatDialog,
private _errorHandler: ErrorHandlerService,
private _notification: NotificationService,
private _userService: UserService,
private _valueOperationEventService: ValueOperationEventService,
private _valueService: ValueService,
private _incomingService: IncomingService
) { }
ngOnInit(): void {
// reset the page event
this.pageEvent = new PageEvent();
this.pageEvent.pageIndex = 0;
this._getIncomingLinks();
if (this.resource.res) {
// get user permissions
const allPermissions = PermissionUtil.allUserPermissions(
this.resource.res.userHasPermission as 'RV' | 'V' | 'M' | 'D' | 'CR'
);
// get last modification date
this.lastModificationDate = this.resource.res.lastModificationDate;
// if user has modify permissions, set addButtonIsVisible to true so the user see's the add button
this.addButtonIsVisible = allPermissions.indexOf(PermissionUtil.Permissions.M) !== -1;
}
// listen for the AddValue event to be emitted and call hideAddValueForm()
// this._valueOperationEventService.on(Events.ValueAdded, () => this.hideAddValueForm())
this.valueOperationEventSubscriptions = [];
// subscribe to the ValueOperationEventService and listen for an event to be emitted
this.valueOperationEventSubscriptions.push(this._valueOperationEventService.on(
Events.ValueAdded, (newValue: AddedEventValue) => {
if (newValue) {
this.lastModificationDate = newValue.addedValue.valueCreationDate;
this.addValueToResource(newValue.addedValue);
this.hideAddValueForm();
}
}));
this.valueOperationEventSubscriptions.push(this._valueOperationEventService.on(
Events.ValueUpdated, (updatedValue: UpdatedEventValues) => {
this.lastModificationDate = updatedValue.updatedValue.valueCreationDate;
this.updateValueInResource(updatedValue.currentValue, updatedValue.updatedValue);
this.hideAddValueForm();
}));
this.valueOperationEventSubscriptions.push(this._valueOperationEventService.on(
Events.ValueDeleted, (deletedValue: DeletedEventValue) => {
// the DeletedEventValue does not contain a creation or last modification date
// so, we have to grab it from res info
this._getLastModificationDate(this.resource.res.id);
this.deleteValueFromResource(deletedValue.deletedValue);
}));
// keep the information if the user wants to display all properties or not
if (localStorage.getItem('showAllProps')) {
this.showAllProps = JSON.parse(localStorage.getItem('showAllProps'));
} else {
localStorage.setItem('showAllProps', JSON.stringify(this.showAllProps));
}
}
ngOnChanges(): void {
// get project information
this._dspApiConnection.admin.projectsEndpoint.getProjectByIri(this.resource.res.attachedToProject).subscribe(
(response: ApiResponseData<ProjectResponse>) => {
this.project = response.body.project;
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
// get user information
this._userService.getUser(this.resource.res.attachedToUser).subscribe(
(response: UserResponse) => {
this.user = response.user;
}
);
}
ngOnDestroy() {
// unsubscribe from the event bus when component is destroyed
// if (this.valueOperationEventSubscription !== undefined) {
// this.valueOperationEventSubscription.unsubscribe();
// }
// unsubscribe from the ValueOperationEventService when component is destroyed
if (this.valueOperationEventSubscriptions !== undefined) {
this.valueOperationEventSubscriptions.forEach(sub => sub.unsubscribe());
}
}
/**
* opens project
* @param linkValue
*/
openProject(project: ReadProject) {
window.open('/project/' + project.shortcode, '_blank');
}
previewProject(project: ReadProject) {
// --> TODO: pop up project preview on hover
}
/**
* goes to the next page of the incoming link pagination
* @param page
*/
goToPage(page: PageEvent) {
this.pageEvent = page;
this._getIncomingLinks();
}
/**
* opens resource
* @param linkValue
*/
openResource(linkValue: ReadLinkValue | string) {
const id = ((typeof linkValue == 'string') ? linkValue : linkValue.linkedResourceIri);
window.open('/resource/' + encodeURIComponent(id), '_blank');
}
previewResource(linkValue: ReadLinkValue) {
// --> TODO: pop up resource preview on hover
}
openDialog(type: 'delete' | 'erase' | 'edit') {
const dialogConfig: MatDialogConfig = {
width: '560px',
maxHeight: '80vh',
position: {
top: '112px'
},
data: { mode: type + 'Resource', title: this.resource.res.label }
};
const dialogRef = this._dialog.open(
DialogComponent,
dialogConfig
);
dialogRef.afterClosed().subscribe((answer: ConfirmationWithComment) => {
if (answer.confirmed === true) {
if (type !== 'edit') {
const payload = new DeleteResource();
payload.id = this.resource.res.id;
payload.type = this.resource.res.type;
payload.deleteComment = answer.comment ? answer.comment : undefined;
payload.lastModificationDate = this.lastModificationDate;
switch (type) {
case 'delete':
// delete the resource and refresh the view
this._dspApiConnection.v2.res.deleteResource(payload).subscribe(
(response: DeleteResourceResponse) => {
// display notification and mark resource as 'deleted'
this._notification.openSnackBar(`${response.result}: ${this.resource.res.label}`);
this.deletedResource = true;
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
break;
case 'erase':
// erase the resource and refresh the view
this._dspApiConnection.v2.res.eraseResource(payload).subscribe(
(response: DeleteResourceResponse) => {
// display notification and mark resource as 'erased'
this._notification.openSnackBar(`${response.result}: ${this.resource.res.label}`);
this.deletedResource = true;
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
break;
}
} else {
// update resource's label if it has changed
if (this.resource.res.label !== answer.comment) {
const payload = new UpdateResourceMetadata();
payload.id = this.resource.res.id;
payload.type = this.resource.res.type;
payload.lastModificationDate = this.lastModificationDate;
payload.label = answer.comment;
this._dspApiConnection.v2.res.updateResourceMetadata(payload).subscribe(
(response: UpdateResourceMetadataResponse) => {
this.resource.res.label = payload.label;
},
(error: ApiResponseError) => {
this._errorHandler.showMessage(error);
}
);
}
}
}
});
}
/**
* display message to confirm the copy of the citation link (ARK URL)
*/
openSnackBar() {
const message = 'ARK URL copied to clipboard!';
this._notification.openSnackBar(message);
}
/**
* called from the template when the user clicks on the add button
*/
showAddValueForm(prop: PropertyInfoValues) {
this.propID = prop.propDef.id;
this.addValueFormIsVisible = true;
}
/**
* called from the template when the user clicks on the cancel button
*/
hideAddValueForm() {
this.addValueFormIsVisible = false;
this.addButtonIsVisible = true;
this.propID = undefined;
}
/**
* given a resource property, check if an add button should be displayed under the property values
*
* @param prop the resource property
*/
addValueIsAllowed(prop: PropertyInfoValues): boolean {
// if the ontology flags this as a read-only property,
// don't ever allow to add a value
if (prop.propDef instanceof ResourcePropertyDefinition && !prop.propDef.isEditable) {
return false;
}
const isAllowed = CardinalityUtil.createValueForPropertyAllowed(
prop.propDef.id, prop.values.length, this.resource.res.entityInfo.classes[this.resource.res.type]);
// check if:
// cardinality allows for a value to be added
// value component does not already have an add value form open
// user has write permissions
return isAllowed && this.propID !== prop.propDef.id && this.addButtonIsVisible;
}
/**
* updates the UI in the event of a new value being added to show the new value
*
* @param valueToAdd the value to add to the end of the values array of the filtered property
*/
addValueToResource(valueToAdd: ReadValue): void {
if (this.resource.resProps) {
this.resource.resProps
.filter(propInfoValueArray =>
propInfoValueArray.propDef.id === valueToAdd.property) // filter to the correct property
.forEach(propInfoValue => {
propInfoValue.values.push(valueToAdd); // push new value to array
});
if (valueToAdd instanceof ReadTextValueAsXml) {
this._updateStandoffLinkValue();
}
} else {
// --> TODO: better error handler!
console.error('No properties exist for this resource');
}
}
/**
* updates the UI in the event of an existing value being updated to show the updated value
*
* @param valueToReplace the value to be replaced within the values array of the filtered property
* @param updatedValue the value to replace valueToReplace with
*/
updateValueInResource(valueToReplace: ReadValue, updatedValue: ReadValue): void {
if (this.resource.resProps && updatedValue !== null) {
this.resource.resProps
.filter(propInfoValueArray =>
propInfoValueArray.propDef.id === valueToReplace.property) // filter to the correct property
.forEach(filteredpropInfoValueArray => {
filteredpropInfoValueArray.values.forEach((val, index) => { // loop through each value of the current property
if (val.id === valueToReplace.id) { // find the value that should be updated using the id of valueToReplace
filteredpropInfoValueArray.values[index] = updatedValue; // replace value with the updated value
}
});
});
if (updatedValue instanceof ReadTextValueAsXml) {
this._updateStandoffLinkValue();
}
} else {
console.error('No properties exist for this resource');
}
}
/**
* given a resource property, check if its cardinality allows a value to be deleted
*
* @param prop the resource property
*/
deleteValueIsAllowed(prop: PropertyInfoValues): boolean {
const isAllowed = CardinalityUtil.deleteValueForPropertyAllowed(
prop.propDef.id, prop.values.length, this.resource.res.entityInfo.classes[this.resource.res.type]);
return isAllowed;
}
/**
* updates the UI in the event of an existing value being deleted
*
* @param valueToDelete the value to remove from the values array of the filtered property
*/
deleteValueFromResource(valueToDelete: DeleteValue): void {
if (this.resource.resProps) {
this.resource.resProps
.filter(propInfoValueArray => // filter to the correct type
this._valueService.compareObjectTypeWithValueType(propInfoValueArray.propDef.objectType, valueToDelete.type))
.forEach(filteredpropInfoValueArray => {
filteredpropInfoValueArray.values.forEach((val, index) => { // loop through each value of the current property
if (val.id === valueToDelete.id) { // find the value that was deleted using the id
filteredpropInfoValueArray.values.splice(index, 1); // remove the value from the values array
if (val instanceof ReadTextValueAsXml) {
this._updateStandoffLinkValue();
}
}
});
}
);
} else {
console.error('No properties exist for this resource');
}
}
toggleAllProps(status: boolean) {
this.showAllProps = !status;
localStorage.setItem('showAllProps', JSON.stringify(this.showAllProps));
}
/**
* gets the number of incoming links and gets the incoming links.
* @private
*/
private _getIncomingLinks() {
this.loading = true;
if (this.pageEvent.pageIndex === 0) {
this._incomingService.getIncomingLinks(this.resource.res.id, this.pageEvent.pageIndex, true).subscribe(
(response: CountQueryResponse) => {
this.numberOffAllIncomingLinkRes = response.numberOfResults;
}
);
}
this._incomingService.getIncomingLinks(this.resource.res.id, this.pageEvent.pageIndex).subscribe(
(response: ReadResourceSequence) => {
if (response.resources.length > 0) {
this.incomingLinkResources = response.resources;
}
this.loading = false;
}, (error: ApiResponseError) => {
this.loading = false;
}
);
}
/**
* updates the standoff link value for the resource being displayed.
*
*/
private _updateStandoffLinkValue(): void {
if (this.resource.res === undefined) {
// this should never happen:
// if the user was able to click on a standoff link,
// then the resource must have been initialised before.
return;
}
const gravsearchQuery = `
PREFIX knora-api: <http://api.knora.org/ontology/knora-api/simple/v2#>
CONSTRUCT {
?res knora-api:isMainResource true .
?res knora-api:hasStandoffLinkTo ?target .
} WHERE {
BIND(<${this.resource.res.id}> as ?res) .
OPTIONAL {
?res knora-api:hasStandoffLinkTo ?target .
}
}
OFFSET 0
`;
this._dspApiConnection.v2.search.doExtendedSearch(gravsearchQuery).subscribe(
(res: ReadResourceSequence) => {
// one resource is expected
if (res.resources.length !== 1) {
return;
}
const newStandoffLinkVals = res.resources[0].getValuesAs(Constants.HasStandoffLinkToValue, ReadLinkValue);
this.resource.resProps.filter(
resPropInfoVal => (resPropInfoVal.propDef.id === Constants.HasStandoffLinkToValue)
).forEach(
standoffLinkResPropInfoVal => {
// delete all the existing standoff link values
standoffLinkResPropInfoVal.values = [];
// push standoff link values retrieved for the resource
newStandoffLinkVals.forEach(
standoffLinkVal => {
standoffLinkResPropInfoVal.values.push(standoffLinkVal);
}
);
});
},
err => {
console.error(err);
}
);
}
private _getLastModificationDate(resId: string) {
this._dspApiConnection.v2.res.getResource(resId).subscribe(
(res: ReadResource) => this.lastModificationDate = res.lastModificationDate
);
}
}