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