Available javascript functions in admin

Updated at 1693562496000

ezyadmin.getI18nMessage

I18n messages from the server through Thymeleaf can be rendered on an HTML page and sent to the client, typically assigned to the ezyadmin.messages variable, for example:

<script>
/*<![CDATA[*/
ezyadmin.messages.avatar = "Avatar";
ezyadmin.messages.asked = "Asked";
</script>

The getI18nMessage function is used to retrieve an i18n message from ezyadmin.messages based on the provided key and can return it in lowercase if requested. In cases where there is no value, the parameters include:

  1. key - String: the message key.
  2. toLowerCase - Boolean: whether to convert the i18n message to lowercase or not.

Example:

const avatarMessage = ezyadmin.getI18nMessage('avatar', true);

ezyadmin.currentTimeMillis

Returns the current timestamp as a Number.

Example:

var currentMillis = ezyadmin.currentTimeMillis();

ezyadmin.formatTimeStamp

Formats a timestamp from Number into the desired format. The parameters include:

  1. timestamp - Number.
  2. format - String: Default is YYYY-MM-DD HH:mm:ss.

Example:

ezyadmin.formatTimeStamp(page.createdAt);

ezyadmin.formatTimeStampMinute

Format a timestamp from Number to the format YYYY-MM-DD HH:mm. The parameters include:

1. timestamp - Number

Example:

ezyadmin.formatTimeStampMinute(timestamp);

ezyadmin.durationToString

Converts a duration (in seconds) to a string, for example, 34218061 will be 1y-1m-1d 1h:1m:1s. The parameter includes:

  1. duration - Number.

Note: A year is considered as 356 days, a month as 30 days.

Example:

ezyadmin.durationToString(ezyadmin.liveTime);

ezyadmin.durationToSimpleString

Converts a duration (in seconds) to a simplified string format, for example, 34822861 will be 1y1M1w1d1h1m1s. The parameter includes:

  1. duration - Number.

Note: A year is considered as 356 days, a month as 30 days, and a week as 7 days.

Example:

ezyadmin.durationToSimpleString(duration);

ezyadmin.simpleDurationStringToMillis

Converts a duration (in string format) to milliseconds, for example, 1y1M1w1d will be converted to 1450800000. The parameter includes:

  1. str - String.

Example:

ezyadmin.simpleDurationStringToMillis('1m');

ezyadmin.getTimeRangeValue

Calculates the time range compared to the milestone time from the current time, for example, if the current time is 1693203170896 and the milestone time is 1693203170890, the result will be 6. The parameter includes:

  1. milestoneTime - Number: The milestone time in milliseconds.

Example:

var timeRangeValue = ezyadmin.getTimeRangeValue(milestoneTime);

ezyadmin.getTimeRangeTextValue

Calculates the time range compared to the milestone time from the current time and converts it to a string format. For example, if the current time is 1693203170896, and the milestone time is 1693206770896, the result will be 1 hour. The parameters include:

  1. milestoneTime - Number: The milestone time in milliseconds.
  2. includeSuffix - Boolean: Whether to add a suffix to the time range. If it's true, and 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:

ezyadmin.getTimeRangeTextValue(notification.sentAt, false);

ezyadmin.formatNumberWithCommas

Format a number with comma delimiters, for example, 1000 becomes 1,000. The parameter is:

number - Number: The number to format.

Example:

ezyadmin.formatNumberWithCommas(post.comments);

ezyadmin.listToBooleanMap

Convert a list into a boolean map, for example, List[1, 2, 3] will be converted to Map{1:true, 2:true, 3:true}. The goal is to convert it into a map for faster element existence checks. The parameter is:

  1. list - Array: The list of elements.

Example:

var moduleTypeMap = ezyadmin.listToBooleanMap(moduleTypes);

ezyadmin.removeItemFromList

Remove an item from a list, for example, removing 2 from [1, 2, 3] will result in [1, 3]. The parameters are:

  1. list - Array: The list of elements.
  2. itemToRemove - Any: The element to remove from the list.

Example:

ezyadmin.removeItemFromList(list, 1);

