TSearch JavaScript
TSearch Core Files
There are a number of javascript files associated with TSearch’s core functionality.
tsearch-core.js: Contains the core widget definitions as well as two classes:
TSearchManager: A class that is responsible for the management of widgets and security information. The Permission and Security widgets are also stored as members of the Manager. Also executes searches via the doRequest() method.
ParameterStore: Lives on the manager. The store is used to interact with the search query being used to generate search requests for the view.
tsearch-util.js: As the name suggests, contains a number of utility methods for quickly building UI elements and handling data. We’ll cover the more commonly used functions later.
tsearch-ui.js: Must always be loaded last, as this script is responsible for retrieving the view configuration and parsing it. The TSearchManager is created here and all widgets are initialized in this process.
Common Libraries Used
Base Template
- jquery [1.12.4]
- bootstrap.js
- moment.js
- sweetalert 2
- Font Awesome css libraries
- numeral.js
Simflofy Template
- chart.js
- bootstrap-select.js
- bootstrap-datetimepicker.js
- dropzone.js
- jquery-ui [1.12.1]
RM Template
- treeview.js
JavaScript Context
Context is tricky in javascript. At the beginning of any function built into a widget, set this
equal to the variable self
, so you'll always have access to the context of the whole widget. This will let you access any built-in functions, variables (customFields), or labels.
TSearchManager.doRequest() step by step
Loops through each widget, calling their
beforeRequest(
) method if one exists.Sets the number of rows that will be returned. This value defaults to 10, but can be set by the page sizer.
Call
executeRequest()
, which creates a parameter string by calling theParameterStore.string()
method.The final URL has the following construction:
/search/[connectorId]/[collection if not null]/select
. This is passed as the "req" argument to the TSearch HomeController. This request will take the form of a Solr Query, but this will be changing in the near future.The
handleResponse()
method will then parse the data and store the response and execute the afterRequest() method of each widget. Additionally, the returned documents are stored in a global variable named docArr.
Global Variables and Utility Methods
templateId: the shortName for the current template
viewId: the shortName of the current view
simflofyHost: The url of the tsearch instance.
ugs: A list of user groups that include the current user
usermarks: A list of longs representing the current users Security Marks
secOfficer: Whether the current user has the Security Officer role
rmUser: Whether the current user has the RM User role
rmOfficer: Whether the current user has the RM Officer role
rmManager: Whether the current user has the RM Manager role
capabilities: A map of capabilities for each of the configured Content Service Connections in Simflofy Admin. The key is the connectorId and the value is an array of capabilities. This cache can be refreshed in tsearch/config.
docArr: Array containing an object for each document. Except for the id field, all variables on documents are contained within an array. Ex. simflofy_filename:[“myfile.txt”]
.
Documents have some fields that remain the same.
id: The id of the indexed document. Used for content service calls.
simflofy_connectorid: The content service connection indexed with the documents
isRM: Denotes whether the document has a retention schedule
onHold: Denotes whether the document is on hold
simflofy_filename: The document name
simflofy_content_type: The mimetype of the document
docPermissions: Array of objects. The individual permissions for the document. Used to control which widgets can access it.
securityMarks: An array of longs. Numerical representations of the Security Marks on the document.
Manager - The TSearchManager which contains the following
connectorId: (String) The connectorId of the Search Connection
contentWidgets: (Array) Contains objects representing the instances of each content action widget in the view. Includes widgetId and the instance id.
contentWidgetDefinitions: (Array) Contains objects representing widget definitions not appearing in the view. Used in permission management
collection: (String) The collection on the Search Connection
permissions: The PermissionManagementWidget
security: The SecurityGroupWidget
widgetIds: Key value map of widgetIds and their definitions. So {1:”ResultWidget”,etc}.
widgets: Similar map, except the values are the entire widget instance
roles: (Object) The roles field from the view, containing widget permissions
admins: (Array) Array of admin users
users: (Array) Array of view users
response: (Object) The complete response from the previous search. A Complete response can be found as Appendix A.
isAdmin: (Boolean) Whether the current user has admin privileges. Admins skip permission checks.
hasPermission(doc, widgetId)
- Used in afterRequest() to determine whether the user has access to the widget for a particular document. Compares the users’ principals (username/user groups) with the docPermissions field.
hasCapability(connId, cap)
- Used in afterRequest() to determine whether the content service connection on the document can handle the widget’s functionality.
handleError(err, opname)
- Used as the error function for ajax calls. The first argument is the jqXHR error. The second is the operation attempted. It will attempt to parse the error and present it in a popup.
toggleOverlay()
- Shows or hides the loading overlay
showOverlay(show)
- Shows or hides the overlay depending on the value of show
humanReadable(fileType)
- Converts some common mime types into simple names for easier reading.
TSearch Utilities
All of these methods must be prefixed with TSearch
.
getJSONHeaders()
- Use this when making POST/PUT requests and send a json body. Returns an object
{'Accept': 'application/json','Content-Type': 'application/json' }
getRecordById(recordId)
- Searches docArr for a document whose recordId field equals the supplied value. Returns an object representing the document or undefined if none was found.
getDocById(docId, isRM)
- Searches docArr for a record whose id field equals the supplied value. If isRM is present and true, it will search the recordId.
size(object)
- Returns the number of keys in an object.
equals(object1, object2)
- Compares strings or arrays to see if they are the same.
inArray(value, array)
- Returns the index of the value in the given array, or -1 if not present. Alternatively you can use array.indexOf(a => a === value);
isArray(obj)
- Returns true if the object is an Array
isString(obj)
- Returns true if the object is a String
isNotBlank(str)
- Returns true if the string is not empty or undefined
isBlank(str)
- Inverse of isNotBlank
getDocRow(docId)
- Returns a jquery object whose data-target is equal to the supplied id or undefined.
getDocValue(doc, field)
- Will unpack the request value if it is an array and return it. Will return “false” if the value was not found on the document
getDocValueById(docId,field)
- A combination of getDocById() and getDocValue()
getFileImageUrl(ct)
- Returns the file name of the resource for each file type icon.
capitalize(str)
- Capitalizes the first letter of the string.
sortObj(obj)
- Returns a version of the object with its keys in alphabetical order.
intersection(arr1, arr2, field1, field2)
- Will return a list of objects that appear in arr1 and arr2, based on the fields used to compare
unintersection(arr1, arr2, field1, field2)
- Will return a list of objects from arr1 that don't appear in arr2, based on the fields used to compare
getCheckedDocumentIds()
- Retrieves an array of document ids for documents who have been checked. Returns an empty array if there are no checked documents.
makePanel(id, title)
- simflofy template only. Constructs a collapsible card on the left sidebar
makePanel(id, title)
- simflofy template only. Constructs a collapsible card on the left sidebarid - The id you wish to use for the panel. Appends the body to $('#body'+id)
title - The title for panel header.
addButton(menu, text, modalSelector, id)
- Adds a button to the supplied menu. Usually used for top_menu type widgets
addButton(menu, text, modalSelector, id)
- Adds a button to the supplied menu. Usually used for top_menu type widgetsmenu - The menu where the button will be added. Can be an id, selector or jquery object
text - The button label
modalSelector - (optional) The string selector for a modal (with #) that will open when the button is clicked
id - The id of the button
addBulkAction(text, id, modal)
- Both templates have a dropdown called “bulkDocActions” on the top menu. If no items are appended to it, the button will not appear.
addBulkAction(text, id, modal)
- Both templates have a dropdown called “bulkDocActions” on the top menu. If no items are appended to it, the button will not appear.text - button text
id - the button id
modal - (optional) The string selector for a modal (with #) that will open when the button is clicked
makeDropdown(menu,text,id,items,addClass,prepend)
- Programmatically generates a dropdown and attaches it to a menu
makeDropdown(menu,text,id,items,addClass,prepend)
- Programmatically generates a dropdown and attaches it to a menumenu - The menu where the button will be added. Can be an id, selector or jquery object
text - The button label
id - The id of the dropdown container (not the menu!)
items - If an array, the id and text of the items will be the same. If an object, the keys will be used as ids, and values will be the text
addClass - css class to add to dropdown items
prepend - Whether to append or prepend to menu
addRMTab($nav, $body, id, active, label)
- RM Template Only. This template uses a list of nav tabs and panels from bootstrap.
addRMTab($nav, $body, id, active, label)
- RM Template Only. This template uses a list of nav tabs and panels from bootstrap.$nav - The list of nav tabs. For the RM Template it is $('#rmnavtabs')
$body - The list of tab content. For the RM Template it is $('#rmtabs')
id - The id of the content tab
active - whether the panel is currently active. Conflicts will always leave to the first active tab open
label - The nav tab text
addFormInput($section, type, id, label, columns)
- Currently only used in the RM Template. Will append a form input to the selected section. Note that this just creates the input and does not populate any items or logic.
addFormInput($section, type, id, label, columns)
- Currently only used in the RM Template. Will append a form input to the selected section. Note that this just creates the input and does not populate any items or logic.$section - The jQuery object for the section.
type - text, select, check or date
id - the id of the input. Will be selectable as $(‘#’+ id+’div’);
label - A label for the input
columns - how many columns in boostrap’s grid system to use. If blank, three are used.
jQuery
Object Extensions - Meant to be called on a selected DOM element
findChild(number,type,last)
- Searches for a child of the selected type
findChild(number,type,last)
- Searches for a child of the selected typenumber - the child position, 0 based.
type - the object type
last - (optional) - select the last child
invisible()
- Turns visibility on an item to “hidden”
visible()
- Turns visibility on an item to “visible”
disable()
- Sets the disabled attribute and adds the “disabled” class
enable()
- Removes the disabled attribute and “disabled” class
selectedText()
- Returns the text of a selected option on a select input
jQuery Extensions - Standalone jquery methods
$.humanFileSize(bytes,si)
- Returns a human-readable file size string.
$.humanFileSize(bytes,si)
- Returns a human-readable file size string.bytes - number of bytes to convert
si - Whether to use 1000 (true) or 1024 (false/undefined) as the base divisor
$.i18(stringArray)
- Returns a map of the supplied keys with their i18 Strings
$.alertSuccess(text)
- Fires a SweetAlert with the supplied text and the success icon
$.alertWarn(text)
- Fires a SweetAlert with the supplied text and the warning icon
$.alertError(text)
- Fires a SweetAlert with the supplied text and the error icon
$.alertInfo(text)
- Fires a SweetAlert with the supplied text and the information icon
$.alertQuestion(text)
- Fires a SweetAlert with the supplied text and the question icon
Contacting the Simflofy APIs
TSearch has a built-in set of methods that allow you to perform calls on behalf of the current user. Attempting to contact simflofy directly via REST calls will fail without the proper credentials. The methods are named after the standard REST methods, so:
get
- For retrieving dataput
- For updating data, accepts a body, accepts a JSON String as a request body via thedata
field in ajaxdelete
- For deleting datapost
- For creating new data, accepts a JSON String as a request body via thedata
field in ajax
Each of these methods take a single argument called req
, which contains the full Simflofy api call, without the /api/
prefix
These methods are only available internally (they cannot be accessed by external rest calls).
Below is an example of a PUT request
$.ajax({
type: 'PUT',
url: simflofyHost + "put?req=/search/" + Manager.connectorId + "/" + Manager.collection + "/security",//Note the lack of /api/ prefix
async: false,//This is generally considered bad form, but can be necessary if other components are waiting for the return, but are not part of the "success" method
headers: TSearch.getJSONHeaders(),
data: JSON.stringify({docs: docs}),//We always need to stringify the body
success: function (resp) {
if(resp.success){//The response will have a boolean flag for whether the call suceeded
let results = resp.results;//Results are dependant on whatever Simflofy returns, but it is usually a JSON or JSON String
}else{
$.alertError(resp.message);//Messages are usually only used in the case of an error.
}
},
error: function (err) {//This method will handle internal errors that would cause ajax to not receive a 200 response and present them as an error popup
handleError(err,'Updating Security');
}
})