Available javascript functions in web
Updated at 1693585767000ezyweb.getI18nMessage
I18n messages from the server via Thymeleaf can be rendered directly into the HTML page and sent to the client, typically assigned to the ezyweb.messages
variable. For example:
<script> /*<![CDATA[*/ ezyweb.messages.avatar = "Avatar"; ezyweb.messages.asked = "Asked"; </script>
The getI18nMessage
function is used to retrieve an i18n message from ezyweb.messages
based on the key passed in and can return it in lowercase if requested. In case there is no value, the parameters include:
- key - String: The message key.
- toLowerCase - Boolean: Convert the i18n message to lowercase or not.
Example:
const avatarMessage = ezyweb.getI18nMessage('avatar', true);
ezyweb.currentTimeMillis
Returns the current timestamp as a Number
.
Example:
var currentMillis = ezyweb.currentTimeMillis();
ezyweb.formatTimeStamp
Formats a timestamp from Number
to the required format. Parameters include:
- timestamp - Number.
- format - String: Default is
YYYY-MM-DD HH:mm:ss
.
Example:
ezyweb.formatTimeStamp(page.createdAt);
ezyweb.formatTimeStampMinute
Formats a timestamp from Number
to the format YYYY-MM-DD HH:mm
. Parameters include:
- timestamp - Number.
Example:
ezyweb.formatTimeStampMinute(timestame);
ezyweb.durationToString
Converts a duration (in seconds) to a string, e.g., 34218061
becomes: 1y-1m-1d 1h:1m:1s
. Parameters include:
- duration - Number.
Note: A year has 356 days, a month has 30 days.
Example:
ezyweb.durationToString(ezyweb.liveTime);
ezyweb.durationToSimpleString
Converts a duration (in seconds) to a simple string, e.g., 34822861
becomes: 1y1M1w1d1h1m1s
. Parameters include:
- duration - Number.
Note: A year has 356 days, a month has 30 days, a week has 7 days.
Example:
ezyweb.durationToSimpleString(duration);
ezyweb.simpleDurationStringToMillis
Converts a duration (in string format) to milliseconds, e.g., 1y1M1w1d
is converted to: 1450800000
. Parameters include:
- str - String.
Example:
ezyweb.simpleDurationStringToMillis('1m');
ezyweb.getTimeRangeValue
Calculates the time range compared to a milestone time from the current time, e.g., if the current time is 1693203170896
and the milestone time is 1693203170890
, the result will be 6
. Parameters include:
- milestoneTime - Number: The milestone time in milliseconds.
Example:
var timeRangeValue = ezyweb.getTimeRangeValue(milestoneTime);
ezyweb.getTimeRangeTextValue
Calculates the time range compared to a milestone time from the current time and converts it to a string, e.g., if the current time is 1693203170896
and the milestone time is 1693206770896
, the result will be 1 hour
. Parameters include:
- milestoneTime - Number: The milestone time in milliseconds.
- includeSuffix - Boolean: Whether to add a suffix to the time range, if added, if the milestone time is greater than the current time, the suffix will be
more
, otherwise, if the milestone time is smaller, it will beago
.
Example:
ezyweb.getTimeRangeTextValue(notification.sentAt, false);
ezyweb.formatNumberWithCommas
Formats a number with commas, e.g., 1000
becomes 1,000
. Parameters include:
- number - Number: The number to format.
Example:
ezyweb.formatNumberWithCommas(post.comments);
ezyweb.listToBooleanMap
Converts a list to a boolean map, e.g., List[1, 2, 3]
becomes Map{1:true, 2:true, 3:true}
. The goal is to convert it to a map for faster existence checking. Parameters include:
- list - Array: The list of elements.
Example:
var moduleTypeMap = ezyweb.listToBooleanMap(moduleTypes);
ezyweb.removeItemFromList
Removes an item from a list, e.g., removing 2
from [1, 2, 3]
results in [1, 3]
. Parameters include:
- list - Array: The list of elements.
- itemToRemove - Any: The item to remove from the list.
Example:
ezyweb.removeItemFromList(list, 1);
ezyweb.getModuleTypeShortName
Gets the abbreviated name of a module type from the name passed in. The list of module types mapped to their short names is as follows:
- 'admin-plugin': 'Plugin'
- 'socket-plugin': 'Plugin'
- 'socket-app': 'App'
- 'web-plugin': 'Plugin'
- 'theme': 'Theme'
Parameters include:
- moduleType - String.
Example:
var moduleTypeShortName = ezyweb.getModuleTypeShortName(module.type);
ezyweb.getModuleTypeName
Retrieve the module type name from the given module type. The list of module type names mapped to module types is as follows:
- 'admin-plugin': 'Admin Plugin'
- 'socket-plugin': 'Socket Plugin'
- 'socket-app': 'Socket Application'
- 'web-plugin': 'Web Plugin'
- 'theme': 'Theme'
Parameters:
- moduleType - String.
Example:
moduleTypeNames.push(ezyweb.getModuleTypeName(moduleType));
ezyweb.getModuleTypeNames
Get a list of module type names as a comma-separated string. For example, if you pass [admin-plugin, socket-plugin]
, you will get: Admin Plugin, Socket Plugin
. Parameters:
- moduleTypes - Array: List of module types.
Example:
ezyweb.getModuleTypeNames(moduleTypes);
ezyweb.getErrorMessageByCode
Retrieve an error message based on the provided error code. The message map with codes is as follows:
ezyweb.errorMessageByCode = { 'required': ezyweb.getI18nMessage('required'), 'invalid': ezyweb.getI18nMessage('invalid'), 'tooShort': ezyweb.getI18nMessage('too_short'), 'tooLong': ezyweb.getI18nMessage('too_long'), 'overLength': ezyweb.getI18nMessage('over_length'), 'duplicated': ezyweb.getI18nMessage('duplicated'), 'incorrect': ezyweb.getI18nMessage('incorrect'), 'mismatch': ezyweb.getI18nMessage('mismatch'), 'tooMany': ezyweb.getI18nMessage('too_many') };
Parameters:
- code - String: The error code.
Example:
ezyweb.getErrorMessageByCode('required');
Note: You can also add your own error codes and messages, for example:
ezyweb.errorMessageByCode['helloWorld'] = ezyweb.getI18nMessage('helloWorld');
ezyweb.getTextColorByStatus
Get text color based on the provided status. The color map with statuses is as follows:
ezyweb.textColorByStatus = { 'ACTIVATED': 'text-success', 'ARCHIVED': 'text-info', 'APPROVED': 'text-success', 'APPROVING': 'text-primary', 'BLOCKING': 'text-primary', 'BLOCKED': 'text-danger', 'BURNED': 'text-secondary', 'CLOSED': 'text-danger', 'DELETED': 'text-danger', 'INACTIVATED': 'text-secondary', 'MINTED': 'text-info', 'OPENED': 'text-success', 'PUBLISHED': 'text-success', 'REGISTER_OPENED': 'text-success', 'REGISTER_CLOSED': 'text-danger', 'REJECTED': 'text-danger', 'REVIEWING': 'text-primary', 'RELEASABLE': 'text-info', 'RELEASED': 'text-success' };
Parameters:
- status - String.
Example:
var statusColor = ezyweb.getTextColorByStatus(admin.status);
Note: You can also add your own colors and statuses, for example:
ezyweb.textColorByStatus['HELLO'] = 'text-hello';
ezyweb.toDisplayString
Convert a regular string to a display string, for example, hello world
, hello-world
, hello.world
, hello_world
will be converted to Hello world
. Parameters:
- str - String.
Example:
var displayString = ezyweb.toDisplayString(str);
ezyweb.toCapitalizeString
Convert a regular string to a string with the first letter of each word capitalized, for example, hello world
will be converted to Hello World
. Parameters:
- str - String.
Example:
ezyweb.toCapitalizeString(moduleType);
ezyweb.toHeadingString
Convert a regular string to a display string, for example, hello world
, hello-world
, hello.world
, hello_world
will be converted to Hello World
. Parameters:
- str - String.
Example:
ezyweb.toHeadingString(feature);
ezyweb.truncateString
Shorten a string and append a suffix. Parameters:
- str - String: Input string.
- maxLength - Number: The maximum length of the string after truncation.
- suffix - String: The suffix to append.
Example:
ezyweb.truncateString(notification.title, 18, '...');
ezyweb.getHtmlBodyContent
Retrieve the content within the body tags of an HTML string. Parameters:
- html - String.
Example:
ezyweb.getHtmlBodyContent(html);
ezyweb.removeHtmlTagAndSub
Remove HTML tags from content and truncate it. Parameters:
- html - String.
- maxLength - Number: The maximum length of the content after truncation.
Example:
ezyweb.removeHtmlTagAndSub(project.description, 300);
ezyweb.randomString
Generate a random string. Parameters:
- length - Number: The length of the random string.
- characters - String: A string containing characters to include in the random string. By default, it includes
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
.
Example:
var encryptionKey = ezyweb.randomString(32);
ezyweb.randomPassword
Generate a random password. Parameters:
- length - Number: The length of the password.
The characters in the password will be from the string: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_+
.
Example:
var password = ezyweb.randomPassword();
ezyweb.wrapTextIfNeed
Wrap content with an HTML tag if necessary. Parameters:
- text - String: The content.
- tag - String: The name of the HTML tag.
- need - Boolean: If true, the content will be wrapped with the tag; if false, it won't.
Example:
ezyweb.wrapTextIfNeed(from, 'strong', !letter.readAt);
ezyweb.getCurrentUrlParameter
Get a query parameter from the page's URL. Parameters:
- paramName - String: The name of the parameter to retrieve.
Example:
var keyword = ezyweb.getCurrentUrlParameter('keyword');
ezyweb.joinToString
Convert an array to a string. Parameters:
- array - Array.
- separator - String: The character to use as a separator between elements.
- itemMapper - Function: A function to convert each item.
Example:
ezyweb.joinToString( module.dependencies, ', ', it => it.projectName + ':' + it.projectVersion )
ezyweb.mergeObjects
Merge multiple objects together. Parameters:
- objects - Array: The list of objects to merge.
Example:
ezyweb.mergeObjects([ezyweb.fromUserById, userMap]);
ezyweb.mergeObjectsToFirst
Merge objects into the first object. Parameters:
- objects - Array: The list of objects to merge.
Example:
ezyweb.mergeObjectsToFirst([ezyweb.fromUserById, userMap]);
ezyweb.fetchAll
Call the callback
function after all other functions have been executed. Parameters:
- fetchFunctions - Array: The list of functions to execute.
- callback - Function: The
callback
function to call after the functions have finished executing.
Example:
var fetchUsers = callback => { ezyweb.fetchUsersByIds(newFromUserIds, (userMap) => { ezyweb.mergeObjectsToFirst([ezyweb.fromUserById, userMap]); callback(); }); } fetchUsers.condition = () => newFromUserIds.length; var fetchAdmins = callback => { ezyweb.fetchAdminsByIds(newFromAdminIds, (adminMap) => { ezyweb.mergeObjectsToFirst([ezyweb.fromAdminById, adminMap]); callback(); }); } fetchAdmins.condition = () => newFromAdminIds.length; var callback = () => $('#letterListBody').html( ezyweb.buildLetterListBodyHtml(data.items) ); ezyweb.fetchAll([fetchUsers, fetchAdmins], callback);
ezyweb.copyToClipboard
Copy the content of a selected element to the clipboard. Parameters:
- elementId - String: The ID of the selected element.
- isInput - Boolean: Whether the selected element is an input or not.
- alertTextPrefix - String: The prefix of the success copy alert.
Example:
ezyweb.copyToClipboard('updateMediaUrl', true, 'URL');
ezyweb.formDataToObject
Convert form data to an object. For example, if we have a form:
<form id="editRoleForm"> <input type="text" name="editRoleName" id="editRoleName"> <input type="text" name="editRoleDisplayName" id="editRoleDisplayName"> </form>
It will be converted into an object:
{ editRoleName: $('input[name="editRoleName"]').val(), editRoleDisplayName: $('input[name="editRoleDisplayName"]').val() }
Parameters:
- formName - String: The name of the form.
Example:
var formData = ezyweb.formDataToObject('addNewRoleForm');
ezyweb.watchInputKeyDown
Listen to keydown and keyup events of an input element to control the length of the value and display the current length of the value. Parameters:
- elementId - String: The ID of the element to listen to events.
- maxValueLength - Number: The maximum length of the input element's value.
- onEnterCallback - Function: The callback function when the user presses Enter.
For example, if you have the following HTML:
<input type="text" name="helloWorld" id="helloWorld"> <span id="helloWorldLength"></span>
You can use:
ezyweb.watchInputKeyDown('helloWorld', 100, () => { console.log('Enter'); });
ezyweb.extractMediaUrl
Get the URL from a media object. Parameters:
- media - Object: The media object.
Example:
var mediaUrl = ezyweb.extractMediaUrl(media);
ezyweb.scrollToElement
Scroll to the position of an element. Parameters:
- elementId - String: The ID of the element.
- duration - Number: The time duration for scrolling.
Example:
ezyweb.scrollToElement('answer', 100);
ezyweb.syntaxHighlightJson
Highlight JSON syntax. Parameters:
- json - String.
Example:
ezyweb.syntaxHighlightJson(body);
ezyweb.toCapacityString
Convert byte capacity to a formatted string. For example, 1
will be 1B
, 1024
will be 1KB
, and so on. Parameters:
- input - Number: The byte capacity.
Example:
ezyweb.toCapacityString(data.usedMemory);
ezyweb.toCountString
Convert a number to a formatted string, for example, 1000
becomes 1K
, 1000000
becomes 1M
, and so on. Parameters:
- input - Number: The number.
Example:
ezyweb.toCountString(data);
ezyweb.setCookie
Set a cookie value. Parameters:
- name - String: The cookie name.
- value - Any: The cookie value.
- days - Number: The number of days the cookie will exist.
Example:
ezyweb.setCookie('token', 'abc', 1);
ezyweb.deleteCookie
Delete a cookie. Parameters:
- name - String: The cookie name.
Example:
ezyweb.deleteCookie('token');
ezyweb.getCookie
Get the value of a cookie. Parameters:
- cname - String: The cookie name.
Example:
ezyweb.getCookie("adminAccessToken");
ezyweb.getCookieAccessToken
Get the user access token from a cookie.
Example:
ezyweb.getCookieAccessToken();
ezyweb.showLoadingScreen
Display the loading screen.
Example:
ezyweb.showLoadingScreen();
ezyweb.hideLoadingScreen
Hide the loading screen.
Example:
ezyweb.hideLoadingScreen();
ezyweb.logout
Log out the user.
Example:
ezyweb.logout();
ezyweb.redirectToLogin
Redirect to the login page with the path /login
.
Example:
ezyweb.redirectToLogin();
ezyweb.redirectToNotFound
Redirect to the not-found page with the path /not-found
.
Example:
ezyweb.redirectToNotFound();
ezyweb.redirectToServerError
Redirect to the server error page with the path /server-error
.
Example:
ezyweb.redirectToServerError();
ezyweb.processGetApiErrors
Handle errors when calling a GET API. Parameters:
- responseData - Any: The response data from the server.
- handler - Function or Map: A function or a map containing functions to handle error codes.
Example:
ezyweb.processGetApiErrors(e);
ezyweb.processUpdateApiErrors
Handle errors when calling an API and display the errors on the form's interface. Parameters:
- formData - Object: The form containing data fields mapped to fields with errors in the response data from the server.
- responseData - Any: The response data from the server.
- handler - Function or Map: A function or a map containing functions to handle error codes.
For example, in the case where the field names in the form match the fields in the response data:
HTML form:
<form class="form-horizontal" id="contactUsForm"> <div class="form-group"> <label for="contactUsYourName" class="col-form-label"> [[#{ezysupport_contact_us_your_name}]] </label> <label class="col-form-label text-danger ml-2 ms-2 d-none" id="contactUsYourNameErrorLabel" for="contactUs YourName"> <i class="fas fa-exclamation"></i> <span id="contactUsYourNameError"></span> </label> <input type="text" name="contactUsYourName" id="contactUsYourName" class="form-control" th:value="${user != null ? user.displayName : ''}"> </div> ... <div class="form-group"> <button type="button" id="submitButton" class="form-control btn btn-outline-primary" onclick="ezysupport.sendContactUs();"> [[#{ezysupport_contact_us_submit}]] </button> </div> </form>
JavaScript code:
var formData = ezyweb.formDataToObject('contactUsForm'); $.ajax({ ... error: function (data, e) { ezyweb.processUpdateApiErrors(formData, data); } });
In the case where the field names in the form do not match the fields in the response data:
HTML form:
<form id="changePasswordForm"> <div class="form-group row" th:if="${!hasAutoGeneratedPassword}"> <label for="changeOldPassword" class="col-sm-4 col-form-label"> [[#{old_password}]] </label> <div class="col-sm-8"> <label class="col-form-label text-danger d-none" id="changeOldPasswordErrorLabel" for="changeOldPassword"> <i class="far fa-times-circle"></i> <span id="changeOldPasswordError"></span> </label> <div class="input-group mb-3"> <input type="password" name="oldPassword" onkeydown="onKeyDownToChangePassword()" id="changeOldPassword" class="form-control" th:placeholder="#{old_password}"> </div> </div> </div> ... <div class="form-group row"> <label for="changeRetypePassword" class="col-sm-4 col-form-label"> [[#{retype_password}]] </label> <div class="col-sm-8"> <label class="col-form-label text-danger d-none" id="changeRetypePasswordErrorLabel" for="changeRetypePassword"> <i class="far fa-times-circle"></i> <span id="changeRetypePasswordError"></span> </label> <div class="input-group"> <input type="password" name="retypeNewPassword" onkeydown="onKeyDownToChangePassword()" id="changeRetypePassword" class="form-control" th:placeholder="#{retype_password}"> </div> </div> </div> </form>
JavaScript code:
var formView = { changeOldPassword: true, changeNewPassword: true, changeRetypePassword: true }; $.ajax({ ..., error: function (e) { var errors = e.responseJSON || {}; errors.changeOldPassword = errors.password; errors.changeNewPassword = errors.newPassword; ezyweb.processUpdateApiErrors(formView, e); } });
In this case, you need to create a dummy form to map to fields in the response data.
ezyweb.hideFormErrors
Hide error messages from the form. Parameters:
- formData - Object: The form containing data fields mapped to fields with errors in the response data from the server.
Example:
ezyweb.hideFormErrors(formData);
ezyweb.resetFormData
Hide error messages and reset the data of the form.
- formData - Object: The form containing data fields mapped to fields with errors in the response data from the server.
Example:
ezyweb.resetFormData(formData);
ezyweb.getUploadFileApiErrorMessage
Parse and return an error message code from the server response when calling an upload file API. Parameters:
- responseData - Object: The response data from the server.
Example:
var errorMessage = ezyweb.getUploadFileApiErrorMessage(responseData);
ezyweb.processUploadFileApiErrors
Handle errors in the case of a file upload failure. If the error code is 401
, it redirects to the login page. Parameters:
- responseData - Object: The response data from the server.
- uploadView - Object: An object containing information about the file upload interface.
Example:
var releaseProjectView = { name: 'uploadProject', chooseFileLabelText: $('#releaseBundleFileLabel').text() }; ezyweb.processUploadFileApiErrors(data, releaseProjectView);
ezyweb.formatDateStringElements
Iterate through all elements with the class date-string
and convert data from timestamp format to YYYY-MM-DD
.
Example:
ezyweb.formatDateStringElements();
ezyweb.formatDateTimeStringElements
Iterate through all elements with the class date-time-string
and convert data from timestamp format to YYYY-MM-DD HH:mm:ss
.
Example:
ezyweb.formatDateTimeStringElements();
ezyweb.formatDateTimeMinuteStringElements
Iterate through all elements with the class date-time-minute-string
and convert data from timestamp format to YYYY-MM-DD HH:mm:ss
.
Example:
ezyweb.formatDateTimeStringElements();
ezyweb.formatStatus
TextElements
Iterate through all elements with the class status-text
and add a color class to the text.
Example:
ezyweb.formatStatusTextElements();
ezyweb.formatNumberWithCommasElements
Iterate through all elements with the class commas-number-string
and format the value with commas.
Example:
ezyweb.formatNumberWithCommasElements();
ezyweb.createDataTable
Create a data table. Parameters:
- tableId - String: The ID of the data table.
- pageLength - Number: The number of items per page.
- searching - Boolean: Allow searching or not.
Example:
ezyadmin.createDataTable('categoryList', 12);
Note: To use this function, you must include the DataTables library in your HTML page. You can use a CDN.
ezyweb.appendLangParameterToFormActions
Append the lang
parameter to form actions.
Example:
ezyweb.appendLangParameterToFormActions();
ezyweb.appendLangParameterToLinks
Append the lang
parameter to the href
attribute of a
tags.
Example:
ezyweb.appendLangParameterToLinks();
ezyweb.onLanguageSelected
Change the page to a new language when the user selects a language. Parameters:
- selectedLanguage - String: The selected language code.
Example:
th:attr="onclick=|ezyweb.onLanguageSelected('${webLanguage.code}')|"