ezyadmin.getModuleTypeShortName

Retrieve the module type from the given name. The list of module types mapped to short names is as follows:

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

The parameter is:

  1. moduleType - String.

Example:

var moduleTypeShortName = ezyadmin.getModuleTypeShortName(module.type);

ezyadmin.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'

Parameter:

  1. moduleType - String.

Example:

moduleTypeNames.push(ezyadmin.getModuleTypeName(moduleType));

ezyadmin.getModuleTypeNames

Retrieve a list of module type names as a comma-separated string, for example, when passing [admin-plugin, socket-plugin], you will receive: Admin Plugin, Socket Plugin. The parameter is:

  1. moduleTypes - Array: The list of module types.

Example:

ezyadmin.getModuleTypeNames(moduleTypes);

ezyadmin.getErrorMessageByCode

Retrieve an error message by the provided code. The list of messages mapped to codes is as follows:

ezyadwmin.errorMessageByCode = {
    'required': ezyadmin.getI18nMessage('required'),
    'invalid': ezyadmin.getI18nMessage('invalid'),
    'tooShort': ezyadmin.getI18nMessage('too_short'),
    'tooLong': ezyadmin.getI18nMessage('too_long'),
    'overLength': ezyadmin.getI18nMessage('over_length'),
    'duplicated': ezyadmin.getI18nMessage('duplicated'),
    'incorrect': ezyadmin.getI18nMessage('incorrect'),
    'mismatch': ezyadmin.getI18nMessage('mismatch'),
    'tooMany': ezyadmin.getI18nMessage('too_many')
};

Parameter:

  1. code - String: The error code.

Example:

ezyadmin.getErrorMessageByCode('required');

Note: You can also add your own error codes and messages, for example:

ezyadmin.errorMessageByCode['helloWorld'] = ezyadmin.getI18nMessage('helloWorld');

ezyadmin.getTextColorByStatus

Retrieve the text color based on the provided status. The list of color mappings for statuses is as follows:

ezyadmin.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'
};

Parameter:

  1. status - String

Example:

var statusColor = ezyadmin.getTextColorByStatus(admin.status);

Note: You can also add your own colors and statuses, for example:

ezyadmin.textColorByStatus['HELLO'] = 'text-hello';

ezyadmin.toDisplayString

Convert a regular string into a display string, for example, hello world, hello-world, hello.world, hello_world will be converted into Hello world. The parameter is:

  1. str - String

Example:

var displayString = ezyadmin.toDisplayString(str);

ezyadmin.toCapitalizeString

Convert a regular string into a string with the initial letters capitalized. For example, hello world will be transformed into Hello World. The parameter is:

  1. str - String

Example:

ezyadmin.toCapitalizeString(moduleType);

ezyadmin.toHeadingString

Convert a regular string into a display string. For example, hello world, hello-world, hello.world, hello_world will be converted into Hello World. The parameter is:

  1. str - String

Example:

ezyadmin.toHeadingString(feature);

ezyadmin.truncateString

Truncate a string and append a suffix. The parameters are:

  1. str - String: The input string.
  2. maxLength - Number: The length to truncate the string.
  3. suffix - String: The suffix to append.

Example:

ezyadmin.truncateString(notification.title, 18, '...');

ezyadmin.getHtmlBodyContent

Retrieve the content within the HTML body. The parameter is:

  1. html - String.

Example:

ezyadmin.getHtmlBodyContent(html);

ezyadmin.removeHtmlTagAndSub

Remove HTML tags from content and truncate it. The parameters are:

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

Example:

ezyadmin.removeHtmlTagAndSub(project.description, 300);

ezyadmin.randomString

Generate a random string. The parameters are:

  1. length - Number: The length of the random string.
  2. characters - String: A string containing characters to be used for randomization, default is ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.

Example:

var encryptionKey = ezyadmin.randomString(32);

ezyadmin.randomPassword

Generate a random password. The parameter is:

  1. length - Number: The length of the password.

The characters in the password will be selected from the string: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_+.

Example:

var password = ezyadmin.randomPassword();

ezyadmin.wrapTextIfNeed

