-
-
Notifications
You must be signed in to change notification settings - Fork 28
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Move JSON-LD schema.org logic into single view + model; truncate or pad descriptions that are too long or too short #2559
Move JSON-LD schema.org logic into single view + model; truncate or pad descriptions that are too long or too short #2559
Conversation
- Model can handle Dataset and DataCatalog types, and can import attributes from a template string. - Model includes methods for truncating or padding descriptions to meet Google's requirements. - Add unit tests for the model. Issue #1899
- Remove logic for creating and inserting schema.org JSON-LD from AppView, DataCatalogView, MetadataView, and CatalogSearchView. - Use the SchemaOrg model that is set on the MetacatUI.AppView instead. - Move the jsonLD template importing to the SchemaOrgView. - Use the jsonLD template content in jsonLD tag as default for non-dataset and non-dataCatalog pages. Issue #1899
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Remaining comments which cannot be posted as a review comment to avoid GitHub Rate Limit
eslint
🚫 [eslint] <prefer-arrow-callback> reported by reviewdog 🐶
Unexpected function expression.
metacatui/src/js/views/AppView.js
Lines 14 to 840 in b0aa7ab
], function ( | |
$, | |
_, | |
Backbone, | |
AltHeaderView, | |
NavbarView, | |
FooterView, | |
SignInView, | |
SchemaOrgView, | |
AlertTemplate, | |
AppHeadTemplate, | |
AppTemplate, | |
LoadingTemplate, | |
) { | |
"use strict"; | |
var app = app || {}; | |
/** | |
* @class AppView | |
* @classdesc The top-level view of the UI that contains and coordinates all other views of the UI | |
* @classcategory Views | |
* @extends Backbone.View | |
*/ | |
var AppView = Backbone.View.extend( | |
/** @lends AppView.prototype */ { | |
// Instead of generating a new element, bind to the existing skeleton of | |
// the App already present in the HTML. | |
el: "#metacatui-app", | |
//Templates | |
template: _.template(AppTemplate), | |
alertTemplate: _.template(AlertTemplate), | |
appHeadTemplate: _.template(AppHeadTemplate), | |
loadingTemplate: _.template(LoadingTemplate), | |
events: { | |
click: "closePopovers", | |
"click .btn.direct-search": "routeToMetadata", | |
"keypress input.direct-search": "routeToMetadataOnEnter", | |
"click .toggle-slide": "toggleSlide", | |
"click input.copy": "higlightInput", | |
"focus input.copy": "higlightInput", | |
"click textarea.copy": "higlightInput", | |
"focus textarea.copy": "higlightInput", | |
"click .open-chat": "openChatWithMessage", | |
"click .login.redirect": "sendToLogin", | |
"focus .jump-width-input": "widenInput", | |
"focusout .jump-width-input": "narrowInput", | |
"click .temporary-message .close": "hideTemporaryMessage", | |
}, | |
initialize: function () { | |
//Check for the LDAP sign in error message | |
if ( | |
window.location.search.indexOf( | |
"error=Unable%20to%20authenticate%20LDAP%20user", | |
) > -1 | |
) { | |
window.location = | |
window.location.origin + | |
window.location.pathname + | |
"#signinldaperror"; | |
} | |
//Is there a logged-in user? | |
MetacatUI.appUserModel.checkStatus(); | |
//Change the document title when the app changes the MetacatUI.appModel title at any time | |
this.listenTo(MetacatUI.appModel, "change:title", this.changeTitle); | |
this.listenTo( | |
MetacatUI.appModel, | |
"change:description", | |
this.changeDescription, | |
); | |
this.checkIncompatibility(); | |
}, | |
/** | |
* The JS query selector for the element inside the AppView that contains the main view contents. When a new view is routed to | |
* and displayed via {@link AppView#showView}, the view will be inserted into this element. | |
* @type {string} | |
* @default "#Content" | |
* @since 2.22.0 | |
*/ | |
contentSelector: "#Content", | |
/** | |
* Gets the Element in this AppView via the {@link AppView#contentSelector} | |
* @returns {Element} | |
*/ | |
getContentEl: function () { | |
return this.el.querySelector(this.contentSelector); | |
}, | |
/** | |
* Change the web document's title | |
*/ | |
changeTitle: function () { | |
document.title = MetacatUI.appModel.get("title"); | |
}, | |
/** | |
* Change the web document's description | |
* @since 2.25.0 | |
*/ | |
changeDescription: function () { | |
$("meta[name=description]").attr( | |
"content", | |
MetacatUI.appModel.get("description"), | |
); | |
}, | |
/** Render the main view and/or re-render subviews. Delegate rendering | |
and event handling to sub views. | |
--- | |
If there is no AppView element on the page, don't render the application. | |
--- | |
If there is no AppView element on the page, this function will exit without rendering anything. | |
For instance, this can occur when the AppView is loaded during unit tests. | |
See {@link AppView#el} to check which element is required for rendering. By default, | |
it is set to the element with the `metacatui-app` id (check docs for the most up-to-date info). | |
---- | |
This step is usually unnecessary for Backbone Views since they should only render elements inside of | |
their own `el` anyway. But the APpView is different since it renders the overall structure of MetacatUI. | |
*/ | |
render: function () { | |
//If there is no AppView element on the page, don't render the application. | |
if (!this.el) { | |
console.error( | |
"Not rendering the UI of the app since the AppView HTML element (AppView.el) does not exist on the page. Make sure you have the AppView element included in index.html", | |
); | |
return; | |
} | |
// set up the head | |
$("head").append( | |
this.appHeadTemplate({ | |
theme: MetacatUI.theme, | |
}), | |
); | |
// Add schema.org JSON-LD to the head | |
this.schemaOrg = new SchemaOrgView(); | |
this.schemaOrg.render(); | |
this.schemaOrg.setSchemaFromTemplate(); | |
// set up the body | |
this.$el.append(this.template()); | |
/** | |
* @name MetacatUI.navbarView | |
* @type NavbarView | |
* @description The view that displays a navigation menu on every MetacatUI page and controls the navigation between pages in MetacatUI. | |
*/ | |
MetacatUI.navbarView = new NavbarView(); | |
MetacatUI.navbarView.setElement($("#Navbar")).render(); | |
/** | |
* @name MetacatUI.altHeaderView | |
* @type AltHeaderView | |
* @description The view that displays a header on every MetacatUI view that uses the "AltHeader" header type. | |
* This header is usually for decorative / aesthetic purposes only. | |
*/ | |
MetacatUI.altHeaderView = new AltHeaderView(); | |
MetacatUI.altHeaderView.setElement($("#HeaderContainer")).render(); | |
/** | |
* @name MetacatUI.footerView | |
* @type FooterView | |
* @description The view that displays the main footer of the MetacatUI page. | |
* It has informational and navigational links in it and is displayed on every page, except for views that hide it for full-screen display. | |
*/ | |
MetacatUI.footerView = new FooterView(); | |
MetacatUI.footerView.setElement($("#Footer")).render(); | |
this.showTemporaryMessage(); | |
//Load the Slaask chat widget if it is enabled in this theme | |
if (MetacatUI.appModel.get("slaaskKey") && window._slaask) | |
_slaask.init(MetacatUI.appModel.get("slaaskKey")); | |
this.listenForActivity(); | |
this.listenForTimeout(); | |
this.initializeWidgets(); | |
return this; | |
}, | |
// the currently rendered view | |
currentView: null, | |
// Our view switcher for the whole app | |
showView: function (view, viewOptions) { | |
if (!this.el) { | |
console.error( | |
"Not rendering the UI of the app since the AppView HTML element (AppView.el) does not exist on the page. Make sure you have the AppView element included in index.html", | |
); | |
return; | |
} | |
//reference to appView | |
var thisAppViewRef = this; | |
// Change the background image if there is one | |
MetacatUI.navbarView.changeBackground(); | |
// close the current view | |
if (this.currentView) { | |
//If the current view has a function to confirm closing of the view, call it | |
if (typeof this.currentView.canClose == "function") { | |
//If the user or view confirmed that the view shouldn't be closed, then don't navigate to the next route | |
if (!this.currentView.canClose()) { | |
//Get a confirmation message from the view, or use a default one | |
if ( | |
typeof this.currentView.getConfirmCloseMessage == "function" | |
) { | |
var confirmMessage = this.currentView.getConfirmCloseMessage(); | |
} else { | |
var confirmMessage = "Leave this page?"; | |
} | |
//Show a confirm alert to the user and wait for their response | |
var leave = confirm(confirmMessage); | |
//If they clicked Cancel, then don't navigate to the next route | |
if (!leave) { | |
MetacatUI.uiRouter.undoLastRoute(); | |
return; | |
} | |
} | |
} | |
// need reference to the old/current view for the callback method | |
var oldView = this.currentView; | |
this.currentView.$el.fadeOut("slow", function () { | |
// clean up old view | |
if (oldView.onClose) oldView.onClose(); | |
//If the view to show is not the same as the main content element, then put it inside the content element. | |
if (view.el !== thisAppViewRef.getContentEl()) { | |
thisAppViewRef.getContentEl().replaceChildren(view.el); | |
$(thisAppViewRef.getContentEl()).show(); | |
} | |
view.$el.fadeIn("slow", function () { | |
// render the new view | |
view.render(viewOptions); | |
// after fade in, do postRender() | |
if (view.postRender) view.postRender(); | |
// force scroll to top if no custom scrolling is implemented | |
else thisAppViewRef.scrollToTop(); | |
}); | |
}); | |
} else { | |
//If the view to show is not the same as the main content element, then put it inside the content element. | |
if (view.el !== this.getContentEl()) { | |
this.getContentEl().replaceChildren(view.el); | |
} | |
// just show the view without transition | |
view.render(viewOptions); | |
if (view.postRender) view.postRender(); | |
// force scroll to top if no custom scrolling is implemented | |
else thisAppViewRef.scrollToTop(); | |
} | |
// track the current view | |
this.currentView = view; | |
MetacatUI.analytics?.trackPageView(); | |
this.trigger("appRenderComplete"); | |
}, | |
routeToMetadata: function (e) { | |
e.preventDefault(); | |
//Get the value from the input element | |
var form = $(e.target).attr("form") || null, | |
val = this.$("#" + form) | |
.find("input[type=text]") | |
.val(); | |
//Remove the text from the input | |
this.$("#" + form) | |
.find("input[type=text]") | |
.val(""); | |
if (!val) return false; | |
MetacatUI.uiRouter.navigate("view/" + val, { trigger: true }); | |
}, | |
routeToMetadataOnEnter: function (e) { | |
//If the user pressed a key inside a text input, we only want to proceed if it was the Enter key | |
if (e.type == "keypress" && e.keycode != 13) return; | |
else this.routeToMetadata(e); | |
}, | |
sendToLogin: function (e) { | |
if (e) e.preventDefault(); | |
var url = $(e.target).attr("href"); | |
url = url.substring(0, url.indexOf("target=") + 7); | |
url += window.location.href; | |
window.location.href = url; | |
}, | |
resetSearch: function () { | |
// Clear the search and map model to start a fresh search | |
MetacatUI.appSearchModel.clear(); | |
MetacatUI.appSearchModel.set(MetacatUI.appSearchModel.defaults()); | |
MetacatUI.mapModel.clear(); | |
MetacatUI.mapModel.set(MetacatUI.mapModel.defaults()); | |
//Clear the search history | |
MetacatUI.appModel.set("searchHistory", new Array()); | |
MetacatUI.uiRouter.navigate("data", { trigger: true }); | |
}, | |
closePopovers: function (e) { | |
if (this.currentView && this.currentView.closePopovers) | |
this.currentView.closePopovers(e); | |
}, | |
toggleSlide: function (e) { | |
if (e) e.preventDefault(); | |
else return false; | |
var clickedOn = $(e.target), | |
toggleElId = | |
clickedOn.attr("data-slide-el") || | |
clickedOn.parents("[data-slide-el]").attr("data-slide-el"), | |
toggleEl = $("#" + toggleElId); | |
toggleEl.slideToggle("fast", function () { | |
//Toggle the display of the link if it has the right class | |
if (clickedOn.is(".toggle-display-on-slide")) { | |
clickedOn.siblings(".toggle-display-on-slide").toggle(); | |
clickedOn.toggle(); | |
} | |
}); | |
}, | |
/** | |
* Displays the given message to the user in a Bootstrap "alert" style. | |
* @param {object} options A literal object of options for the alert message. | |
* @property {string|Element} options.message A message string or HTML Element to display | |
* @property {string} [options.classes] A string of HTML classes to set on the alert | |
* @property {string|Element} [options.container] The container to show the alert in | |
* @property {boolean} [options.replaceContents] If true, the alert will replace the contents of the container element. | |
* If false, the alert will be prepended to the container element. | |
* @property {boolean|number} [options.delay] Set to true or specify a number of milliseconds to display the alert temporarily | |
* @property {boolean} [options.remove] If true, the user will be able to remove the alert with a "close" icon. | |
* @property {boolean} [options.includeEmail] If true, the alert will include a link to the {@link AppConfig#emailContact} | |
* @property {string} [options.emailBody] Specify an email body to use in the email link. | |
* @returns {Element} The alert element | |
*/ | |
showAlert: function () { | |
if (arguments.length > 1) { | |
var options = { | |
message: arguments[0], | |
classes: arguments[1], | |
container: arguments[2], | |
delay: arguments[3], | |
}; | |
if (typeof arguments[4] == "object") { | |
options = _.extend(options, arguments[4]); | |
} | |
} else { | |
var options = arguments[0]; | |
} | |
if (typeof options != "object" || !options) { | |
return; | |
} | |
if (!options.classes) options.classes = "alert-success"; | |
if (!options.container || !$(options.container).length) | |
options.container = this.$el; | |
//Remove any alerts that are already in this container | |
if ($(options.container).children(".alert-container").length > 0) | |
$(options.container).children(".alert-container").remove(); | |
//Allow messages to be HTML or strings | |
if (typeof options.message != "string") | |
options.message = $(document.createElement("div")) | |
.append($(options.message)) | |
.html(); | |
var emailOptions = ""; | |
//Check for more options | |
if (options.emailBody) emailOptions += "?body=" + options.emailBody; | |
var alert = $.parseHTML( | |
this.alertTemplate({ | |
msg: options.message, | |
classes: options.classes, | |
emailOptions: emailOptions, | |
remove: options.remove || false, | |
includeEmail: options.includeEmail, | |
}).trim(), | |
); | |
if (options.delay) { | |
$(alert).hide(); | |
if (options.replaceContents) { | |
$(options.container).html(alert); | |
} else { | |
$(options.container).prepend(alert); | |
} | |
$(alert) | |
.show() | |
.delay(typeof options.delay == "number" ? options.delay : 3000) | |
.fadeOut(); | |
} else { | |
if (options.replaceContents) { | |
$(options.container).html(alert); | |
} else { | |
$(options.container).prepend(alert); | |
} | |
} | |
return alert; | |
}, | |
/** | |
* Previous to MetacatUI 2.14.0, the {@link AppView#showAlert} function allowed up to five parameters | |
* to customize the alert message. As of 2.14.0, the function has condensed these options into | |
* a single literal object. See the docs for {@link AppView#showAlert}. The old signature of five | |
* parameters may soon be deprecated completely, but is still supported. | |
* @deprecated | |
* @param {string|Element} msg | |
* @param {string} [classes] | |
* @param {string|Element} [container] | |
* @param {boolean} [delay] | |
* @param {object} [options] | |
* @param {boolean} [options.includeEmail] If true, the alert will include a link to the {@link AppConfig#emailContact} | |
* @param {string} [options.emailBody] | |
* @param {boolean} [options.remove] | |
* @param {boolean} [options.replaceContents] | |
*/ | |
showAlert_deprecated: function ( | |
msg, | |
classes, | |
container, | |
delay, | |
options, | |
) {}, | |
/** | |
* Listens to the focus event on the window to detect when a user switches back to this browser tab from somewhere else | |
* When a user checks back, we want to check for log-in status | |
*/ | |
listenForActivity: function () { | |
MetacatUI.appUserModel.on("change:loggedIn", function () { | |
if (!MetacatUI.appUserModel.get("loggedIn")) return; | |
//When the user re-focuses back on the window | |
$(window).focus(function () { | |
//If the user has logged out in the meantime, then exit | |
if (!MetacatUI.appUserModel.get("loggedIn")) return; | |
//If the expiration date of the token has passed, then allow the user to sign back in | |
if (MetacatUI.appUserModel.get("expires") <= new Date()) { | |
MetacatUI.appView.showTimeoutSignIn(); | |
} | |
}); | |
}); | |
}, | |
/** | |
* Will determine the length of time until the user's current token expires, | |
* and will set a window timeout for that length of time. When the timeout | |
* is triggered, the sign in modal window will be displayed so that the user | |
* can sign in again (which happens in AppView.showTimeoutSignIn()) | |
*/ | |
listenForTimeout: function () { | |
//Only proceed if the user is logged in | |
if (!MetacatUI.appUserModel.get("checked")) { | |
//When the user logged back in, listen again for the next timeout | |
this.listenToOnce( | |
MetacatUI.appUserModel, | |
"change:checked", | |
function () { | |
//If the user is logged in, then listen call this function again | |
if ( | |
MetacatUI.appUserModel.get("checked") && | |
MetacatUI.appUserModel.get("loggedIn") | |
) | |
this.listenForTimeout(); | |
}, | |
); | |
return; | |
} else if (!MetacatUI.appUserModel.get("loggedIn")) { | |
//When the user logged back in, listen again for the next timeout | |
this.listenToOnce( | |
MetacatUI.appUserModel, | |
"change:loggedIn", | |
function () { | |
//If the user is logged in, then listen call this function again | |
if ( | |
MetacatUI.appUserModel.get("checked") && | |
MetacatUI.appUserModel.get("loggedIn") | |
) | |
this.listenForTimeout(); | |
}, | |
); | |
return; | |
} | |
var view = this, | |
expires = MetacatUI.appUserModel.get("expires"), | |
timeLeft = expires - new Date(); | |
//If there is no time left until expiration, then show the sign in view now | |
if (timeLeft < 0) { | |
this.showTimeoutSignIn(); | |
} | |
//Otherwise, set a timeout for a expiration time, then show the Sign In View | |
else { | |
var timeoutId = setTimeout(function () { | |
view.showTimeoutSignIn.call(view); | |
}, timeLeft); | |
//Save the timeout id in case we want to destroy the timeout later | |
MetacatUI.appUserModel.set("timeoutId", timeoutId); | |
} | |
}, | |
/** | |
* If the user's auth token has expired, a new SignInView model window is | |
* displayed so the user can sign back in. A listener is set on the appUserModel | |
* so that when they do successfully sign back in, we set another timeout listener | |
* via AppView.listenForTimeout() | |
*/ | |
showTimeoutSignIn: function () { | |
if (MetacatUI.appUserModel.get("expires") <= new Date()) { | |
MetacatUI.appUserModel.set("loggedIn", false); | |
var signInView = new SignInView({ | |
inPlace: true, | |
closeButtons: false, | |
topMessage: | |
"Your session has timed out. Click Sign In to open a " + | |
"new window to sign in again. Make sure your browser settings allow pop-ups.", | |
}); | |
var signInForm = signInView.render().el; | |
if (this.subviews && Array.isArray(this.subviews)) | |
this.subviews.push(signInView); | |
else this.subviews = [signInView]; | |
$("body").append(signInForm); | |
$(signInForm).modal(); | |
//When the user logged back in, listen again for the next timeout | |
this.listenToOnce( | |
MetacatUI.appUserModel, | |
"change:checked", | |
function () { | |
if ( | |
MetacatUI.appUserModel.get("checked") && | |
MetacatUI.appUserModel.get("loggedIn") | |
) | |
this.listenForTimeout(); | |
}, | |
); | |
} | |
}, | |
openChatWithMessage: function () { | |
if (!_slaask) return; | |
$("#slaask-input").val(MetacatUI.appModel.get("defaultSupportMessage")); | |
$("#slaask-button").trigger("click"); | |
}, | |
initializeWidgets: function () { | |
// Autocomplete widget extension to provide description tooltips. | |
$.widget("app.hoverAutocomplete", $.ui.autocomplete, { | |
// Set the content attribute as the "item.desc" value. | |
// This becomes the tooltip content. | |
_renderItem: function (ul, item) { | |
// if we have a label, use it for the title | |
var title = item.value; | |
if (item.label) { | |
title = item.label; | |
} | |
// if we have a description, use it for the content | |
var content = item.value; | |
if (item.desc) { | |
content = item.desc; | |
if (item.desc != item.value) { | |
content += " (" + item.value + ")"; | |
} | |
} | |
var element = this._super(ul, item) | |
.attr("data-title", title) | |
.attr("data-content", content); | |
element.popover({ | |
placement: "right", | |
trigger: "hover", | |
container: "body", | |
}); | |
return element; | |
}, | |
}); | |
}, | |
/** | |
* Checks if the user's browser is an outdated version that won't work with | |
* MetacatUI well, and displays a warning message to the user.. | |
* The user agent is checked against the `unsupportedBrowsers` list in the AppModel. | |
*/ | |
checkIncompatibility: function () { | |
//Check if this browser is incompatible with this app. i.e. It is an old browser version | |
var isUnsupportedBrowser = _.some( | |
MetacatUI.appModel.get("unsupportedBrowsers"), | |
function (browserRegEx) { | |
var matches = navigator.userAgent.match(browserRegEx); | |
return matches && matches.length > 0; | |
}, | |
); | |
if (!isUnsupportedBrowser) { | |
return; | |
} else { | |
//Show a warning message to the user about their browser. | |
this.showAlert( | |
"Your web browser is out of date. Update your browser for more security, " + | |
"speed and the best experience on this site.", | |
"alert-warning", | |
this.$el, | |
false, | |
{ remove: true }, | |
); | |
this.$el | |
.children(".alert-container") | |
.addClass("important-app-message"); | |
} | |
}, | |
/** | |
* Shows a temporary message at the top of the view | |
*/ | |
showTemporaryMessage: function () { | |
try { | |
//Is there a temporary message to display throughout the app? | |
if (MetacatUI.appModel.get("temporaryMessage")) { | |
var startTime = MetacatUI.appModel.get("temporaryMessageStartTime"), | |
endTime = MetacatUI.appModel.get("temporaryMessageEndTime"), | |
today = new Date(), | |
isDisplayed = false; | |
//Find cases where we should display the message | |
//If there is a date range and today is in the range | |
if (startTime && endTime && today > startTime && today < endTime) { | |
isDisplayed = true; | |
} | |
//If there's just a start time and today is after it | |
else if (startTime && !endTime && today > startTime) { | |
isDisplayed = true; | |
} | |
//If there's just an end time and today is before it | |
else if (!startTime && endTime && today < endTime) { | |
isDisplayed = true; | |
} | |
//If there's no start or end time | |
else if (!startTime && !endTime) { | |
isDisplayed = true; | |
} | |
if (isDisplayed) { | |
require(["text!templates/alert.html"], function (alertTemplate) { | |
//Get classes for the message | |
var classes = | |
MetacatUI.appModel.get("temporaryMessageClasses") || ""; | |
classes += " temporary-message"; | |
var container = | |
MetacatUI.appModel.get("temporaryMessageContainer") || | |
"#Navbar"; | |
//If the message exists already, return | |
if ($(container + " .temporary-message").length) { | |
return; | |
} | |
//Insert the message using the Alert template | |
$(container).prepend( | |
_.template(alertTemplate)({ | |
classes: classes, | |
msg: MetacatUI.appModel.get("temporaryMessage"), | |
includeEmail: MetacatUI.appModel.get( | |
"temporaryMessageIncludeEmail", | |
), | |
remove: true, | |
}), | |
); | |
//Add a class to the body in case we need to adjust other elements on the page | |
$("body").addClass("has-temporary-message"); | |
}); | |
} | |
} | |
} catch (e) { | |
console.error("Couldn't display the temporary message: ", e); | |
} | |
}, | |
/** | |
* Hides the temporary message | |
*/ | |
hideTemporaryMessage: function () { | |
try { | |
this.$(".temporary-message").remove(); | |
$("body").removeClass("has-temporary-message"); | |
} catch (e) { | |
console.error("Couldn't hide the temporary message: ", e); | |
} | |
}, | |
/********************** Utilities ********************************/ | |
// Various utility functions to use across the app // | |
/************ Function to add commas to large numbers ************/ | |
commaSeparateNumber: function (val) { | |
if (!val) return 0; | |
if (val < 1) return Math.round(val * 100) / 100; | |
while (/(\d+)(\d{3})/.test(val.toString())) { | |
val = val.toString().replace(/(\d+)(\d{3})/, "$1" + "," + "$2"); | |
} | |
return val; | |
}, | |
numberAbbreviator: function (number, decimalPlaces) { | |
if (number === 0) { | |
return 0; | |
} | |
decimalPlaces = Math.pow(10, decimalPlaces); | |
var abbreviations = ["K", "M", "B", "T"]; | |
// Go through the array backwards, so we do the largest first | |
for (var i = abbreviations.length - 1; i >= 0; i--) { | |
// Convert array index to "1000", "1000000", etc | |
var size = Math.pow(10, (i + 1) * 3); | |
// If the number is bigger or equal do the abbreviation | |
if (size <= number) { | |
// Here, we multiply by decimalPlaces, round, and then divide by decimalPlaces. | |
// This gives us nice rounding to a particular decimal place. | |
number = | |
Math.round((number * decimalPlaces) / size) / decimalPlaces; | |
// Handle special case where we round up to the next abbreviation | |
if (number == 1000 && i < abbreviations.length - 1) { | |
number = 1; | |
i++; | |
} | |
// Add the letter for the abbreviation | |
number += abbreviations[i]; | |
break; | |
} | |
} | |
return number; | |
}, | |
higlightInput: function (e) { | |
if (!e) return; | |
e.preventDefault(); | |
e.target.setSelectionRange(0, 9999); | |
}, | |
widenInput: function (e) { | |
$(e.target).css("width", "200px"); | |
}, | |
narrowInput: function (e) { | |
$(e.target).delay(500).animate({ width: "60px" }); | |
}, | |
// scroll to top of page | |
scrollToTop: function () { | |
$("body,html") | |
.stop(true, true) //stop first for it to work in FF | |
.animate({ scrollTop: 0 }, "slow"); | |
return false; | |
}, | |
scrollTo: function (pageElement, offsetTop) { | |
//Find the header height if it is a fixed element | |
var headerOffset = | |
this.$("#Header").css("position") == "fixed" | |
? this.$("#Header").outerHeight() | |
: 0; | |
var navOffset = | |
this.$("#Navbar").css("position") == "fixed" | |
? this.$("#Navbar").outerHeight() | |
: 0; | |
var totalOffset = headerOffset + navOffset; | |
$("body,html") | |
.stop(true, true) //stop first for it to work in FF | |
.animate( | |
{ scrollTop: $(pageElement).offset().top - 40 - totalOffset }, | |
1000, | |
); | |
return false; | |
}, | |
}, | |
); | |
return AppView; | |
}); |
🚫 [eslint] <no-var> reported by reviewdog 🐶
Unexpected var, use let or const instead.
metacatui/src/js/views/AppView.js
Lines 38 to 838 in b0aa7ab
var AppView = Backbone.View.extend( | |
/** @lends AppView.prototype */ { | |
// Instead of generating a new element, bind to the existing skeleton of | |
// the App already present in the HTML. | |
el: "#metacatui-app", | |
//Templates | |
template: _.template(AppTemplate), | |
alertTemplate: _.template(AlertTemplate), | |
appHeadTemplate: _.template(AppHeadTemplate), | |
loadingTemplate: _.template(LoadingTemplate), | |
events: { | |
click: "closePopovers", | |
"click .btn.direct-search": "routeToMetadata", | |
"keypress input.direct-search": "routeToMetadataOnEnter", | |
"click .toggle-slide": "toggleSlide", | |
"click input.copy": "higlightInput", | |
"focus input.copy": "higlightInput", | |
"click textarea.copy": "higlightInput", | |
"focus textarea.copy": "higlightInput", | |
"click .open-chat": "openChatWithMessage", | |
"click .login.redirect": "sendToLogin", | |
"focus .jump-width-input": "widenInput", | |
"focusout .jump-width-input": "narrowInput", | |
"click .temporary-message .close": "hideTemporaryMessage", | |
}, | |
initialize: function () { | |
//Check for the LDAP sign in error message | |
if ( | |
window.location.search.indexOf( | |
"error=Unable%20to%20authenticate%20LDAP%20user", | |
) > -1 | |
) { | |
window.location = | |
window.location.origin + | |
window.location.pathname + | |
"#signinldaperror"; | |
} | |
//Is there a logged-in user? | |
MetacatUI.appUserModel.checkStatus(); | |
//Change the document title when the app changes the MetacatUI.appModel title at any time | |
this.listenTo(MetacatUI.appModel, "change:title", this.changeTitle); | |
this.listenTo( | |
MetacatUI.appModel, | |
"change:description", | |
this.changeDescription, | |
); | |
this.checkIncompatibility(); | |
}, | |
/** | |
* The JS query selector for the element inside the AppView that contains the main view contents. When a new view is routed to | |
* and displayed via {@link AppView#showView}, the view will be inserted into this element. | |
* @type {string} | |
* @default "#Content" | |
* @since 2.22.0 | |
*/ | |
contentSelector: "#Content", | |
/** | |
* Gets the Element in this AppView via the {@link AppView#contentSelector} | |
* @returns {Element} | |
*/ | |
getContentEl: function () { | |
return this.el.querySelector(this.contentSelector); | |
}, | |
/** | |
* Change the web document's title | |
*/ | |
changeTitle: function () { | |
document.title = MetacatUI.appModel.get("title"); | |
}, | |
/** | |
* Change the web document's description | |
* @since 2.25.0 | |
*/ | |
changeDescription: function () { | |
$("meta[name=description]").attr( | |
"content", | |
MetacatUI.appModel.get("description"), | |
); | |
}, | |
/** Render the main view and/or re-render subviews. Delegate rendering | |
and event handling to sub views. | |
--- | |
If there is no AppView element on the page, don't render the application. | |
--- | |
If there is no AppView element on the page, this function will exit without rendering anything. | |
For instance, this can occur when the AppView is loaded during unit tests. | |
See {@link AppView#el} to check which element is required for rendering. By default, | |
it is set to the element with the `metacatui-app` id (check docs for the most up-to-date info). | |
---- | |
This step is usually unnecessary for Backbone Views since they should only render elements inside of | |
their own `el` anyway. But the APpView is different since it renders the overall structure of MetacatUI. | |
*/ | |
render: function () { | |
//If there is no AppView element on the page, don't render the application. | |
if (!this.el) { | |
console.error( | |
"Not rendering the UI of the app since the AppView HTML element (AppView.el) does not exist on the page. Make sure you have the AppView element included in index.html", | |
); | |
return; | |
} | |
// set up the head | |
$("head").append( | |
this.appHeadTemplate({ | |
theme: MetacatUI.theme, | |
}), | |
); | |
// Add schema.org JSON-LD to the head | |
this.schemaOrg = new SchemaOrgView(); | |
this.schemaOrg.render(); | |
this.schemaOrg.setSchemaFromTemplate(); | |
// set up the body | |
this.$el.append(this.template()); | |
/** | |
* @name MetacatUI.navbarView | |
* @type NavbarView | |
* @description The view that displays a navigation menu on every MetacatUI page and controls the navigation between pages in MetacatUI. | |
*/ | |
MetacatUI.navbarView = new NavbarView(); | |
MetacatUI.navbarView.setElement($("#Navbar")).render(); | |
/** | |
* @name MetacatUI.altHeaderView | |
* @type AltHeaderView | |
* @description The view that displays a header on every MetacatUI view that uses the "AltHeader" header type. | |
* This header is usually for decorative / aesthetic purposes only. | |
*/ | |
MetacatUI.altHeaderView = new AltHeaderView(); | |
MetacatUI.altHeaderView.setElement($("#HeaderContainer")).render(); | |
/** | |
* @name MetacatUI.footerView | |
* @type FooterView | |
* @description The view that displays the main footer of the MetacatUI page. | |
* It has informational and navigational links in it and is displayed on every page, except for views that hide it for full-screen display. | |
*/ | |
MetacatUI.footerView = new FooterView(); | |
MetacatUI.footerView.setElement($("#Footer")).render(); | |
this.showTemporaryMessage(); | |
//Load the Slaask chat widget if it is enabled in this theme | |
if (MetacatUI.appModel.get("slaaskKey") && window._slaask) | |
_slaask.init(MetacatUI.appModel.get("slaaskKey")); | |
this.listenForActivity(); | |
this.listenForTimeout(); | |
this.initializeWidgets(); | |
return this; | |
}, | |
// the currently rendered view | |
currentView: null, | |
// Our view switcher for the whole app | |
showView: function (view, viewOptions) { | |
if (!this.el) { | |
console.error( | |
"Not rendering the UI of the app since the AppView HTML element (AppView.el) does not exist on the page. Make sure you have the AppView element included in index.html", | |
); | |
return; | |
} | |
//reference to appView | |
var thisAppViewRef = this; | |
// Change the background image if there is one | |
MetacatUI.navbarView.changeBackground(); | |
// close the current view | |
if (this.currentView) { | |
//If the current view has a function to confirm closing of the view, call it | |
if (typeof this.currentView.canClose == "function") { | |
//If the user or view confirmed that the view shouldn't be closed, then don't navigate to the next route | |
if (!this.currentView.canClose()) { | |
//Get a confirmation message from the view, or use a default one | |
if ( | |
typeof this.currentView.getConfirmCloseMessage == "function" | |
) { | |
var confirmMessage = this.currentView.getConfirmCloseMessage(); | |
} else { | |
var confirmMessage = "Leave this page?"; | |
} | |
//Show a confirm alert to the user and wait for their response | |
var leave = confirm(confirmMessage); | |
//If they clicked Cancel, then don't navigate to the next route | |
if (!leave) { | |
MetacatUI.uiRouter.undoLastRoute(); | |
return; | |
} | |
} | |
} | |
// need reference to the old/current view for the callback method | |
var oldView = this.currentView; | |
this.currentView.$el.fadeOut("slow", function () { | |
// clean up old view | |
if (oldView.onClose) oldView.onClose(); | |
//If the view to show is not the same as the main content element, then put it inside the content element. | |
if (view.el !== thisAppViewRef.getContentEl()) { | |
thisAppViewRef.getContentEl().replaceChildren(view.el); | |
$(thisAppViewRef.getContentEl()).show(); | |
} | |
view.$el.fadeIn("slow", function () { | |
// render the new view | |
view.render(viewOptions); | |
// after fade in, do postRender() | |
if (view.postRender) view.postRender(); | |
// force scroll to top if no custom scrolling is implemented | |
else thisAppViewRef.scrollToTop(); | |
}); | |
}); | |
} else { | |
//If the view to show is not the same as the main content element, then put it inside the content element. | |
if (view.el !== this.getContentEl()) { | |
this.getContentEl().replaceChildren(view.el); | |
} | |
// just show the view without transition | |
view.render(viewOptions); | |
if (view.postRender) view.postRender(); | |
// force scroll to top if no custom scrolling is implemented | |
else thisAppViewRef.scrollToTop(); | |
} | |
// track the current view | |
this.currentView = view; | |
MetacatUI.analytics?.trackPageView(); | |
this.trigger("appRenderComplete"); | |
}, | |
routeToMetadata: function (e) { | |
e.preventDefault(); | |
//Get the value from the input element | |
var form = $(e.target).attr("form") || null, | |
val = this.$("#" + form) | |
.find("input[type=text]") | |
.val(); | |
//Remove the text from the input | |
this.$("#" + form) | |
.find("input[type=text]") | |
.val(""); | |
if (!val) return false; | |
MetacatUI.uiRouter.navigate("view/" + val, { trigger: true }); | |
}, | |
routeToMetadataOnEnter: function (e) { | |
//If the user pressed a key inside a text input, we only want to proceed if it was the Enter key | |
if (e.type == "keypress" && e.keycode != 13) return; | |
else this.routeToMetadata(e); | |
}, | |
sendToLogin: function (e) { | |
if (e) e.preventDefault(); | |
var url = $(e.target).attr("href"); | |
url = url.substring(0, url.indexOf("target=") + 7); | |
url += window.location.href; | |
window.location.href = url; | |
}, | |
resetSearch: function () { | |
// Clear the search and map model to start a fresh search | |
MetacatUI.appSearchModel.clear(); | |
MetacatUI.appSearchModel.set(MetacatUI.appSearchModel.defaults()); | |
MetacatUI.mapModel.clear(); | |
MetacatUI.mapModel.set(MetacatUI.mapModel.defaults()); | |
//Clear the search history | |
MetacatUI.appModel.set("searchHistory", new Array()); | |
MetacatUI.uiRouter.navigate("data", { trigger: true }); | |
}, | |
closePopovers: function (e) { | |
if (this.currentView && this.currentView.closePopovers) | |
this.currentView.closePopovers(e); | |
}, | |
toggleSlide: function (e) { | |
if (e) e.preventDefault(); | |
else return false; | |
var clickedOn = $(e.target), | |
toggleElId = | |
clickedOn.attr("data-slide-el") || | |
clickedOn.parents("[data-slide-el]").attr("data-slide-el"), | |
toggleEl = $("#" + toggleElId); | |
toggleEl.slideToggle("fast", function () { | |
//Toggle the display of the link if it has the right class | |
if (clickedOn.is(".toggle-display-on-slide")) { | |
clickedOn.siblings(".toggle-display-on-slide").toggle(); | |
clickedOn.toggle(); | |
} | |
}); | |
}, | |
/** | |
* Displays the given message to the user in a Bootstrap "alert" style. | |
* @param {object} options A literal object of options for the alert message. | |
* @property {string|Element} options.message A message string or HTML Element to display | |
* @property {string} [options.classes] A string of HTML classes to set on the alert | |
* @property {string|Element} [options.container] The container to show the alert in | |
* @property {boolean} [options.replaceContents] If true, the alert will replace the contents of the container element. | |
* If false, the alert will be prepended to the container element. | |
* @property {boolean|number} [options.delay] Set to true or specify a number of milliseconds to display the alert temporarily | |
* @property {boolean} [options.remove] If true, the user will be able to remove the alert with a "close" icon. | |
* @property {boolean} [options.includeEmail] If true, the alert will include a link to the {@link AppConfig#emailContact} | |
* @property {string} [options.emailBody] Specify an email body to use in the email link. | |
* @returns {Element} The alert element | |
*/ | |
showAlert: function () { | |
if (arguments.length > 1) { | |
var options = { | |
message: arguments[0], | |
classes: arguments[1], | |
container: arguments[2], | |
delay: arguments[3], | |
}; | |
if (typeof arguments[4] == "object") { | |
options = _.extend(options, arguments[4]); | |
} | |
} else { | |
var options = arguments[0]; | |
} | |
if (typeof options != "object" || !options) { | |
return; | |
} | |
if (!options.classes) options.classes = "alert-success"; | |
if (!options.container || !$(options.container).length) | |
options.container = this.$el; | |
//Remove any alerts that are already in this container | |
if ($(options.container).children(".alert-container").length > 0) | |
$(options.container).children(".alert-container").remove(); | |
//Allow messages to be HTML or strings | |
if (typeof options.message != "string") | |
options.message = $(document.createElement("div")) | |
.append($(options.message)) | |
.html(); | |
var emailOptions = ""; | |
//Check for more options | |
if (options.emailBody) emailOptions += "?body=" + options.emailBody; | |
var alert = $.parseHTML( | |
this.alertTemplate({ | |
msg: options.message, | |
classes: options.classes, | |
emailOptions: emailOptions, | |
remove: options.remove || false, | |
includeEmail: options.includeEmail, | |
}).trim(), | |
); | |
if (options.delay) { | |
$(alert).hide(); | |
if (options.replaceContents) { | |
$(options.container).html(alert); | |
} else { | |
$(options.container).prepend(alert); | |
} | |
$(alert) | |
.show() | |
.delay(typeof options.delay == "number" ? options.delay : 3000) | |
.fadeOut(); | |
} else { | |
if (options.replaceContents) { | |
$(options.container).html(alert); | |
} else { | |
$(options.container).prepend(alert); | |
} | |
} | |
return alert; | |
}, | |
/** | |
* Previous to MetacatUI 2.14.0, the {@link AppView#showAlert} function allowed up to five parameters | |
* to customize the alert message. As of 2.14.0, the function has condensed these options into | |
* a single literal object. See the docs for {@link AppView#showAlert}. The old signature of five | |
* parameters may soon be deprecated completely, but is still supported. | |
* @deprecated | |
* @param {string|Element} msg | |
* @param {string} [classes] | |
* @param {string|Element} [container] | |
* @param {boolean} [delay] | |
* @param {object} [options] | |
* @param {boolean} [options.includeEmail] If true, the alert will include a link to the {@link AppConfig#emailContact} | |
* @param {string} [options.emailBody] | |
* @param {boolean} [options.remove] | |
* @param {boolean} [options.replaceContents] | |
*/ | |
showAlert_deprecated: function ( | |
msg, | |
classes, | |
container, | |
delay, | |
options, | |
) {}, | |
/** | |
* Listens to the focus event on the window to detect when a user switches back to this browser tab from somewhere else | |
* When a user checks back, we want to check for log-in status | |
*/ | |
listenForActivity: function () { | |
MetacatUI.appUserModel.on("change:loggedIn", function () { | |
if (!MetacatUI.appUserModel.get("loggedIn")) return; | |
//When the user re-focuses back on the window | |
$(window).focus(function () { | |
//If the user has logged out in the meantime, then exit | |
if (!MetacatUI.appUserModel.get("loggedIn")) return; | |
//If the expiration date of the token has passed, then allow the user to sign back in | |
if (MetacatUI.appUserModel.get("expires") <= new Date()) { | |
MetacatUI.appView.showTimeoutSignIn(); | |
} | |
}); | |
}); | |
}, | |
/** | |
* Will determine the length of time until the user's current token expires, | |
* and will set a window timeout for that length of time. When the timeout | |
* is triggered, the sign in modal window will be displayed so that the user | |
* can sign in again (which happens in AppView.showTimeoutSignIn()) | |
*/ | |
listenForTimeout: function () { | |
//Only proceed if the user is logged in | |
if (!MetacatUI.appUserModel.get("checked")) { | |
//When the user logged back in, listen again for the next timeout | |
this.listenToOnce( | |
MetacatUI.appUserModel, | |
"change:checked", | |
function () { | |
//If the user is logged in, then listen call this function again | |
if ( | |
MetacatUI.appUserModel.get("checked") && | |
MetacatUI.appUserModel.get("loggedIn") | |
) | |
this.listenForTimeout(); | |
}, | |
); | |
return; | |
} else if (!MetacatUI.appUserModel.get("loggedIn")) { | |
//When the user logged back in, listen again for the next timeout | |
this.listenToOnce( | |
MetacatUI.appUserModel, | |
"change:loggedIn", | |
function () { | |
//If the user is logged in, then listen call this function again | |
if ( | |
MetacatUI.appUserModel.get("checked") && | |
MetacatUI.appUserModel.get("loggedIn") | |
) | |
this.listenForTimeout(); | |
}, | |
); | |
return; | |
} | |
var view = this, | |
expires = MetacatUI.appUserModel.get("expires"), | |
timeLeft = expires - new Date(); | |
//If there is no time left until expiration, then show the sign in view now | |
if (timeLeft < 0) { | |
this.showTimeoutSignIn(); | |
} | |
//Otherwise, set a timeout for a expiration time, then show the Sign In View | |
else { | |
var timeoutId = setTimeout(function () { | |
view.showTimeoutSignIn.call(view); | |
}, timeLeft); | |
//Save the timeout id in case we want to destroy the timeout later | |
MetacatUI.appUserModel.set("timeoutId", timeoutId); | |
} | |
}, | |
/** | |
* If the user's auth token has expired, a new SignInView model window is | |
* displayed so the user can sign back in. A listener is set on the appUserModel | |
* so that when they do successfully sign back in, we set another timeout listener | |
* via AppView.listenForTimeout() | |
*/ | |
showTimeoutSignIn: function () { | |
if (MetacatUI.appUserModel.get("expires") <= new Date()) { | |
MetacatUI.appUserModel.set("loggedIn", false); | |
var signInView = new SignInView({ | |
inPlace: true, | |
closeButtons: false, | |
topMessage: | |
"Your session has timed out. Click Sign In to open a " + | |
"new window to sign in again. Make sure your browser settings allow pop-ups.", | |
}); | |
var signInForm = signInView.render().el; | |
if (this.subviews && Array.isArray(this.subviews)) | |
this.subviews.push(signInView); | |
else this.subviews = [signInView]; | |
$("body").append(signInForm); | |
$(signInForm).modal(); | |
//When the user logged back in, listen again for the next timeout | |
this.listenToOnce( | |
MetacatUI.appUserModel, | |
"change:checked", | |
function () { | |
if ( | |
MetacatUI.appUserModel.get("checked") && | |
MetacatUI.appUserModel.get("loggedIn") | |
) | |
this.listenForTimeout(); | |
}, | |
); | |
} | |
}, | |
openChatWithMessage: function () { | |
if (!_slaask) return; | |
$("#slaask-input").val(MetacatUI.appModel.get("defaultSupportMessage")); | |
$("#slaask-button").trigger("click"); | |
}, | |
initializeWidgets: function () { | |
// Autocomplete widget extension to provide description tooltips. | |
$.widget("app.hoverAutocomplete", $.ui.autocomplete, { | |
// Set the content attribute as the "item.desc" value. | |
// This becomes the tooltip content. | |
_renderItem: function (ul, item) { | |
// if we have a label, use it for the title | |
var title = item.value; | |
if (item.label) { | |
title = item.label; | |
} | |
// if we have a description, use it for the content | |
var content = item.value; | |
if (item.desc) { | |
content = item.desc; | |
if (item.desc != item.value) { | |
content += " (" + item.value + ")"; | |
} | |
} | |
var element = this._super(ul, item) | |
.attr("data-title", title) | |
.attr("data-content", content); | |
element.popover({ | |
placement: "right", | |
trigger: "hover", | |
container: "body", | |
}); | |
return element; | |
}, | |
}); | |
}, | |
/** | |
* Checks if the user's browser is an outdated version that won't work with | |
* MetacatUI well, and displays a warning message to the user.. | |
* The user agent is checked against the `unsupportedBrowsers` list in the AppModel. | |
*/ | |
checkIncompatibility: function () { | |
//Check if this browser is incompatible with this app. i.e. It is an old browser version | |
var isUnsupportedBrowser = _.some( | |
MetacatUI.appModel.get("unsupportedBrowsers"), | |
function (browserRegEx) { | |
var matches = navigator.userAgent.match(browserRegEx); | |
return matches && matches.length > 0; | |
}, | |
); | |
if (!isUnsupportedBrowser) { | |
return; | |
} else { | |
//Show a warning message to the user about their browser. | |
this.showAlert( | |
"Your web browser is out of date. Update your browser for more security, " + | |
"speed and the best experience on this site.", | |
"alert-warning", | |
this.$el, | |
false, | |
{ remove: true }, | |
); | |
this.$el | |
.children(".alert-container") | |
.addClass("important-app-message"); | |
} | |
}, | |
/** | |
* Shows a temporary message at the top of the view | |
*/ | |
showTemporaryMessage: function () { | |
try { | |
//Is there a temporary message to display throughout the app? | |
if (MetacatUI.appModel.get("temporaryMessage")) { | |
var startTime = MetacatUI.appModel.get("temporaryMessageStartTime"), | |
endTime = MetacatUI.appModel.get("temporaryMessageEndTime"), | |
today = new Date(), | |
isDisplayed = false; | |
//Find cases where we should display the message | |
//If there is a date range and today is in the range | |
if (startTime && endTime && today > startTime && today < endTime) { | |
isDisplayed = true; | |
} | |
//If there's just a start time and today is after it | |
else if (startTime && !endTime && today > startTime) { | |
isDisplayed = true; | |
} | |
//If there's just an end time and today is before it | |
else if (!startTime && endTime && today < endTime) { | |
isDisplayed = true; | |
} | |
//If there's no start or end time | |
else if (!startTime && !endTime) { | |
isDisplayed = true; | |
} | |
if (isDisplayed) { | |
require(["text!templates/alert.html"], function (alertTemplate) { | |
//Get classes for the message | |
var classes = | |
MetacatUI.appModel.get("temporaryMessageClasses") || ""; | |
classes += " temporary-message"; | |
var container = | |
MetacatUI.appModel.get("temporaryMessageContainer") || | |
"#Navbar"; | |
//If the message exists already, return | |
if ($(container + " .temporary-message").length) { | |
return; | |
} | |
//Insert the message using the Alert template | |
$(container).prepend( | |
_.template(alertTemplate)({ | |
classes: classes, | |
msg: MetacatUI.appModel.get("temporaryMessage"), | |
includeEmail: MetacatUI.appModel.get( | |
"temporaryMessageIncludeEmail", | |
), | |
remove: true, | |
}), | |
); | |
//Add a class to the body in case we need to adjust other elements on the page | |
$("body").addClass("has-temporary-message"); | |
}); | |
} | |
} | |
} catch (e) { | |
console.error("Couldn't display the temporary message: ", e); | |
} | |
}, | |
/** | |
* Hides the temporary message | |
*/ | |
hideTemporaryMessage: function () { | |
try { | |
this.$(".temporary-message").remove(); | |
$("body").removeClass("has-temporary-message"); | |
} catch (e) { | |
console.error("Couldn't hide the temporary message: ", e); | |
} | |
}, | |
/********************** Utilities ********************************/ | |
// Various utility functions to use across the app // | |
/************ Function to add commas to large numbers ************/ | |
commaSeparateNumber: function (val) { | |
if (!val) return 0; | |
if (val < 1) return Math.round(val * 100) / 100; | |
while (/(\d+)(\d{3})/.test(val.toString())) { | |
val = val.toString().replace(/(\d+)(\d{3})/, "$1" + "," + "$2"); | |
} | |
return val; | |
}, | |
numberAbbreviator: function (number, decimalPlaces) { | |
if (number === 0) { | |
return 0; | |
} | |
decimalPlaces = Math.pow(10, decimalPlaces); | |
var abbreviations = ["K", "M", "B", "T"]; | |
// Go through the array backwards, so we do the largest first | |
for (var i = abbreviations.length - 1; i >= 0; i--) { | |
// Convert array index to "1000", "1000000", etc | |
var size = Math.pow(10, (i + 1) * 3); | |
// If the number is bigger or equal do the abbreviation | |
if (size <= number) { | |
// Here, we multiply by decimalPlaces, round, and then divide by decimalPlaces. | |
// This gives us nice rounding to a particular decimal place. | |
number = | |
Math.round((number * decimalPlaces) / size) / decimalPlaces; | |
// Handle special case where we round up to the next abbreviation | |
if (number == 1000 && i < abbreviations.length - 1) { | |
number = 1; | |
i++; | |
} | |
// Add the letter for the abbreviation | |
number += abbreviations[i]; | |
break; | |
} | |
} | |
return number; | |
}, | |
higlightInput: function (e) { | |
if (!e) return; | |
e.preventDefault(); | |
e.target.setSelectionRange(0, 9999); | |
}, | |
widenInput: function (e) { | |
$(e.target).css("width", "200px"); | |
}, | |
narrowInput: function (e) { | |
$(e.target).delay(500).animate({ width: "60px" }); | |
}, | |
// scroll to top of page | |
scrollToTop: function () { | |
$("body,html") | |
.stop(true, true) //stop first for it to work in FF | |
.animate({ scrollTop: 0 }, "slow"); | |
return false; | |
}, | |
scrollTo: function (pageElement, offsetTop) { | |
//Find the header height if it is a fixed element | |
var headerOffset = | |
this.$("#Header").css("position") == "fixed" | |
? this.$("#Header").outerHeight() | |
: 0; | |
var navOffset = | |
this.$("#Navbar").css("position") == "fixed" | |
? this.$("#Navbar").outerHeight() | |
: 0; | |
var totalOffset = headerOffset + navOffset; | |
$("body,html") | |
.stop(true, true) //stop first for it to work in FF | |
.animate( | |
{ scrollTop: $(pageElement).offset().top - 40 - totalOffset }, | |
1000, | |
); | |
return false; | |
}, | |
}, | |
); |
🚫 [eslint] <object-shorthand> reported by reviewdog 🐶
Expected method shorthand.
metacatui/src/js/views/AppView.js
Lines 141 to 203 in b0aa7ab
render: function () { | |
//If there is no AppView element on the page, don't render the application. | |
if (!this.el) { | |
console.error( | |
"Not rendering the UI of the app since the AppView HTML element (AppView.el) does not exist on the page. Make sure you have the AppView element included in index.html", | |
); | |
return; | |
} | |
// set up the head | |
$("head").append( | |
this.appHeadTemplate({ | |
theme: MetacatUI.theme, | |
}), | |
); | |
// Add schema.org JSON-LD to the head | |
this.schemaOrg = new SchemaOrgView(); | |
this.schemaOrg.render(); | |
this.schemaOrg.setSchemaFromTemplate(); | |
// set up the body | |
this.$el.append(this.template()); | |
/** | |
* @name MetacatUI.navbarView | |
* @type NavbarView | |
* @description The view that displays a navigation menu on every MetacatUI page and controls the navigation between pages in MetacatUI. | |
*/ | |
MetacatUI.navbarView = new NavbarView(); | |
MetacatUI.navbarView.setElement($("#Navbar")).render(); | |
/** | |
* @name MetacatUI.altHeaderView | |
* @type AltHeaderView | |
* @description The view that displays a header on every MetacatUI view that uses the "AltHeader" header type. | |
* This header is usually for decorative / aesthetic purposes only. | |
*/ | |
MetacatUI.altHeaderView = new AltHeaderView(); | |
MetacatUI.altHeaderView.setElement($("#HeaderContainer")).render(); | |
/** | |
* @name MetacatUI.footerView | |
* @type FooterView | |
* @description The view that displays the main footer of the MetacatUI page. | |
* It has informational and navigational links in it and is displayed on every page, except for views that hide it for full-screen display. | |
*/ | |
MetacatUI.footerView = new FooterView(); | |
MetacatUI.footerView.setElement($("#Footer")).render(); | |
this.showTemporaryMessage(); | |
//Load the Slaask chat widget if it is enabled in this theme | |
if (MetacatUI.appModel.get("slaaskKey") && window._slaask) | |
_slaask.init(MetacatUI.appModel.get("slaaskKey")); | |
this.listenForActivity(); | |
this.listenForTimeout(); | |
this.initializeWidgets(); | |
return this; | |
}, |
🚫 [eslint] <prefer-arrow-callback> reported by reviewdog 🐶
Unexpected function expression.
metacatui/src/js/views/search/CatalogSearchView.js
Lines 12 to 846 in b0aa7ab
], function ( | |
$, | |
Backbone, | |
SearchResultsView, | |
FilterGroupsView, | |
MapView, | |
PagerView, | |
SorterView, | |
Template, | |
MapSearchFiltersConnector, | |
CatalogSearchViewCSS, | |
) { | |
"use strict"; | |
/** | |
* @class CatalogSearchView | |
* @classdesc The data catalog search view for the repository. This view | |
* displays a Cesium map, search results, and search filters. | |
* @name CatalogSearchView | |
* @classcategory Views | |
* @extends Backbone.View | |
* @constructor | |
* @since 2.22.0 | |
* @screenshot views/search/CatalogSearchView.png | |
*/ | |
return Backbone.View.extend( | |
/** @lends CatalogSearchView.prototype */ { | |
/** | |
* The type of View this is | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
type: "CatalogSearch", | |
/** | |
* The HTML tag to use for this view's element | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
tagName: "section", | |
/** | |
* The HTML classes to use for this view's element | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
className: "catalog", | |
/** | |
* The template to use for this view's element | |
* @type {underscore.template} | |
* @since 2.22.0 | |
*/ | |
template: _.template(Template), | |
/** | |
* The template to use in case there is a major error in rendering the | |
* view. | |
* @type {string} | |
* @since 2.25.0 | |
*/ | |
errorTemplate: `<div class="error" role="alert"> | |
<h2>There was an error loading the search results.</h2> | |
<p>Please try again later.</p> | |
</div>`, | |
/** | |
* Whether the map is displayed or hidden. | |
* @type boolean | |
* @since 2.25.0 | |
* @default true | |
*/ | |
mapVisible: true, | |
/** | |
* Whether the filters are displayed or hidden. | |
* @type boolean | |
* @since 2.25.0 | |
* @default true | |
*/ | |
filtersVisible: true, | |
/** | |
* Whether to limit the search to the extent of the map. When true, the | |
* search will update when the user pans or zooms the map. This property | |
* will be updated when the user clicks the map filter toggle. Whatever is | |
* set during the initial render will be the default. | |
* @type {boolean} | |
* @since 2.25.0 | |
* @default false | |
*/ | |
limitSearchToMapArea: false, | |
/** | |
* Whether to limit the search to the extent the first time the user | |
* interacts with the map. This only applies if limitSearchToMapArea is | |
* initially set to false. | |
* @type {boolean} | |
* @since 2.26.0 | |
* @default true | |
*/ | |
limitSearchToMapOnInteraction: true, | |
/** | |
* The View that displays the search results. The render method will be | |
* attach the search results view to the | |
* {@link CatalogSearchView#searchResultsContainer} element and will add | |
* the view reference to this property. | |
* @type {SearchResultsView} | |
* @since 2.22.0 | |
*/ | |
searchResultsView: null, | |
/** | |
* The view that shows the search filters. The render method will attach | |
* the filter groups view to the | |
* {@link CatalogSearchView#filterGroupsContainer} element and will add | |
* the view reference to this property. | |
* @type {FilterGroupsView} | |
* @since 2.22.0 | |
*/ | |
filterGroupsView: null, | |
/** | |
* The view that shows the number of pages and allows the user to navigate | |
* between them. The render method will attach the pager view to the | |
* {@link CatalogSearchView#pagerContainer} element and will add the view | |
* reference to this property. | |
* @type {PagerView} | |
* @since 2.22.0 | |
*/ | |
pagerView: null, | |
/** | |
* The view that handles sorting the search results. The render method | |
* will attach the sorter view to the | |
* {@link CatalogSearchView#sorterContainer} element and will add the view | |
* reference to this property. | |
* @type {SorterView} | |
* @since 2.22.0 | |
*/ | |
sorterView: null, | |
/** | |
* The CSS class to add to the body element when this view is rendered. | |
* @type {string} | |
* @since 2.22.0 | |
* @default "catalog-search-body", | |
*/ | |
bodyClass: "catalog-search-body", | |
/** | |
* The jQuery selector for the FilterGroupsView container | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
filterGroupsContainer: ".catalog__filters", | |
/** | |
* The query selector for the SearchResultsView container | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
searchResultsContainer: ".catalog__results-list", | |
/** | |
* The query selector for the CesiumWidgetView container | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
mapContainer: ".catalog__map", | |
/** | |
* The query selector for the PagerView container | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
pagerContainer: ".catalog__pager", | |
/** | |
* The query selector for the SorterView container | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
sorterContainer: ".catalog__sorter", | |
/** | |
* The query selector for the title container | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
titleContainer: ".catalog__summary", | |
/** | |
* The query selector for button that is used to either show or hide the | |
* map. | |
* @type {string} | |
* @since 2.22.0 | |
*/ | |
toggleMapButton: ".catalog__map-toggle", | |
/** | |
* The query selector for the label that is used to describe the | |
* {@link CatalogSearchView#toggleMapButton}. | |
* @type {string} | |
* @since 2.25.0 | |
* @default "#toggle-map-label" | |
*/ | |
toggleMapLabel: "#toggle-map-label", | |
/** | |
* The query selector for the button that is used to either show or hide | |
* the filters. | |
* @type {string} | |
* @since 2.25.0 | |
*/ | |
toggleFiltersButton: ".catalog__filters-toggle", | |
/** | |
* The query selector for the label that is used to describe the | |
* {@link CatalogSearchView#toggleFiltersButton}. | |
* @type {string} | |
* @since 2.25.0 | |
* @default "#toggle-map-label" | |
*/ | |
toggleFiltersLabel: "#toggle-filters-label", | |
/** | |
* The query selector for the button that is used to turn on or off | |
* spatial filtering by map extent. | |
* @type {string} | |
* @since 2.25.0 | |
*/ | |
mapFilterToggle: ".catalog__map-filter-toggle", | |
/** | |
* The CSS class (not selector) to add to the body element when the map is | |
* hidden. | |
* @type {string} | |
* @since 2.25.0 | |
*/ | |
hideMapClass: "catalog--map-hidden", | |
/** | |
* The CSS class (not selector) to add to the body element when the | |
* filters are hidden. | |
* @type {string} | |
* @since 2.25.0 | |
*/ | |
hideFiltersClass: "catalog--filters-hidden", | |
/** | |
* The events this view will listen to and the associated function to | |
* call. | |
* @type {Object} | |
* @since 2.22.0 | |
*/ | |
events: function () { | |
const e = {}; | |
e[`click ${this.mapFilterToggle}`] = "toggleMapFilter"; | |
e[`click ${this.toggleMapButton}`] = "toggleMapVisibility"; | |
e[`click ${this.toggleFiltersButton}`] = "toggleFiltersVisibility"; | |
return e; | |
}, | |
/** | |
* Initialize the view. In addition to the options described below, any | |
* option that is available in the | |
* {@link MapSearchFiltersConnector#initialize} method can be passed to | |
* this view, such as Map, SolrResult, and FilterGroup models, and whether | |
* to create a geohash layer or spatial filter if they are not present. | |
* @param {Object} options - The options for this view. | |
* @param {string} [options.initialQuery] - The initial text query to run | |
* when the view is rendered. | |
* @param {MapSearchFiltersConnector} [options.model] - A | |
* MapSearchFiltersConnector model to use for this view. If not provided, | |
* a new one will be created. If one is provided, then other options that | |
* would be passed to the MapSearchFiltersConnector model will be ignored | |
* (such as map, searchResults, filterGroups, catalogSearch, etc.) | |
* @since 2.25.0 | |
*/ | |
initialize: function (options) { | |
this.cssID = "catalogSearchView"; | |
MetacatUI.appModel.addCSS(CatalogSearchViewCSS, this.cssID); | |
if (!options) options = {}; | |
this.initialQuery = options.initialQuery || null; | |
let model = options.model; | |
if (!model) { | |
const app = MetacatUI.appModel; | |
model = new MapSearchFiltersConnector({ | |
map: options.map || app.get("catalogSearchMapOptions"), | |
searchResults: options.searchResults || null, | |
filterGroups: | |
options.filterGroups || app.get("defaultFilterGroups"), | |
catalogSearch: options.catalogSearch !== false, | |
addGeohashLayer: options.addGeohashLayer !== false, | |
addSpatialFilter: options.addSpatialFilter !== false, | |
}); | |
} | |
this.model = model; | |
this.model.connect(); | |
}, | |
/** | |
* Renders the view | |
* @since 2.22.0 | |
*/ | |
render: function () { | |
// Set the search mode - either map or list | |
this.setMapVisibility(); | |
// Set up the view for styling and layout | |
this.setupView(); | |
// Render the search components | |
this.renderComponents(); | |
// Set up the initial map toggle state | |
this.setMapToggleState(); | |
}, | |
/** | |
* Indicates that there was a problem rendering this view. | |
* @since 2.25.0 | |
*/ | |
renderError: function () { | |
this.$el.html(this.errorTemplate); | |
}, | |
/** | |
* Sets the search mode (map or list) | |
* @since 2.22.0 | |
*/ | |
setMapVisibility: function () { | |
try { | |
if ( | |
typeof this.mapVisible === "undefined" && | |
MetacatUI.appModel.get("enableCesium") | |
) { | |
this.mapVisible = true; | |
} | |
// Use map mode on tablets and browsers only. TODO: should we set a | |
// listener for window resize? | |
if ($(window).outerWidth() <= 600) { | |
this.mapVisible = false; | |
} | |
} catch (e) { | |
console.error( | |
"Error setting the search mode, defaulting to list:" + e, | |
); | |
this.mapVisible = false; | |
} | |
this.toggleMapVisibility(this.mapVisible); | |
}, | |
/** | |
* Sets the initial state of the map filter toggle. Optionally listens | |
* for the first user interaction with the map before turning on the | |
* spatial filter. | |
* @since 2.26.0 | |
*/ | |
setMapToggleState: function () { | |
// Set the initial state of the spatial filter | |
this.toggleMapFilter(this.limitSearchToMapArea); | |
if (this.limitSearchToMapOnInteraction && !this.limitSearchToMapArea) { | |
this.listenToOnce( | |
this.model.get("map").get("interactions"), | |
"change:firstInteraction", | |
function () { | |
this.toggleMapFilter(true); | |
}, | |
); | |
} | |
}, | |
/** | |
* Sets up the basic components of this view | |
* @since 2.22.0 | |
*/ | |
setupView: function () { | |
try { | |
// The body class modifies the entire page layout to accommodate the | |
// catalog search view | |
if (!this.isSubView) { | |
MetacatUI.appModel.set("headerType", "default"); | |
document.querySelector("body").classList.add(this.bodyClass); | |
} else { | |
// TODO: Set up styling for sub-view version of the catalog | |
} | |
// Add LinkedData to the page | |
MetacatUI.appView.schemaOrg.setSchema("DataCatalog"); | |
// Render the template | |
this.$el.html( | |
this.template({ | |
mapFilterOn: this.limitSearchToMapArea === true, | |
}), | |
); | |
} catch (e) { | |
console.log( | |
"There was an error setting up the CatalogSearchView:" + e, | |
); | |
this.renderError(); | |
} | |
}, | |
/** | |
* Calls other methods that insert the sub-views into the DOM and render | |
* them. | |
* @since 2.22.0 | |
*/ | |
renderComponents: function () { | |
try { | |
this.createSearchResults(); | |
this.createMap(); | |
this.renderFilters(); | |
// Render the list of search results | |
this.renderSearchResults(); | |
// Render the Title | |
this.renderTitle(); | |
this.listenTo( | |
this.model.get("searchResults"), | |
"reset", | |
this.renderTitle, | |
); | |
// Render Pager | |
this.renderPager(); | |
// Render Sorter | |
this.renderSorter(); | |
// Render Cesium | |
this.renderMap(); | |
} catch (e) { | |
console.log( | |
"There was an error rendering the CatalogSearchView:" + e, | |
); | |
this.renderError(); | |
} | |
}, | |
/** | |
* Renders the search filters | |
* @since 2.22.0 | |
*/ | |
renderFilters: function () { | |
try { | |
// Render FilterGroups | |
this.filterGroupsView = new FilterGroupsView({ | |
filterGroups: this.model.get("filterGroups"), | |
filters: this.model.get("filters"), | |
vertical: true, | |
parentView: this, | |
initialQuery: this.initialQuery, | |
collapsible: true, | |
}); | |
// Add the FilterGroupsView element to this view | |
this.$(this.filterGroupsContainer).html(this.filterGroupsView.el); | |
// Render the FilterGroupsView | |
this.filterGroupsView.render(); | |
} catch (e) { | |
console.log("There was an error rendering the FilterGroupsView:" + e); | |
} | |
}, | |
/** | |
* Creates the SearchResultsView and saves a reference to the SolrResults | |
* collection | |
* @since 2.22.0 | |
*/ | |
createSearchResults: function () { | |
try { | |
this.searchResultsView = new SearchResultsView(); | |
this.searchResultsView.searchResults = | |
this.model.get("searchResults"); | |
} catch (e) { | |
console.log("There was an error creating the SearchResultsView:" + e); | |
} | |
}, | |
/** | |
* Renders the search result list | |
* @since 2.22.0 | |
*/ | |
renderSearchResults: function () { | |
try { | |
if (!this.searchResultsView) return; | |
// Add the view element to this view | |
this.$(this.searchResultsContainer).html(this.searchResultsView.el); | |
// Render the view | |
this.searchResultsView.render(); | |
} catch (e) { | |
console.log( | |
"There was an error rendering the SearchResultsView:" + e, | |
); | |
} | |
}, | |
/** | |
* Creates a PagerView and adds it to the page. | |
* @since 2.22.0 | |
*/ | |
renderPager: function () { | |
try { | |
this.pagerView = new PagerView(); | |
// Give the PagerView the SearchResults to listen to and update | |
this.pagerView.searchResults = this.model.get("searchResults"); | |
// Add the pager view to the page | |
this.el | |
.querySelector(this.pagerContainer) | |
.replaceChildren(this.pagerView.el); | |
// Render the pager view | |
this.pagerView.render(); | |
} catch (e) { | |
console.log("There was an error rendering the PagerView:" + e); | |
} | |
}, | |
/** | |
* Creates a SorterView and adds it to the page. | |
* @since 2.22.0 | |
*/ | |
renderSorter: function () { | |
try { | |
this.sorterView = new SorterView(); | |
// Give the SorterView the SearchResults to listen to and update | |
this.sorterView.searchResults = this.model.get("searchResults"); | |
// Add the sorter view to the page | |
this.el | |
.querySelector(this.sorterContainer) | |
.replaceChildren(this.sorterView.el); | |
// Render the sorter view | |
this.sorterView.render(); | |
} catch (e) { | |
console.log("There was an error rendering the SorterView:" + e); | |
} | |
}, | |
/** | |
* Constructs an HTML string of the title of this view | |
* @param {number} start | |
* @param {number} end | |
* @param {number} numFound | |
* @returns {string} | |
* @since 2.22.0 | |
*/ | |
titleTemplate: function (start, end, numFound) { | |
try { | |
let content = ""; | |
const csn = MetacatUI.appView.commaSeparateNumber; | |
if (numFound < end) end = numFound; | |
if (numFound > 0) { | |
content = `<span>${csn(start)}</span> to <span>${csn(end)}</span>`; | |
if (typeof numFound == "number") { | |
content += ` of <span>${csn(numFound)}</span>`; | |
} | |
} | |
return ` | |
<div id="statcounts"> | |
<h5 class="result-header-count bold-header" id="countstats"> | |
${content} | |
</h5> | |
</div>`; | |
} catch (e) { | |
console.log("There was an error creating the title template:" + e); | |
return ""; | |
} | |
}, | |
/** | |
* Updates the view title using the | |
* {@link CatalogSearchView#searchResults} data. | |
* @since 2.22.0 | |
*/ | |
renderTitle: function () { | |
try { | |
const searchResults = this.model.get("searchResults"); | |
let titleEl = this.el.querySelector(this.titleContainer); | |
if (!titleEl) { | |
titleEl = document.createElement("div"); | |
titleEl.classList.add("title-container"); | |
this.el.prepend(titleEl); | |
} | |
titleEl.innerHTML = ""; | |
let title = this.titleTemplate( | |
searchResults.getStart() + 1, | |
searchResults.getEnd() + 1, | |
searchResults.getNumFound(), | |
); | |
titleEl.insertAdjacentHTML("beforeend", title); | |
} catch (e) { | |
console.log("There was an error rendering the title:" + e); | |
} | |
}, | |
/** | |
* Create the models and views associated with the map and map search | |
* @since 2.22.0 | |
*/ | |
createMap: function () { | |
try { | |
this.mapView = new MapView({ model: this.model.get("map") }); | |
} catch (e) { | |
console.error("Couldn't create map in search. ", e); | |
this.toggleMapVisibility(false); | |
} | |
}, | |
/** | |
* Renders the Cesium map with a geohash layer | |
* @since 2.22.0 | |
*/ | |
renderMap: function () { | |
try { | |
// Add the map to the page and render it | |
this.$(this.mapContainer).append(this.mapView.el); | |
this.mapView.render(); | |
} catch (e) { | |
console.error("Couldn't render map in search. ", e); | |
this.toggleMapVisibility(false); | |
} | |
}, | |
/** | |
* Shows or hide the filters | |
* @param {boolean} show - Optionally provide the desired choice of | |
* whether the filters should be shown (true) or hidden (false). If not | |
* provided, the opposite of the current mode will be used. | |
* @since 2.25.0 | |
*/ | |
toggleFiltersVisibility: function (show) { | |
try { | |
const classList = document.querySelector("body").classList; | |
// If the new mode is not provided, the new mode is the opposite of | |
// the current mode | |
show = typeof show == "boolean" ? show : !this.filtersVisible; | |
const hideFiltersClass = this.hideFiltersClass; | |
if (show) { | |
this.filtersVisible = true; | |
classList.remove(hideFiltersClass); | |
} else { | |
this.filtersVisible = false; | |
classList.add(hideFiltersClass); | |
} | |
this.updateToggleFiltersLabel(); | |
} catch (e) { | |
console.error("Couldn't toggle filter visibility. ", e); | |
} | |
}, | |
/** | |
* Show or hide the map | |
* @param {boolean} show - Optionally provide the desired choice of | |
* whether the filters should be shown (true) or hidden (false). If not | |
* provided, the opposite of the current mode will be used. (Set to true | |
* to show map, false to hide it.) | |
* @since 2.25.0 | |
*/ | |
toggleMapVisibility: function (show) { | |
try { | |
// If the new mode is not provided, the new mode is the opposite of | |
// the current mode | |
show = typeof show == "boolean" ? show : !this.mapVisible; | |
const classList = document.querySelector("body").classList; | |
const hideMapClass = this.hideMapClass; | |
if (show) { | |
this.mapVisible = true; | |
classList.remove(hideMapClass); | |
} else { | |
this.mapVisible = false; | |
classList.add(hideMapClass); | |
} | |
this.updateToggleMapLabel(); | |
} catch (e) { | |
console.error("Couldn't toggle search mode. ", e); | |
} | |
}, | |
/** | |
* Change the content of the map toggle label to indicate whether | |
* clicking the button will show or hide the map. | |
* @since 2.25.0 | |
*/ | |
updateToggleMapLabel: function () { | |
try { | |
const toggleMapLabel = this.el.querySelector(this.toggleMapLabel); | |
const toggleMapButton = this.el.querySelector(this.toggleMapButton); | |
if (this.mapVisible) { | |
if (toggleMapLabel) { | |
toggleMapLabel.innerHTML = | |
'Hide Map <i class="icon icon-angle-right"></i>'; | |
} | |
if (toggleMapButton) { | |
toggleMapButton.innerHTML = | |
'<i class="icon icon-double-angle-right"></i>'; | |
} | |
} else { | |
if (toggleMapLabel) { | |
toggleMapLabel.innerHTML = | |
'<i class="icon icon-globe"></i> Show Map <i class="icon icon-angle-left"></i>'; | |
} | |
if (toggleMapButton) { | |
toggleMapButton.innerHTML = '<i class="icon icon-globe"></i>'; | |
} | |
} | |
} catch (e) { | |
console.log("Couldn't update map toggle. ", e); | |
} | |
}, | |
/** | |
* Change the content of the filters toggle label to indicate whether | |
* clicking the button will show or hide the filters. | |
* @since 2.25.0 | |
*/ | |
updateToggleFiltersLabel: function () { | |
try { | |
const toggleFiltersLabel = this.el.querySelector( | |
this.toggleFiltersLabel, | |
); | |
const toggleFiltersButton = this.el.querySelector( | |
this.toggleFiltersButton, | |
); | |
if (this.filtersVisible) { | |
if (toggleFiltersLabel) { | |
toggleFiltersLabel.innerHTML = | |
'Hide Filters <i class="icon icon-angle-left"></i>'; | |
} | |
if (toggleFiltersButton) { | |
toggleFiltersButton.innerHTML = | |
'<i class="icon icon-double-angle-left"></i>'; | |
} | |
} else { | |
if (toggleFiltersLabel) { | |
toggleFiltersLabel.innerHTML = | |
'<i class="icon icon-filter"></i> Show Filters <i class="icon icon-angle-right"></i>'; | |
} | |
if (toggleFiltersButton) { | |
toggleFiltersButton.innerHTML = | |
'<i class="icon icon-filter"></i>'; | |
} | |
} | |
} catch (e) { | |
console.log("Couldn't update filters toggle. ", e); | |
} | |
}, | |
/** | |
* Toggles the map filter on and off | |
* @param {boolean} newSetting - Optionally provide the desired new mode | |
* to switch to. true = limit search to map area, false = do not limit | |
* search to map area. If not provided, the opposite of the current mode | |
* will be used. | |
* @since 2.25.0 | |
*/ | |
toggleMapFilter: function (newSetting) { | |
// Make sure the new setting is a boolean | |
newSetting = | |
typeof newSetting != "boolean" | |
? !this.limitSearchToMapArea // the opposite of the current mode | |
: newSetting; // the provided new mode if it is a boolean | |
// Select the map filter toggle checkbox so that we can keep it in sync | |
// with the new setting | |
let mapFilterToggle = this.el.querySelector(this.mapFilterToggle); | |
// If it's not a checkbox input, find the child checkbox input | |
if (mapFilterToggle && mapFilterToggle.tagName != "INPUT") { | |
mapFilterToggle = mapFilterToggle.querySelector("input"); | |
} | |
if (newSetting) { | |
// If true, then the filter should be ON | |
this.model.connectFiltersMap(); | |
if (mapFilterToggle) { | |
mapFilterToggle.checked = true; | |
} | |
} else { | |
// If false, then the filter should be OFF | |
this.model.disconnectFiltersMap(true); | |
if (mapFilterToggle) { | |
mapFilterToggle.checked = false; | |
} | |
} | |
this.limitSearchToMapArea = newSetting; | |
}, | |
/** | |
* Tasks to perform when the view is closed | |
* @since 2.22.0 | |
*/ | |
onClose: function () { | |
try { | |
MetacatUI.appModel.removeCSS(this.cssID); | |
document | |
.querySelector("body") | |
.classList.remove(this.bodyClass, this.hideMapClass); | |
// Remove the JSON-LD from the page | |
MetacatUI.appView.schemaOrg.removeExistingJsonldEls(); | |
} catch (e) { | |
console.error("Couldn't close search view. ", e); | |
} | |
}, | |
}, | |
); | |
}); |
🚫 [eslint] <object-shorthand> reported by reviewdog 🐶
Expected method shorthand.
metacatui/src/js/views/search/CatalogSearchView.js
Lines 397 to 423 in b0aa7ab
setupView: function () { | |
try { | |
// The body class modifies the entire page layout to accommodate the | |
// catalog search view | |
if (!this.isSubView) { | |
MetacatUI.appModel.set("headerType", "default"); | |
document.querySelector("body").classList.add(this.bodyClass); | |
} else { | |
// TODO: Set up styling for sub-view version of the catalog | |
} | |
// Add LinkedData to the page | |
MetacatUI.appView.schemaOrg.setSchema("DataCatalog"); | |
// Render the template | |
this.$el.html( | |
this.template({ | |
mapFilterOn: this.limitSearchToMapArea === true, | |
}), | |
); | |
} catch (e) { | |
console.log( | |
"There was an error setting up the CatalogSearchView:" + e, | |
); | |
this.renderError(); | |
} | |
}, |
🚫 [eslint] <object-shorthand> reported by reviewdog 🐶
Expected method shorthand.
metacatui/src/js/views/search/CatalogSearchView.js
Lines 651 to 660 in b0aa7ab
renderMap: function () { | |
try { | |
// Add the map to the page and render it | |
this.$(this.mapContainer).append(this.mapView.el); | |
this.mapView.render(); | |
} catch (e) { | |
console.error("Couldn't render map in search. ", e); | |
this.toggleMapVisibility(false); | |
} | |
}, |
🚫 [eslint] <object-shorthand> reported by reviewdog 🐶
Expected method shorthand.
metacatui/src/js/views/search/CatalogSearchView.js
Lines 831 to 843 in b0aa7ab
onClose: function () { | |
try { | |
MetacatUI.appModel.removeCSS(this.cssID); | |
document | |
.querySelector("body") | |
.classList.remove(this.bodyClass, this.hideMapClass); | |
// Remove the JSON-LD from the page | |
MetacatUI.appView.schemaOrg.removeExistingJsonldEls(); | |
} catch (e) { | |
console.error("Couldn't close search view. ", e); | |
} | |
}, |
The branch is currently deployed at https://metacatui.test.dataone.org/, pointing to the |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Datasets on metacatui.test.dataone.org with both too long and too short abstracts meet the description requirement of between 50 and 5000 characters. Thanks Robyn!
…te-jsonld-descriptions
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
LGTM! Thank you, @robyngit. I remember that this was one of my first feature implementations while getting familiar with MetacatUI, and Bryce and Lauren were helping me figure out how to get this in. It is great to see all the changes and improvements that have come along over the years. Thank you again, Robyn! 🙏🏻🎉
…te-jsonld-descriptions
This PR introduces a new
SchemaOrgView
andSchemaOrg
mode, updates views to use these new components, and removes redundant JSON-LD generation code. With management of JSON-LD centralized, added a check for the length of the description in the Dataset json-ld to adhere to Google's guidelines. It either truncates the description if it's above 5000 characters, or adds some text if the description is less than 50 characters.In working on this, I found a few issues with the current JSON-LD generation that I also fixed in this PR:
isJSONLDEnabled
, when false, now prevents all instances of schema.orgjson-ld from being added in the app; previously it only applied to the Dataset json-ld, which seems to have been an oversight.
}
at the end of the template that was causing a parsing error.Fixes #1899