blob: 574454813d28a76c1489d77ba1e172a34dc085a0 [file] [log] [blame]
j7940eec2020-12-28 14:00:41 -06001/**
2 * @file DTPS global search
3 * @author jottocraft
4 *
j6e1a7bf2026-10-13 03:37:04 +00005 * @copyright Copyright (c) jottocraft 2020
j40db0272022-01-14 15:18:29 -08006 * @license MIT
j7940eec2020-12-28 14:00:41 -06007 */
8
9
10/**
11 * Searches Power+ globally and shows results on the "Search Results" screen
12 *
13 * @param term {string} The search term typed in the input box
14 */
jd4fc5d82020-12-28 19:38:41 -060015dtps.globalSearch = function (param) {
16 var term = param.term;
17 var type = param.type;
18 var courseNum = param.course;
19
20 $("#dtpsMainSearchBox").attr("data-search-type", param.type).attr("data-dtps-course", param.course).attr("data-ctx-type", param.ctxType).attr("data-ctx-course", param.ctxCourse);
j7940eec2020-12-28 14:00:41 -060021
22 //Ensure classes are rendered in the sidebar
23 dtps.presentClass("search");
24 dtps.showClasses();
25 dtps.selectedContent = "stream";
26
27 //Clear active state from all tabs
28 $("#dtpsTabBar .btn").removeClass("active");
29
30 jQuery(".classContent").html([1, 2, 3, 4].map(() => (
31 /*html*/`
32 <div class="card assignment graded">
33 <h4>
34 <span style="width: 450px;" class="shimmer">Assignment Title</span>
35 <div class="points shimmer">00/00</div>
36 </h4>
37
38 <h5 style="white-space: nowrap; overflow: hidden;">
39 <div style="width: 200px;" class="infoChip shimmer"></div>
40 <i class="fluid-icon statusIcon shimmer">more_horiz</i>
41 </h5>
42 </div>
43 `
44 )).join(""));
45
46 //Fetch everything
47 var dataset = [];
48 var datasetPromises = [];
jd4fc5d82020-12-28 19:38:41 -060049 var checkedCourses = [];
j7940eec2020-12-28 14:00:41 -060050
51 (courseNum == "all" ? dtps.classes : [dtps.classes[Number(courseNum)]]).forEach(course => {
52 if ((type == "assignments") || (type == "coursework") || (type == "everything")) {
53 datasetPromises.push(new Promise((resolve, reject) => {
54 if (!course.assignments) return resolve([]);
55 resolve(course.assignments.map(assignment => ({
56 title: assignment.title,
57 class: course.num,
58 body: $('<div>' + assignment.body + '</div>').text(),
59 onclick: "dtps.assignment('" + assignment.id + "', " + assignment.class + ")",
60 locatedIn: assignment.category ? assignment.category : "Assignment",
61 icon: "assignment",
62 type: "assignment",
63 infoIcons: [
jd4fc5d82020-12-28 19:38:41 -060064 assignment.dueAt ? "alarm" : null,
65 dtps.user.parent ? "person" : null
j7940eec2020-12-28 14:00:41 -060066 ].filter(i => i),
67 info: [
jd4fc5d82020-12-28 19:38:41 -060068 assignment.dueAt ? "Due: " + dtps.formatDate(assignment.dueAt) : null,
69 dtps.user.parent ? dtps.user.children.find(c => c.id == course.userID).name : null
j7940eec2020-12-28 14:00:41 -060070 ].filter(i => i).join("$|$"),
71 icons: [
72 {
73 icon: assignment.missing ? "remove_circle_outline" : null,
74 state: "missing"
75 },
76 {
77 icon: assignment.turnedIn ? "assignment_turned_in" : null,
78 state: "turnedIn"
79 },
80 {
81 icon: assignment.locked ? "lock_outline" : null,
82 state: "locked"
83 },
84 {
85 icon: assignment.late ? "assignment_late" : null,
86 state: "late"
87 }
88 ].filter(i => i.icon)
89 })));
90 }));
91 }
92
jd4fc5d82020-12-28 19:38:41 -060093 if ((type == "grades") || (type == "everything")) {
94 datasetPromises.push(new Promise((resolve, reject) => {
95 if (!course.assignments) return resolve([]);
96 var res = [];
97
98 course.assignments.forEach(assignment => {
99 if (dtpsLMS.useRubricGrades && assignment.rubric) {
100 assignment.rubric.forEach(rubric => {
101 if (rubric.score) {
102 res.push({
103 title: assignment.title,
104 class: course.num,
105 onclick: "dtps.assignment('" + assignment.id + "', " + assignment.class + ")",
106 locatedIn: rubric.title,
107 icon: "assessment",
108 infoIcons: [
109 "bar_chart",
110 dtps.user.parent ? "person" : null
111 ].filter(i => i),
112 info: [
113 "Score: " + rubric.score + "/" + rubric.value + (rubric.scoreName ? " " + rubric.scoreName : ""),
114 dtps.user.parent ? dtps.user.children.find(c => c.id == course.userID).name : null
115 ].filter(i => i).join("$|$"),
116 icons: []
117 });
118 }
119 });
120 } else if (assignment.grade) {
121 res.push({
122 title: assignment.title,
123 class: course.num,
124 onclick: "dtps.assignment('" + assignment.id + "', " + assignment.class + ")",
125 locatedIn: "Grade",
126 icon: "assessment",
127 infoIcons: [
128 "bar_chart",
129 dtps.user.parent ? "person" : null
130 ].filter(i => i),
131 info: [
132 "Score: " + assignment.grade + "/" + assignment.value + " (" + Math.round((assignment.grade / assignment.value) * 100) + "%" + (assignment.letter ? ", " + assignment.letter : "") + ")",
133 dtps.user.parent ? dtps.user.children.find(c => c.id == course.userID).name : null
134 ].filter(i => i).join("$|$"),
135 icons: []
136 });
137 }
138 });
139
140 resolve(res);
141 }));
142 }
143
144 //Check if this course has already been checked
145 if (checkedCourses.includes(course.lmsID)) return;
146 checkedCourses.push(course.lmsID);
147
j7940eec2020-12-28 14:00:41 -0600148 if ((type == "modules") || (type == "coursework") || (type == "everything")) {
149 datasetPromises.push(new Promise((resolve, reject) => {
150 if (!course.modules) return resolve([]);
151 new Promise(resolve => {
152 if (course.modules && (course.modules !== true)) {
153 resolve(course.modules);
154 } else {
155 dtpsLMS.fetchModules(dtps.user.id, course.lmsID).then(data => resolve(data));
156 }
157 }).then(data => {
158 var res = [];
159 data.forEach(module => {
160 module.items.forEach(item => {
161 //Prevent assignments from showing twice in coursework search results
162 //(since assignments can appear in both assignments and modules tab)
163 if ((item.type == "assignment") && (type == "coursework")) return;
164
165 item.locatedIn = module.title;
166 res.push(item);
167 });
168 });
169
170 resolve(res.map(item => ({
171 title: item.title,
172 class: course.num,
173 url: item.url,
174 locatedIn: item.locatedIn,
175 icon: "view_module",
176 infoIcons: [
177 "category"
178 ].filter(i => i),
179 info: [
180 "Type: " + item.type
181 ].filter(i => i).join("$|$"),
182 icons: [
183 {
184 icon: item.completed ? "check" : null,
185 keywords: "completed done submitted"
186 }
187 ].filter(i => i.icon)
188 })));
189 }).catch(() => resolve([]));
190 }));
191 }
192
193 if ((type == "homepages") || (type == "everything")) {
194 datasetPromises.push(new Promise((resolve, reject) => {
195 if (!course.homepage) return resolve([]);
196 dtpsLMS.fetchHomepage(course.lmsID).then(data => {
197 resolve([{
198 title: course.subject + " Homepage",
199 class: course.num,
200 onclick: "dtps.classHome(" + course.num + ");",
201 locatedIn: course.subject,
202 icon: "home",
203 body: $('<div>' + data + '</div>').text(),
204 icons: []
205 }]);
206 }).catch(() => resolve([]));
207 }));
208 }
209
210 if ((type == "pages") || (type == "everything")) {
211 datasetPromises.push(new Promise((resolve, reject) => {
212 if (!course.pages) return resolve([]);
213 dtpsLMS.fetchPages(course.lmsID).then(pages => {
214 Promise.all(pages.map(page => (
215 dtpsLMS.fetchPageContent(course.lmsID, page.id)
216 ))).then(pages => {
217 resolve(pages.map(page => ({
218 title: page.title,
219 class: course.num,
220 onclick: "fluid.screen('pages', '" + course.id + "|" + page.id + "');",
221 body: $('<div>' + page.content + '</div>').text(),
222 locatedIn: "Page",
223 icon: "insert_drive_file",
224 infoIcons: [
225 page.author && page.author.name ? "person" : null
226 ].filter(i => i),
227 info: [
228 page.author && page.author.name ? "Author: " + page.author && page.author.name : null
229 ].filter(i => i).join("$|$"),
230 icons: []
231 })));
232 })
233 }).catch(() => resolve([]));
234 }));
235 }
236
237 if ((type == "discussions") || (type == "everything")) {
238 datasetPromises.push(new Promise((resolve, reject) => {
239 if (!course.discussions) return resolve([]);
240 dtpsLMS.fetchDiscussionThreads(course.lmsID).then(discussions => {
241 Promise.all(discussions.map(discussion => (
242 dtpsLMS.fetchDiscussionPosts(course.lmsID, discussion.id)
243 ))).then(discussions => {
244 var res = [];
245 discussions.forEach(discussion => {
246 discussion.posts.forEach(post => {
247 post.locatedIn = discussion.title;
248 post.threadID = discussion.id;
249 res.push(post);
250
251 if (post.replies) {
252 post.replies.forEach(reply => {
253 reply.locatedIn = discussion.title;
254 reply.threadID = discussion.id;
255 res.push(reply);
256 });
257 }
258 })
259 });
260 resolve(res.map(post => ({
261 body: $('<div>' + post.body + '</div>').text(),
262 class: course.num,
263 onclick: "fluid.screen('discussions', '" + course.id + "|" + post.threadID + "|false|" + post.id + "');",
264 locatedIn: post.locatedIn,
265 icon: "forum",
266 infoIcons: [
267 post.author && post.author.name ? "person" : null,
268 post.postedAt ? "calendar_today" : null
269 ].filter(i => i),
270 info: [
271 post.author && post.author.name ? "Author: " + post.author && post.author.name : null,
272 post.postedAt ? "Posted At: " + dtps.formatDate(post.postedAt) : null
273 ].filter(i => i).join("$|$"),
274 icons: []
275 })));
276 })
277 }).catch(() => resolve([]));
278 }));
279 }
280
281 if ((type == "people") || (type == "everything")) {
282 datasetPromises.push(new Promise((resolve, reject) => {
283 if (!course.people) return resolve([]);
284 new Promise(resolve => {
285 if (course.people && (course.people !== true)) {
286 resolve(course.people);
287 } else {
288 dtpsLMS.fetchUsers(course.lmsID).then(data => resolve(data));
289 }
290 }).then(data => {
291 var res = [];
292 data.forEach(section => {
293 section.users.forEach(user => {
294 user.locatedIn = section.title;
295 res.push(user);
296 });
297 });
298 resolve(res.map(person => ({
299 title: person.name,
300 class: course.num,
301 url: person.url,
302 locatedIn: person.locatedIn,
303 icon: "people",
304 icons: []
305 })));
306 }).catch(() => resolve([]));
307 }));
308 }
309
j7940eec2020-12-28 14:00:41 -0600310 if ((type == "announcements") || (type == "everything")) {
311 datasetPromises.push(new Promise((resolve, reject) => {
312 dtpsLMS.fetchAnnouncements(course.lmsID).then(announcements => {
313 resolve(announcements.map((announcement) => ({
314 title: announcement.title,
315 url: announcement.url,
316 class: course.num,
317 locatedIn: course.subject,
318 icon: "announcement",
319 body: $('<div>' + announcement.body + '</div>').text(),
320 infoIcons: [
321 "calendar_today"
322 ].filter(i => i),
323 info: [
324 "Posted at: " + dtps.formatDate(announcement.postedAt)
325 ].filter(i => i).join("$|$"),
326 icons: []
327 })));
328 }).catch(() => resolve([]));
329 }));
330 }
331 });
332
333 Promise.all(datasetPromises).then(results => {
334 results.forEach(result => {
335 dataset = dataset.concat(result);
336 });
337
338 var idx = lunr(function () {
339 this.ref('id');
340 this.field('title');
341 this.field('body');
342 this.field('locatedIn');
343 this.field('info');
344 this.metadataWhitelist = ['position'];
345
346 dataset.forEach(function (doc, i) {
347 this.add({
348 id: i,
349 ...doc
350 });
351 }, this)
352 });
353
354 var result = idx.search(term);
355 var resHTML = result.map(res => dtps.renderSearchResult(dataset[Number(res.ref)], res.matchData.metadata, courseNum == "all")).join("");
356
357 if (dtps.selectedClass == "search") {
358 $(".headerArea .contentLabel i").text("find_in_page");
359 $(".headerArea .contentLabel span").text(result.length + " results");
360 $(".headerArea .contentLabel").show();
361
362 $(".classContent").html(/*html*/`
363 <div ${!["assignments", "coursework"].includes(type) ? `style="display: none;"` : ``} id="searchFilterContainer">
364 <div id="searchFilterCard" class="card">
365 <h5><i class="fluid-icon">filter_alt</i><span>Filters</span></h5>
366 <div class="checkContainer">
367 <div id="missingSearchFilter" init="true" onclick="dtps.filterSearch(this)" class="checkbox"><i class="fluid-icon">check</i></div>
368 <div class="label"><i class="fluid-icon">remove_circle_outline</i> Missing</div>
369 </div>
370 <div class="checkContainer">
371 <div id="turnedInSearchFilter" init="true" onclick="dtps.filterSearch(this)" class="checkbox"><i class="fluid-icon">check</i></div>
372 <div class="label"><i class="fluid-icon">assignment_turned_in</i> Turned in</div>
373 </div>
374 <div class="checkContainer">
375 <div id="lateSearchFilter" init="true" onclick="dtps.filterSearch(this)" class="checkbox"><i class="fluid-icon">check</i></div>
376 <div class="label"><i class="fluid-icon">assignment_late</i> Late</div>
377 </div>
378 <div class="checkContainer">
379 <div id="lockedSearchFilter" init="true" onclick="dtps.filterSearch(this)" class="checkbox"><i class="fluid-icon">check</i></div>
380 <div class="label"><i class="fluid-icon">lock_outline</i> Locked</div>
381 </div>
382 </div>
383 </div>
384 <div ${["assignments", "coursework"].includes(type) ? `class="withFilters"` : ``} id="searchResultsContainer">
385 ${resHTML}
386 </div>
387 `);
388
389 if (!dtps.searchScrollListener) {
390 dtps.searchScrollListener = true;
391 var searchFilters = document.getElementById("searchFilterCard");
392 var sticky = searchFilters.offsetTop - parseFloat($("body").css("padding-top"));
393 window.onscroll = function () {
394 if ((window.pageYOffset >= sticky) && (dtps.selectedClass == "search")) {
395 $(".classContent").addClass("fixedSearchFilters");
396 } else {
397 $(".classContent").removeClass("fixedSearchFilters");
398 }
399 };
400 }
401 }
402
403 /**
404 * Filters search results
405 *
406 * @param {Element|string} [toggleItem] The selector for the element to toggle
407 */
408 dtps.filterSearch = function (toggleItem) {
409 if (toggleItem) $(toggleItem).toggleClass("active");
410
411 //Check for enabled filters
412 var missingFilter = $("#missingSearchFilter").hasClass("active");
413 var turnedInFilter = $("#turnedInSearchFilter").hasClass("active");
414 var lateFilter = $("#lateSearchFilter").hasClass("active");
415 var lockedFilter = $("#lockedSearchFilter").hasClass("active");
416
417 var filtersActive = missingFilter || turnedInFilter || lateFilter || lockedFilter;
418
419 var filterRes = result.filter(function (res) {
420 var item = dataset[Number(res.ref)];
421
422 if (!filtersActive) return true;
423
424 if (item.type == "assignment") {
425 if (missingFilter && item.icons.map(i => i.state).includes("missing")) return true;
426 if (turnedInFilter && item.icons.map(i => i.state).includes("turnedIn")) return true;
427 if (lateFilter && item.icons.map(i => i.state).includes("late")) return true;
428 if (lockedFilter && item.icons.map(i => i.state).includes("locked")) return true;
429 }
430
431 return false;
432 });
433
434 var filterHTML = filterRes.map(res => dtps.renderSearchResult(dataset[Number(res.ref)], res.matchData.metadata, courseNum == "all")).join("");
435
436 if (dtps.selectedClass == "search") {
437 $(".headerArea .contentLabel i").text(filtersActive ? "filter_alt" : "find_in_page");
438 $(".headerArea .contentLabel span").text(filterRes.length + " results");
439 $(".headerArea .contentLabel").show();
440
441 $("#searchResultsContainer").html(filterHTML);
442 }
443 }
444 });
445}
446
447/**
448 * Renders a Search data object into HTML for display in the search results list
449 *
450 * @param {SearchData} result The search result to render
451 * @param {Object[]} matchData The list of matches from Lunr
452 * @param {boolean} [mixedClasses] True if there are results from multiple classes
453 * @return {string} The HTML for this result in the results list
454 */
455dtps.renderSearchResult = function (result, matchData, mixedClasses) {
456
457 if (!result.processed) {
458 var matches = {};
459 var matchTerms = Object.values(matchData);
460 matchTerms.forEach(term => {
461 Object.keys(term).forEach(k => {
462 if (matches[k]) {
463 matches[k] = matches[k].concat(term[k].position);
464 } else {
465 matches[k] = term[k].position;
466 }
467 });
468 });
469 matches = Object.keys(matches).map(k => ({ key: k, position: matches[k] }));
470
471 //A function that highlights a string
472 function highlightString(string, position) {
473 var parts = string.split("");
474 position.forEach(pos => {
475 //highlight part
476 parts.forEach((part, i) => {
477 if (i == pos[0]) {
478 parts[i] = '<span class="highlight">' + parts[i];
479 }
480
481 if (i == (pos[0] + pos[1] - 1)) {
482 parts[i] = parts[i] + '</span>';
483 }
484 });
485 });
486
487 return parts.join("");
488 }
489
490 //Highlight matches
491 result.bodyParts = [];
492 result.bodyOverflow = 0;
493 matches.forEach(match => {
494 if (match.key == "title") {
495 result.title = highlightString(result.title, match.position);
496 } else if (match.key == "locatedIn") {
497 result.locatedIn = highlightString(result.locatedIn, match.position);
498 } else if (match.key == "body") {
499 //Get longest 2 matches
500 var sections = match.position.sort((a, b) => b[1] - a[1]);
501 var matchesToDisplay = 2;
502 if (sections.length < matchesToDisplay) matchesToDisplay = sections.length;
503 result.bodyOverflow = sections.length - matchesToDisplay;
504
505 for (var i = 0; i < matchesToDisplay; i++) {
506 var matchStartIndex = sections[i][0];
507 var matchEndIndex = sections[i][0] + sections[i][1] - 1;
508
509 var startIndex = matchStartIndex - 10;
510 var endIndex = matchEndIndex + 10;
511
512 if (startIndex < 0) startIndex = 0;
513 if (endIndex > (result.body.length - 1)) endIndex = result.body.length - 1;
514
515 var res = result.body.slice(startIndex, matchStartIndex) + '<span class="highlight">' + result.body.slice(matchStartIndex, matchEndIndex + 1) + '</span>' + result.body.slice(matchEndIndex + 1, endIndex + 1);
516 result.bodyParts.push(res);
517 }
518 } else if (match.key == "info") {
519 result.info = highlightString(result.info, match.position);
520 }
521 });
522
523 //Map result info back into an array
524 if (result.info) {
525 result.info = result.info.split("$|$").map((info, i) => {
526 return {
527 icon: result.infoIcons[i],
528 info: info,
529 }
530 });
531 }
532
533 //Mark this result as processed so it doesn't have to be re-highlighted if a filter is used
534 result.processed = true;
535 }
536
537 return /*html*/`
538 <div
539 class="card searchResult ${mixedClasses ? "mixedClasses" : ""}"
540 style="${'--classColor: ' + dtps.classes[result.class].color}"
541 onclick="${result.onclick || (result.url && "window.open('" + result.url + "')")}"
542 >
543
544 <!-- Color bar for the dashboard -->
545 <div class="colorBar"></div>
546
547 <!-- Assignment title and points -->
548 ${result.title ? `<h4>${result.title}</h4>` : ""}
549
550 <h5>
551 <div class="infoChip"><i style="margin-top: -2px;" class="fluid-icon">${result.icon}</i> ${result.locatedIn}</div>
552 ${result.info ? result.info.map(info => (
553 `<div class="infoChip"><i style="margin-top: -2px;" class="fluid-icon">${info.icon}</i> ${info.info}</div>`
554 )).join("") : ""}
555 </h5>
556
557 ${result.bodyParts.map(part => (
558 `<p><span style="color: var(--secText);">...</span>${part}<span style="color: var(--secText);">...</span></p>`
559 )).join("")}
560 ${result.bodyOverflow ? `<p style="color: var(--secText);">+${result.bodyOverflow} more matches</p>` : ""}
561
562 <h5>
563 ${result.icons.map((icon, i) => (`<i class="fluid-icon statusIcon">${icon.icon}</i>`)).join("")}
564 </h5>
565 </div>
566 `;
567}
568
569//Fluid UI screen definitions
570fluid.externalScreens.search = (term) => {
571 dtps.globalSearch(term);
572}
573
574/**
575 * @typedef {Object} SearchData
576 * @description An object that can represent any type of data to be searched.
577 * @property {string} [title] Result title
578 * @property {string} [body] Result body (can be HTML)
579 * @property {string} [url] A URL for opening this result in the LMS
580 * @property {string} locatedIn Describes where this result was found (as specific as possible)
581 * @property {string} icon The icon to use for this result. Should match (and is displayed with) the locatedIn property.
582 * @property {Object[]} [info] Contains any info (e.g. due dates) for this result. Has an icon property, label property, and info property.
583 * @property {Object[]} icons Status icons for this result. Has an "icon" property, for the icon, and a "keywords" property for a string with all of the search keywords for the icon.
584 * @property {number} class The number of the class that this result is from
j645a8682020-12-22 14:27:23 -0600585 */