Wrap content with an HTML tag if necessary. The parameters are:

  1. text - String: The content.
  2. tag - String: The HTML tag name.
  3. need - Boolean: If true, the content will be wrapped with the tag; otherwise, it won't.

Example:

ezyadmin.wrapTextIfNeed(from, 'strong', !letter.readAt);

ezyadmin.getCurrentUrlParameter

Retrieve a query parameter from the page's URL. The parameter is:

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

Example:

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

ezyadmin.joinToString

Convert an array into a string. The parameters are:

  1. array - Array.
  2. separator - String: The character that separates elements.
  3. itemMapper - Function: A function for converting items.

Example:

ezyadmin.joinToString(
    module.dependencies,
    ', ',
    it => it.projectName + ':' + it.projectVersion
)

ezyadmin.mergeObjects

Merge objects together. The parameter is:

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

Example:

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

ezyadmin.mergeObjectsToFirst

Merge objects into the first object. The parameter is:

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

Example:

ezyadmin.mergeObjectsToFirst([ezyadmin.fromUserById, userMap]);

ezyadmin.fetchAll

Call the callback function after all other functions have been executed. The parameters are:

  1. fetchFunctions - Array: The list of functions to execute.
  2. callback - Function: The callback function to call after the specified functions have completed.

Example:

var fetchUsers = callback => {
    ezyadmin.fetchUsersByIds(newFromUserIds, (userMap) => {
        ezyadmin.mergeObjectsToFirst([ezyadmin.fromUserById, userMap]);
        callback();
    });
}
fetchUsers.condition = () => newFromUserIds.length;

var fetchAdmins = callback => {
    ezyadmin.fetchAdminsByIds(newFromAdminIds, (adminMap) => {
        ezyadmin.mergeObjectsToFirst([ezyadmin.fromAdminById, adminMap]);
        callback();
    });
}
fetchAdmins.condition = () => newFromAdminIds.length;

var callback = () => $('#letterListBody').html(
    ezyadmin.buildLetterListBodyHtml(data.items)
);
ezyadmin.fetchAll([fetchUsers, fetchAdmins], callback);

ezyadmin.shortToast

Display a toast. The parameters are:

  1. colorClass - String: The class name for the text or background color.
  2. title - String: The title.
  3. body - String: The content.

Example:

ezyadmin.shortToast('bg-success', 'Update successfully');

ezyadmin.copyToClipboard

Copy the content of the selected element to the clipboard. The parameters are:

  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 for the successful copy alert.

Example:

ezyadmin.copyToClipboard('updateMediaUrl', true, 'URL');

ezyadmin.formDataToObject

Convert form data into an object. For example, if you have the following 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 like this:

{
  editRoleName: $('input[name="editRoleName"]').val(),
  editRoleDisplayName: $('input[name="editRoleDisplayName"]').val()
}

The parameter is:

  1. formName - String: The name of the form.

Example:

var formData = ezyadmin.formDataToObject('addNewRoleForm');

ezyadmin.watchInputKeyDown

Listen for keydown and keyup events on an input element to control the length of the value and display the current length. The parameters are:

  1. elementId - String: The ID of the element to listen to.
  2. maxValueLength - Number: The maximum length of the input value.
  3. onEnterCallback - Function: The callback function when the user presses Enter.

Example:

You have HTML like this:

<input type="text" name="helloWorld" id="helloWorld">
<span id="helloWorldLength"></span>

You can use it like this:

ezyadmin.watchInputKeyDown('helloWorld', 100, () => { console.log('Enter'); });

ezyadmin.extractMediaUrl

Retrieve the URL from a media object. The parameter is:

  1. media - Object: The media object.

Example:

var mediaUrl = ezyadmin.extractMediaUrl(media);

ezyadmin.scrollToElement

Scroll to the position of an element. The parameters are:

  1. elementId - String: The ID of the element.
  2. duration - Number: The duration of the scroll.

Example:

ezyadmin.scrollToElement('answer', 100);

ezyadmin.syntaxHighlightJson

Highlight JSON syntax. The parameter is:

  1. json - String.

Example:

