This repository was archived by the owner on Oct 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisplay.js
More file actions
464 lines (423 loc) · 17.5 KB
/
display.js
File metadata and controls
464 lines (423 loc) · 17.5 KB
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
import { cloneDeep, each, isObject, uniq, includes, remove, isArray, isEmpty, uniqWith, isEqual } from 'lodash-es';
import * as VocabUtil from './vocab';
import * as StringUtil from './string';
import { lxlLog, lxlWarning } from './debug';
export function expandInherited(display) {
const cloned = cloneDeep(display);
const lensesById = {};
each(cloned.lensGroups, (lensGroup) => {
each(lensGroup.lenses, (lens) => {
if (lens.hasOwnProperty('@id')) {
lensesById[lens['@id']] = lens;
}
});
});
const flattenedProps = (lens, hierarchy) => {
if (lens['@id'] && hierarchy.indexOf(lens['@id']) !== -1) {
throw new Error(`fresnel:extends inheritance loop: ${hierarchy}`);
}
if (lens.showProperties.indexOf('fresnel:super') === -1) {
return lens.showProperties;
}
if (!lens['fresnel:extends'] || !lens['fresnel:extends']['@id']) {
lxlWarning(`👁️ Use of 'fresnel:super' without 'fresnel:extends': ${JSON.stringify(lens)}.`);
return lens.showProperties;
}
const extendId = lens['fresnel:extends']['@id'];
if (!lensesById[extendId]) {
lxlWarning(`👁️ Could not find lens with id '${extendId}' used in 'fresnel:extends': ${JSON.stringify(lens)}.`);
return lens.showProperties;
}
if (lens['@id']) {
hierarchy.push(lens['@id']);
}
lens.showProperties.splice(
lens.showProperties.indexOf('fresnel:super'),
1,
...flattenedProps(lensesById[extendId], hierarchy),
);
return lens.showProperties;
};
each(cloned.lensGroups, (lensGroup) => {
each(lensGroup.lenses, (lens) => {
lens.showProperties = uniqWith(flattenedProps(lens, []), isEqual);
});
});
return cloned;
}
function getValueByLang(item, propertyId, langCode, context) {
const translatedValue = tryGetValueByLang(item, propertyId, langCode, context);
return translatedValue != null ? translatedValue : item[propertyId];
}
function tryGetValueByLang(item, propertyId, langCode, context) {
if (!langCode || typeof langCode === 'undefined') {
throw new Error('tryGetValueByLang was called with an undefined language code.');
}
const byLangKey = VocabUtil.getMappedPropertyByContainer(propertyId, '@language', context);
return byLangKey && item[byLangKey] && item[byLangKey][langCode]
? item[byLangKey][langCode]
: null;
}
export function getLensById(id, displayDefs) {
if (!displayDefs) {
throw new Error('getLensById was called without display resource');
}
if (!id) {
throw new Error('getLensById was called without lens id');
}
for (const collection in displayDefs.lensGroups) {
if (Object.prototype.hasOwnProperty.call(displayDefs.lensGroups, collection)) {
for (const lens in displayDefs.lensGroups[collection].lenses) {
if (Object.prototype.hasOwnProperty.call(displayDefs.lensGroups[collection].lenses, lens)) {
const obj = displayDefs.lensGroups[collection].lenses[lens];
if (obj.hasOwnProperty('@id') && obj['@id'] === id) {
return obj;
}
}
}
}
}
return {};
}
/* eslint-disable no-use-before-define */
export function getLensPropertiesDeep(className, resources, settings, level, depth) {
let props = [];
const lensGroups = resources.display.lensGroups;
if (lensGroups.hasOwnProperty(level) && lensGroups[level].lenses.hasOwnProperty(className)) {
props = lensGroups[level].lenses[className].showProperties;
} else {
const termObj = VocabUtil.getTermObject(className, resources.vocab, resources.context);
if (typeof termObj !== 'undefined' && termObj.hasOwnProperty('subClassOf')) {
const ownClasses = VocabUtil.filterOwnClasses(termObj.subClassOf, resources.context);
if (ownClasses.length > 0) {
props = getDisplayProperties(ownClasses[0]['@id'], resources, settings, level, depth + 1);
}
}
}
return props;
}
export function getDisplayProperties(className, resources, settings, inputLevel, depth = 0) {
if (!className || typeof className === 'undefined') {
throw new Error('getDisplayProperties was called with an undefined type.');
}
if (isObject(className) && !isArray(className)) {
throw new Error(
'getDisplayProperties was called with an object as type parameter (should be a string).',
);
}
const cn = StringUtil.getCompactUri(className, resources.context);
let level = inputLevel;
let props = [];
// If we want tokens, we traverse them first, since they can "fail"
if (level === 'tokens') {
props = getLensPropertiesDeep(cn, resources, settings, level, depth);
if (props.length === 0 && depth === 0) {
// If we wanted tokens and got nothing, change level to "chips"
// We only want to "sidestep" if depth is 0.
level = 'chips';
}
}
// If level is not tokens
if (level !== 'tokens') {
props = getLensPropertiesDeep(cn, resources, settings, level, depth);
}
props = uniq(props);
const propsWithTranslatedObjects = [];
for (let i = 0; i < props.length; i++) {
if (isObject(props[i])) {
const translated = translateObjectProp(props[i]);
if (translated !== null) {
propsWithTranslatedObjects[i] = translated;
}
} else {
propsWithTranslatedObjects[i] = props[i];
}
}
return propsWithTranslatedObjects;
}
export function translateObjectProp(object) {
if (object.hasOwnProperty('inverseOf')) {
return `@reverse/${object.inverseOf}`;
}
if (object.hasOwnProperty('alternateProperties')) {
return object;
}
return null;
}
function formatLabel(item, resources) {
const label = [];
const formatters = resources.display.lensGroups.formatters;
const objKeys = Object.keys(item);
for (let i = 0; i < objKeys.length; i++) {
const key = objKeys[i];
const value = item[key];
if (i > 0) {
label.push(' • ');
}
const formatter = formatters[`${key}-format`];
if (isArray(value)) {
if (formatter && formatter['fresnel:valueFormat'] && formatter['fresnel:valueFormat']['fresnel:contentAfter']) {
label.push(value.join(formatter['fresnel:valueFormat']['fresnel:contentAfter']));
if (formatter['fresnel:contentLast']) {
label.push(formatter['fresnel:contentLast']);
}
} else {
label.push(value.join(', '));
}
} else {
label.push(value);
}
}
return label.join(''); // Join without any extra separators
}
/* eslint-disable no-use-before-define */
export function getItemLabel(item, resources, quoted, settings, inClass = '') {
if (typeof item === 'string') {
// Assume this is already a label.
return item;
}
if (!item || typeof item === 'undefined') {
throw new Error('getItemLabel was called with an undefined object.');
}
if (!isObject(item)) {
throw new Error(`getItemLabel was called with a non-object. Type: ${typeof item}. Value: ${item}`);
}
const displayObject = getChip(item, resources, quoted, settings);
if (Object.keys(displayObject).length === 0) {
return JSON.stringify(item);
}
let rendered = formatLabel(displayObject, resources);
// let rendered = StringUtil.formatLabel(displayObject).trim();
if (item['@type'] && VocabUtil.isSubClassOf(item['@type'], 'Identifier', resources.vocab, resources.context)) {
if (item['@type'] === 'ISNI' || item['@type'] === 'ORCID') {
rendered = formatIsni(rendered);
}
if (inClass.toLowerCase() !== item['@type'].toLowerCase()) {
const translatedType = StringUtil.getLabelByLang(item['@type'], settings.language, resources);
rendered = `${translatedType} ${rendered}`;
}
}
return rendered;
}
export function formatIsni(isni) {
return typeof isni === 'string' && isni.length === 16
? `${isni.slice(0, 4)} ${isni.slice(4, 8)} ${isni.slice(8, 12)} ${isni.slice(12, 16)}`
: isni;
}
export function getSortedProperties(formType, formObj, settings, resources) {
const propertyList = getDisplayProperties(
formType,
resources,
settings,
'full',
);
each(formObj, (v, k) => {
if (!includes(propertyList, k)) {
propertyList.push(k);
}
});
remove(propertyList, k => (settings.hiddenProperties.indexOf(k) !== -1));
return propertyList;
}
export function getItemToken(item, resources, quoted, settings) {
const displayObject = getToken(item, resources, quoted, settings);
let rendered = StringUtil.formatLabel(displayObject).trim();
if (item['@type'] && VocabUtil.isSubClassOf(item['@type'], 'Identifier', resources.vocab, resources.context)) {
const translatedType = StringUtil.getLabelByLang(item['@type'], settings.language, resources);
rendered = `${translatedType} ${rendered}`;
}
return rendered;
}
export function getDisplayObject(item, level, resources, quoted, settings) {
// Some checks before we even start
if (!item || typeof item === 'undefined') {
throw new Error('getDisplayObject was called with an undefined object.');
}
if (!isObject(item)) {
throw new Error(`getDisplayObject was called with a non-object. (Was ${typeof item})`);
}
// Setup
let result = {};
let trueItem = Object.assign({}, item);
// Is this a link?
if (trueItem.hasOwnProperty('@id') && !trueItem.hasOwnProperty('@type')) {
if (trueItem['@id'] === 'https://id.kb.se/vocab/') {
return {};
}
// If we have the entity in quoted, replace our link-object with the entity
if (quoted && quoted.hasOwnProperty(trueItem['@id'])) {
trueItem = quoted[trueItem['@id']];
}
// Plan to try and fetch missing data?
// trueItem = DataUtil.getEmbellished(trueItem['@id'], quoted);
// If the item lacks a type, just return it as an anonymous object with a label
if (!trueItem.hasOwnProperty('@type') && trueItem.hasOwnProperty('@id')) {
return { label: StringUtil.removeDomain(trueItem['@id'], settings.removableBaseUris) };
}
}
if (!trueItem.hasOwnProperty('@type') || typeof trueItem['@type'] === 'undefined') {
return {}; // Early fail
}
// Get the list of properties we want to show
const displayType = isArray(trueItem['@type']) ? trueItem['@type'][0] : trueItem['@type']; // If more than one type, choose the first
const properties = getDisplayProperties(displayType, resources, settings, level);
// Start filling the object with the selected properties
if (properties.length === 2 && properties.indexOf('label') > -1 && properties.indexOf('prefLabel') > -1) {
// This first block can probably be replace by alternateProperties at some point
const labelValue = getValueByLang(trueItem, 'label', settings.language, resources.context);
const prefLabelValue = getValueByLang(trueItem, 'prefLabel', settings.language, resources.context);
if (typeof prefLabelValue !== 'undefined') {
result.prefLabel = prefLabelValue;
} else if (labelValue !== 'undefined') {
result.label = labelValue;
}
} else {
properties.forEach((property) => {
if (!isObject(property)) {
let valueOnItem = '';
valueOnItem = getValueByLang(trueItem, property, settings.language, resources.context);
if (typeof valueOnItem !== 'undefined') {
let value = valueOnItem;
if (isObject(value) && !isArray(value)) {
if (level === 'chips') {
value = getItemToken(value, resources, quoted, settings);
} else {
value = getItemLabel(value, resources, quoted, settings, property);
}
} else if (isArray(value)) {
const newArray = [];
for (const arrayItem of value) {
if (typeof arrayItem === 'undefined' || arrayItem === null) {
throw new Error('getDisplayObject encountered an undefined or null item in an array.');
}
if (isObject(arrayItem) && (Object.keys(arrayItem).length > 1 || arrayItem[Object.keys(arrayItem)[0]] !== '')) {
if (level === 'chips') {
newArray.push(getItemToken(arrayItem, resources, quoted, settings));
} else {
newArray.push(getItemLabel(arrayItem, resources, quoted, settings, property));
}
} else if (arrayItem.length > 0) {
newArray.push(arrayItem);
} else {
// console.warn("Array contained unknown item", arrayItem);
}
}
value = newArray;
}
result[property] = value;
} else if (properties.length < 3 && properties.indexOf(property) === 0) {
const rangeOfMissingProp = VocabUtil.getRange(property, resources.vocab, resources.context);
let propMissing = property;
if (
rangeOfMissingProp.length > 1
|| (rangeOfMissingProp.length === 1 && rangeOfMissingProp[0] !== 'http://www.w3.org/2000/01/rdf-schema#Literal')
) {
propMissing = rangeOfMissingProp[0];
}
const expectedClassName = StringUtil.getLabelByLang(
propMissing, // Get the first one just to show something
settings.language,
resources,
);
result[property] = `{${StringUtil.getLabelByLang(trueItem['@type'], settings.language, resources)} ${StringUtil.getUiPhraseByLang('without', settings.language)} ${expectedClassName.toLowerCase()}}`;
}
} else {
// Property is object, lets calculate that
if (property.hasOwnProperty('alternateProperties')) {
// Handle alternateProperties
for (const p of property.alternateProperties) {
if (typeof p === 'string' && trueItem.hasOwnProperty(p)) {
if (typeof trueItem[p] === 'string') {
result[p] = trueItem[p];
} else if (level === 'chips') {
if (isArray(trueItem[p])) {
result[p] = trueItem[p].map(arrayItem => getItemToken(arrayItem, resources, quoted, settings));
} else {
result[p] = getItemToken(trueItem[p], resources, quoted, settings);
}
} else {
if (isArray(trueItem[p])) {
result[p] = trueItem[p].map(arrayItem => getItemLabel(arrayItem[p], resources, quoted, settings, property));
} else {
result[p] = getItemLabel(trueItem[p], resources, quoted, settings, property);
}
}
lxlLog('Calculating alternate properties for', trueItem['@type'], 'choosing between', property.alternateProperties, 'and found', p);
break;
}
}
}
}
});
}
const itemKeys = Object.keys(result);
if (isEmpty(result) || (itemKeys.length === 1 && (typeof result[itemKeys[0]] === 'undefined' || result[itemKeys[0]] === null || result[itemKeys[0]].length === 0))) {
lxlWarning(`🏷️ DisplayObject was empty. @type was ${trueItem['@type']}.`, 'Item data:', trueItem);
if (trueItem.hasOwnProperty('@id')) {
const idParts = item['@id'].split('/');
result = { label: idParts[idParts.length - 1] };
} else {
result = { label: `{${StringUtil.getUiPhraseByLang('Unnamed', settings.language, resources.i18n)}}` };
}
}
return result;
}
export function getChip(item, resources, quoted, settings) {
return getDisplayObject(item, 'chips', resources, quoted, settings);
}
export function getToken(item, resources, quoted, settings) {
const tokenObj = getDisplayObject(item, 'tokens', resources, quoted, settings);
const token = { rendered: '' };
Object.keys(tokenObj).forEach((key) => {
token.rendered += ` ${tokenObj[key]}`;
});
return token;
}
export function getCard(item, resources, quoted, settings) {
return getDisplayObject(item, 'cards', resources, quoted, settings);
}
/* eslint-enable no-use-before-define */
export function getItemSummary(item, resources, quoted, settings, excludeProperties = []) {
const card = getCard(item, resources, quoted, settings);
if (excludeProperties.length > 0) {
for (let i = 0; i < excludeProperties.length; i++) {
delete card[excludeProperties[i]];
}
}
const cardDisplayGroups = require('@/resources/json/displayGroups.json').card;
const summary = {
categorization: [],
header: [],
info: [],
};
each(card, (value, key) => {
if (value !== null) {
const v = isArray(value) ? value : [value];
if (cardDisplayGroups.header.includes(key)) {
summary.header.push({ property: key, value: v });
} else if (cardDisplayGroups.categorization.includes(key)) {
summary.categorization.push({ property: key, value: v });
} else if (cardDisplayGroups.hidden.includes(key)) {
// drop it
} else {
const translated = tryGetValueByLang(item, key, settings.language, resources.context);
const itemValue = translated !== null ? translated : item[key];
summary.info.push({ property: key, value: isArray(itemValue) ? itemValue : [itemValue] });
}
}
});
if (summary.header.length === 0) {
summary.header.push({ property: 'error', value: `{${StringUtil.getUiPhraseByLang('Unnamed', settings.language, resources.i18n)}}` });
}
return summary;
}
export function getLabelWithTreeDepth(term, settings, resources) {
const maxLength = 43;
let labelByLang = StringUtil.getLabelByLang(term.id, settings.language, resources);
if (labelByLang.length > maxLength) {
labelByLang = `${labelByLang.substr(0, maxLength - 2)}...`;
}
const abstractIndicator = ` {${StringUtil.getUiPhraseByLang('Abstract', settings.language, resources.i18n)}}`;
const indent = Array(term.depth + 1).join('- ');
return `${indent}${labelByLang} ${term.abstract ? abstractIndicator : ''}`;
}