Available javascript functions in web

Updated at 1693585767000
Here is the translation of the provided code:

ezyweb.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:

  1. key - String: The message key.
  2. 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:

  1. timestamp - Number.
  2. 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:

  1. 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:

  1. 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:

  1. 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:

  1. 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:

  1. 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:

  1. milestoneTime - Number: The milestone time in milliseconds.
  2. 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 be ago.

Example:

ezyweb.getTimeRangeTextValue(notification.sentAt, false);

ezyweb.formatNumberWithCommas

Formats a number with commas, e.g., 1000 becomes 1,000. Parameters include:

  1. 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:

  1. 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:

  1. list - Array: The list of elements.
  2. 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:

  1. 'admin-plugin': 'Plugin'
  2. 'socket-plugin': 'Plugin'
  3. 'socket-app': 'App'
  4. 'web-plugin': 'Plugin'
  5. 'theme': 'Theme'

Parameters include:

  1. 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:

  1. 'admin-plugin': 'Admin Plugin'
  2. 'socket-plugin': 'Socket Plugin'
  3. 'socket-app': 'Socket Application'
  4. 'web-plugin': 'Web Plugin'
  5. 'theme': 'Theme'

Parameters:

  1. 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:

  1. 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:

  1. 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:

  1. 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:

  1. 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:

  1. 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:

  1. str - String.

Example:

ezyweb.toHeadingString(feature);

ezyweb.truncateString

Shorten a string and append a suffix. Parameters:

  1. str - String: Input string.
  2. maxLength - Number: The maximum length of the string after truncation.
  3. 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:

  1. html - String.

Example:

ezyweb.getHtmlBodyContent(html);

ezyweb.removeHtmlTagAndSub

Remove HTML tags from content and truncate it. Parameters:

  1. html - String.
  2. maxLength - Number: The maximum length of the content after truncation.

Example:

ezyweb.removeHtmlTagAndSub(project.description, 300);

ezyweb.randomString

Generate a random string. Parameters:

  1. length - Number: The length of the random string.
  2. 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:

  1. 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:

  1. text - String: The content.
  2. tag - String: The name of the HTML tag.
  3. 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:

  1. paramName - String: The name of the parameter to retrieve.

Example:

var keyword = ezyweb.getCurrentUrlParameter('keyword');

ezyweb.joinToString

Convert an array to a string. Parameters:

  1. array - Array.
  2. separator - String: The character to use as a separator between elements.
  3. 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:

  1. objects - Array: The list of objects to merge.

Example:

ezyweb.mergeObjects([ezyweb.fromUserById, userMap]);

ezyweb.mergeObjectsToFirst

Merge objects into the first object. Parameters:

  1. 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:

  1. fetchFunctions - Array: The list of functions to execute.
  2. 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:

  1. elementId - String: The ID of the selected element.
  2. isInput - Boolean: Whether the selected element is an input or not.
  3. 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:

  1. 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:

  1. elementId - String: The ID of the element to listen to events.
  2. maxValueLength - Number: The maximum length of the input element's value.
  3. 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:

  1. media - Object: The media object.

Example:

var mediaUrl = ezyweb.extractMediaUrl(media);

ezyweb.scrollToElement

Scroll to the position of an element. Parameters:

  1. elementId - String: The ID of the element.
  2. duration - Number: The time duration for scrolling.

Example:

ezyweb.scrollToElement('answer', 100);

ezyweb.syntaxHighlightJson

Highlight JSON syntax. Parameters:

  1. 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:

  1. 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:

  1. input - Number: The number.

Example:

ezyweb.toCountString(data);

ezyweb.setCookie

Set a cookie value. Parameters:

  1. name - String: The cookie name.
  2. value - Any: The cookie value.
  3. days - Number: The number of days the cookie will exist.

Example:

ezyweb.setCookie('token', 'abc', 1);

ezyweb.deleteCookie

Delete a cookie. Parameters:

  1. name - String: The cookie name.

Example:

ezyweb.deleteCookie('token');

ezyweb.getCookie

Get the value of a cookie. Parameters:

  1. 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:

  1. responseData - Any: The response data from the server.
  2. 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:

  1. formData - Object: The form containing data fields mapped to fields with errors in the response data from the server.
  2. responseData - Any: The response data from the server.
  3. 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:

  1. 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.

  1. 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:

  1. 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:

  1. responseData - Object: The response data from the server.
  2. 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:

  1. tableId - String: The ID of the data table.
  2. pageLength - Number: The number of items per page.
  3. 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:

  1. selectedLanguage - String: The selected language code.

Example:

th:attr="onclick=|ezyweb.onLanguageSelected('${webLanguage.code}')|"