ezyadmin.syntaxHighlightJson(body);

ezyadmin.toCapacityString

Convert byte capacity to a string. For example, 1 becomes 1B, 1024 becomes 1KB, and so on. The parameter is:

  1. input - Number: The byte capacity.

Example:

ezyadmin.toCapacityString(data.usedMemory);

ezyadmin.toCountString

Convert a quantity to a string, for example, 1000 becomes 1K, 1000000 becomes 1M, and so on. The parameter is:

  1. input - Number: The quantity.

Example:

ezyadmin.toCountString(data);

ezyadmin.setCookie

Set a cookie value. The parameters are:

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

Example:

ezyadmin.setCookie('token', '

abc', 1);

ezyadmin.deleteCookie

Delete a cookie. The parameter is:

  1. name - String: The cookie name.

Example:

ezyadmin.deleteCookie('token');

ezyadmin.getCookie

Retrieve the value of a cookie. The parameter is:

  1. cname - String: The cookie name.

Example:

ezyadmin.getCookie("adminAccessToken");

ezyadmin.getCookieAccessToken

Retrieve the admin access token from a cookie.

Example:

ezyadmin.getCookieAccessToken();

ezyadmin.enableServer

Enable a server. The parameter is:

  1. target - String: Either 'admin', 'socket', or 'web'.

Example:

ezyadmin.enableServer('socket');

ezyadmin.disableServer

Disable a server. The parameter is:

  1. target - String: Either 'admin', 'socket', or 'web'.

Example:

ezyadmin.disableServer('socket');

ezyadmin.startServer

Start a server. The parameter is:

  1. target - String: Either 'admin', 'socket', or 'web'.

Example:

ezyadmin.startServer('socket');

ezyadmin.stopServer

Stop a server. The parameter is:

  1. target - String: Either 'admin', 'socket', or 'web'.

Example:

ezyadmin.stopServer('socket');

ezyadmin.restartServer

Restart a server. The parameter is:

  1. target - String: Either 'admin', 'socket', or 'web'.

Example:

ezyadmin.restartServer('socket');

ezyadmin.doTargetAction

Perform an action on a server. The parameters are:

  1. target - String: Either 'admin', 'socket', or 'web'.
  2. action - String: Either 'enable', 'disable, 'stop', 'start', or 'restart'.
  3. showLoading - Boolean: Whether to show loading or not.

Example:

ezyadmin.doTargetAction(target, 'Enable', false);

ezyadmin.ensureAdminRunning

Call a callback function if the admin is still running or wait for the admin to start running again. The parameter is:

  1. callback - Function.

Example:

ezyadmin.ensureAdminRunning(postAction);

ezyadmin.showLoadingScreen

Display the loading screen.

Example:

ezyadmin.showLoadingScreen();

ezyadmin.hideLoadingScreen

Hide the loading screen.

Example:

ezyadmin.hideLoadingScreen();

ezyadmin.showProfile

Navigate to the admin profile page.

Example:

ezyadmin.showProfile();

ezyadmin.logout

Log out the admin.

Example:

ezyadmin.logout();

ezyadmin.redirectToLogin

Redirect to the login page.

Example:

ezyadmin.redirectToLogin();

ezyadmin.redirectToPermissionDenied

Redirect to the permission denied page with the path /permission-denied.

Example:

ezyadmin.redirectToPermissionDenied();

ezyadmin.redirectToNotFound

Redirect to the not found page with the path /not-found.

Example:

ezyadmin.redirectToNotFound();

ezyadmin.redirectToServerError()

Redirect to the server error page with the path /server-error.

Example:

ezyadmin.redirectToServerError();

ezyadmin.processGetApiErrors

Handle errors when making GET API calls and display them. The parameters are:

  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:

ezyadmin.processGetApiErrors(e);

ezyadmin.processUpdateApiErrors

Handle errors when making API calls and display them on the form interface. The parameters are:

  1. formData - Object: The form data containing 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.

Example:

In case the field names in the form match the fields in the response data:

HTML of the 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="contactUsYourName">
            <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 = ezyadmin.formDataToObject('contactUsForm');
$.ajax({
    ...
    error: function (data, e) {
        ezyadmin.processUpdateApiErrors(formData, data);
    }
});

In case the field names in the form do not match the fields in the response data:

HTML of the 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>
</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;
    	ezyadmin.processUpdateApiErrors(formView, e);
    }
});

