-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
475 lines (425 loc) · 11.5 KB
/
app.js
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
//Global variables ***********************************************************************
const BASE_URL = 'https://api.harvardartmuseums.org';
const KEY = "apikey=298b7ee1-7817-4e54-9fdb-3b4fb87df97d"; // USE YOUR KEY HERE
//Bootstrap
prefetchCategoryLists();
//Functions ******************************************************************************
/**
* Fetches and returns (the promise) any given url
* @param {String} url
*/
async function fetchUrl(url) {
onFetchStart();
try {
const data = await fetch(url);
const response = await data.json();
return response;
} catch (error) {
console.error(error.message);
} finally {
onFetchEnd();
}
}
/**
* Initial fetch of objects
*/
async function fetchObjects() {
const url = `${BASE_URL}/object?${KEY}`;
return await fetchUrl(url);
}
/**
* Pre fetch of list of centuries to populate drop down menu
*/
async function fetchAllCenturies() {
const url = `${BASE_URL}/century?${KEY}&size=100&sort=temporalorder`;
if (localStorage.getItem('centuries')) {
return JSON.parse(localStorage.getItem('centuries'));
} else {
const { records } = await fetchUrl(url);
localStorage.setItem('centuries', JSON.stringify(records));
return records;
}
}
/**
* Pre fetch of list of classifications to populate drop down menu
*/
async function fetchAllClassifications() {
const url = `${BASE_URL}/classification?${KEY}&size=100&sort=name`;
if (localStorage.getItem('classifications')) {
return JSON.parse(localStorage.getItem('classifications'));
} else {
const { records } = await fetchUrl(url);
localStorage.setItem('classifications', JSON.stringify(records));
return records;
}
}
/**
* Handles the resolved fetch of centuries and classifications and appends them to the drop down menues
*/
async function prefetchCategoryLists() {
try {
const [classifications, centuries] = await Promise.all([
fetchAllClassifications(),
fetchAllCenturies(),
]);
// This provides a clue to the user, that there are items in the dropdown
$('.classification-count').text(`(${classifications.length})`);
classifications.forEach((classification) => {
// append a correctly formatted option tag into
// the element with id select-classification
$('#select-classification')
.append(`<option value="${classification.name}">${classification.name}</option>
`);
});
// This provides a clue to the user, that there are items in the dropdown
$('.century-count').text(`(${centuries.length})`);
centuries.forEach((century) => {
// append a correctly formatted option tag into
// the element with id select-century
$('#select-century')
.append(`<option value="${century.name}">${century.name}</option>
`);
});
} catch (error) {
console.error(error.message);
}
}
/**
* Builds a url string using the base url, and any keyword search, classification, and century selected.
* It also builds a query string that reflects what the query was.
*/
function buildSearchString() {
const keyWord = $('#keywords').val();
const classification = $('#select-classification').val();
const century = $('#select-century').val();
const url = encodeURI(
`${BASE_URL}/object?${KEY}&classification=${classification}¢ury=${century}&keyword=${keyWord}`,
);
let query = '';
keyWord ? (query = query + keyWord) : '';
query && classification != 'any'
? (query = query + ' & ' + classification)
: classification != 'any'
? (query = query + classification)
: '';
query && century != 'any'
? (query = query + ' & ' + century)
: century != 'any'
? (query = query + century)
: '';
return [url, query];
}
/**
* Adds a touch of style to the page. When a fetch is initiated it reveals a "downloading" message.
*/
function onFetchStart() {
$('#loading').addClass('active');
}
/**
* It disables the "downloading" message when the fetch is resolved.
*/
function onFetchEnd() {
$('#loading').removeClass('active');
}
/**
* Returns an html element to render one record. For the aside section.
* @param {Object} record
*/
function renderPreview(record) {
const { description, primaryimageurl, title, objectnumber } = record;
const objectNumber = `(${objectnumber})`;
const htmlTemplate = $(`
<div class="object-preview">
<a href="#">
<img src="${primaryimageurl ? primaryimageurl : ''}" />
<h3>${
title === null
? objectNumber
: title === 'Untitled'
? title + ' ' + objectNumber
: title
}</h3>
<h3>${description === null ? '' : description}</h3>
</a>
</div>
`);
htmlTemplate.data('record', record);
return htmlTemplate;
}
/**
* updates the left side preview of all the records
* @param {Array} records
*/
function updatePreview(data) {
const root = $('#preview');
$('.results').empty();
const { info, records } = data;
/*
if info.next is present:
- on the .next button set data with key url equal to info.next
- also update the disabled attribute to false
else
- set the data url to null
- update the disabled attribute to true
Do the same for info.prev, with the .previous button
*/
if (info.next) {
$('.next').data('url', info.next).removeAttr('disabled');
} else {
$('.next').data('url', null).attr('disabled', 'true');
}
if (info.prev) {
$('.previous').data('url', info.prev).removeAttr('disabled');
} else {
$('.previous').data('url', null).attr('disabled', 'true');
}
records.forEach(function (item) {
$('.results').append(renderPreview(item));
});
}
/**
* Returns an html element of the whole record for preview purposes (right side)
* @param {Object} record
*/
function renderFeature(record) {
/**
* We need to read, from record, the following:
* HEADER: title, dated
* FACTS: description, *culture, style, *technique, *medium, dimensions, *people(array), department, division, contact, creditline
* PHOTOS: images(array), primaryimageurl
*/
const {
title,
dated,
description,
culture,
style,
technique,
medium,
dimensions,
people,
department,
division,
contact,
creditline,
images,
primaryimageurl,
} = record;
const header = [
['Title', title],
['Dated', dated],
];
const facts = [
['Description', description],
['Culture', culture],
['Style', style],
['Technique', technique],
['Medium', medium],
['Dimensions', dimensions],
['Person', people],
['Department', department],
['Division', division],
['Contact', contact],
['Credit', creditline],
];
const photos = images;
// build and return template
const htmlElement = $(`
<div class="object-feature">
<header>
<h3>${header[0]}</h3>
<h4>${header[1]}</h4>
</header>
<section class="facts">
<!--
<span class="title">Fact Name</span>
<span class="content">Fact Content</span>
And so on..
-->
</section>
<section class="photos">
<!--
<img src="image url" />
And so on..
-->
</section>
</div>
`);
renderFacts(facts);
renderImages(photos);
return htmlElement;
/**
* Will render one fact at a time
* @param {Array} facts
*/
function renderFacts(facts) {
facts.forEach(function ([name, value]) {
if (name === 'Person') {
personFact(name, value);
} else if (name === 'Contact') {
contactFact(name, value);
} else if (
name === 'Culture' ||
name === 'Technique' ||
name === 'Medium'
) {
searchableFact(name, value);
} else {
simpleFact(name, value);
}
});
}
/**
* Will append a simple fact
* @param {String} name
* @param {String} value
*/
function simpleFact(name, value) {
if (value) {
htmlElement.find('.facts').append(
$(`
<div class='fact'>
<span class="title">${name}</span>
<span class="content">${value}</span>
</div>
`),
);
}
}
/**
* Will append one or more people
* @param {String} name
* @param {Array} value
*/
function personFact(name, value) {
if (value) {
value.map(function (person) {
const personHtml = $(
`
<div class='fact'>
<span class="title">${name}</span>
<span class="content"><a href='${searchURL(
name,
person.displayname,
)}'>${person.displayname}</a></span>
</div>
`,
);
personHtml.data('query', [name, person.displayname]);
htmlElement.find('.facts').append(personHtml);
});
}
}
/**
* Will append an email
* @param {String} name
* @param {String} value
*/
function contactFact(name, value) {
if (value) {
htmlElement.find('.facts').append(
$(
`
<div class='fact'>
<span class="title">${name}</span>
<span class="content"><a target="_blank" href='mailto:${value}'>${value}</a></span>
</div>
`,
),
);
}
}
/**
* Will append a searchable fact
* @param {String} name
* @param {String} value
*/
function searchableFact(name, value) {
if (value) {
const searchHtml = $(`
<div class='fact'>
<span class="title">${name}</span>
<span class="content"><a href='${searchURL(
name,
value,
)}'>${value}</a></span>
</div>
`);
searchHtml.data('query', [name, value]);
htmlElement.find('.facts').append(searchHtml);
}
}
/**
* Appends one or more images if there's any image present
* @param {Array} images
*/
function renderImages(images) {
if (images) {
for (let i = 0; i < images.length; i++) {
htmlElement.find('.photos').append(
$(
`
<img src="${images[i].baseimageurl}" />
`,
),
);
}
}
}
}
/**
*Returns a search url
* @param {String} searchType
* @param {String} searchString
*/
function searchURL(searchType, searchString) {
return encodeURI(
`${BASE_URL}/object?${KEY}&${searchType.toLowerCase()}=${searchString}`,
);
}
//Listeners *************************************************************************
//Listen to the form submission
$('#search').on('submit', async function (event) {
// prevent the default
event.preventDefault();
const [url, query] = buildSearchString();
const result = await fetchUrl(url);
updatePreview(result);
$('.query').text(query);
$('#keywords').val('');
});
//Listen to the next, previous page buttons
$('#preview .next, #preview .previous').on('click', async function () {
/*
read off url from the target
fetch the url
read the records and info from the response.json()
update the preview
*/
const url = $(this).data('url');
const result = await fetchUrl(url);
updatePreview(result);
});
//Handles the click of a record card which will trigger a more thorough preview.
$('#preview').on('click', '.object-preview', function (event) {
event.preventDefault(); // they're anchor tags, so don't follow the link
// find the '.object-preview' element by using .closest() from the target
// recover the record from the element using the .data('record') we attached
// log out the record object to see the shape of the data
const element = $(this).closest('.object-preview');
const data = element.data('record');
$('#feature').empty();
$('#feature').append(renderFeature(data));
});
//Handles the click of a searchable term within the featured (detailed) view and generates a new search.
$('#feature').on('click', '.content a', async function (event) {
if ($(this).attr('href').startsWith('mailto')) {
return;
}
event.preventDefault();
const url = $(this).attr('href');
const result = await fetchUrl(url);
const [name, value] = $(this).closest('.fact').data('query');
$('.query').text(name + ' & ' + value);
updatePreview(result);
});