In this case, you need to create a mock form to map to the fields in the response data.

ezyadmin.hideFormErrors

Hide error messages from the form. The parameter is:

  1. formData - Object: The form data containing fields mapped to fields with errors in the response data from the server.

Example:

ezyadmin.hideFormErrors(formData);

ezyadmin.resetFormData

Hide error messages and reset the form data.

  1. formData - Object: The form data containing fields mapped to fields with errors in the response data from the server.

Example:

ezyadmin.resetFormData(formData);

ezyadmin.getUploadFileApiErrorMessage

Parse and return error messages from the server response when uploading a file. The parameter is:

  1. responseData - Object: The response data from the server.

Example:

var errorMessage = ezyadmin.getUploadFileApiErrorMessage(responseData);

ezyadmin.processUploadFileApiErrors

Handle errors in case of file upload failure. If the error code is 401, it will redirect to the login page. The parameters are:

  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()
};
ezyadmin.processUploadFileApiErrors(data, releaseProjectView);

ezyadmin.formatDateStringElements

Iterate through all elements with the class date-string and convert data from timestamp format to YYY-MM-DD.

Example:

ezyadmin.formatDateStringElements();

ezyadmin.formatDateTimeStringElements

Iterate through all elements with the class date-time-string and convert data from timestamp format to YYY-MM-DD HH:mm:ss.

Example:

ezyadmin.formatDateTimeStringElements();

ezyadmin.formatDateTimeMinuteStringElements

Iterate through all elements with the class date-time-minute-string and convert data from timestamp format to YYY-MM-DD HH:mm:ss.

Example:

ezyadmin.formatDateTimeStringElements();

ezyadmin.formatStatusTextElements

Iterate through all elements with the class status-text and add color classes to the text.

Example:

ezyadmin.formatStatusTextElements();

ezyadmin.formatNumberWithCommasElements

Iterate through all elements with the class commas-number-string and format the value with commas.

Example:

ezyadmin.formatNumberWithCommasElements();

ezyadmin.createDataTable

Create a data table. The parameters are:

  1. tableId - String: The id of the data table.
  2. pageLength - Number: The number of items per page.
  3. searching - Boolean: Whether to enable searching or not.

Example:

ezyadmin.createDataTable('categoryList', 12);

Note: To use this function, you need to include the data table library in your HTML page. You can use a CDN.

ezyadmin.appendLangParameterToFormActions

Add a lang parameter to form actions.

Example:

ezyadmin.appendLangParameterToFormActions();

ezyadmin.appendLangParameterToLinks

Add a lang parameter to the href attribute of <a> tags.

Example:

ezyadmin.appendLangParameterToLinks();

ezyadmin.onLanguageSelected

Switch to a new language when the user selects a language. The parameter is:

selectedLanguage - String: The selected language code.

Example:

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

ezyadmin.fetchAdminsByIds

Retrieve a list of admins by their IDs. The parameters are:

  1. ids - Array: A list of admin IDs.
  2. callback - Function: A callback function to be called when the list of admins is successfully retrieved.

Example:

var fetchAdmins = callback => {
    ezyadmin.fetchAdminsByIds(newFromAdminIds, (adminMap) => {
        ezyadmin.mergeObjectsToFirst([ezyadmin.fromAdminById, adminMap]);
        callback();
    });
}

ezyadmin.fetchUsersByIds

Retrieve a list of users by their IDs. The parameters are:

  1. ids - Array: A list of user IDs.
  2. callback - Function: A callback function to be called when the list of users is successfully retrieved.

Example:

var fetchUsers = callback => {
    ezyadmin.fetchUsersByIds(newFromUserIds, (userMap) => {
        ezyadmin.mergeObjectsToFirst([ezyadmin.fromUserById, userMap]);
        callback();
    });
}