UNPKG

@groww-tech/ella

Version:

Ella is a utility-belt library for JavaScript that provides general purpose methods used in day to day programming.

380 lines (378 loc) 14.1 kB
/** * @module DOM */ /** * This method can be used to listen any custom event. * * @param {string} eventName - Name of the event that you want to listen or subscribe * @param {Function} callback - Callback function which will be called upon dispatching of that event * * @remarks * It's strongly recommended to add the event name in utils/constants/CUSTOM_EVENTS and use. No literals allowed. * * @example * ``` * listenToCustomEvent(CUSTOM_EVENTS.file_loaded, this.xyz) * ``` */ declare function listenToCustomEvent(eventName: string, callback: Function): void; /** * This method can be used to dispatch any custom event. * * @param {string} eventName - Name of the event that you want to dispatch * @param {object} eventDetails - OPTIONAL param, eventDetails object can be used to pass extra details * * @remarks * It's strongly recommended to add the event name in utils/constants/CUSTOM_EVENTS and use. No literals allowed. * * @example * ``` * dispatchCustomEvent(CUSTOM_EVENTS.file_loaded) * dispatchCustomEvent(CUSTOM_EVENTS.file_loaded, {user: 'Ella'}) * ``` */ declare function dispatchCustomEvent(eventName: string, eventDetails?: object): void; /** * This method can be used to unlisten any custom event. * * @param {string} eventName - Name of the event that you want to unlisten or unsubscribe * @param {Function} methodToUnlisten - The EventListener function of the event handler to remove from the event target. * * @remarks * It's strongly recommended to add the event name in utils/constants/CUSTOM_EVENTS and use. No literals allowed. * * @example * ``` * unlistenToCustomEvent(CUSTOM_EVENTS.file_loaded, this.xyz) * ``` */ declare function unlistenToCustomEvent(eventName: string, methodToUnlisten: Function): void; /** * This method can be used to scroll your html page to top. * * @example * ``` * scrollPageToTop(); * ``` */ declare function scrollPageToTop(): void; /** * This method can be used to block special character in input field, also you can allow few special chars as per your requirement * * @param {string} eventObject - Event object * @param {string[]} allowedArr - Array of allowed chars * * @remarks * How to use - Just send the event object here in the onKeyPress callback of input * * @example * ``` * blockSpecialChars(event, ['@', '%']) * ``` */ declare function blockSpecialChars(eventObject: React.KeyboardEvent<HTMLInputElement>, allowedArr: string[]): void; /** * This method can be used to copy some text to clipboard. * * @param {string} str - String that you want to copy to the clipboard * * @example * ``` * copyToClipboard("URN: 2303232923"); * ``` */ declare function copyToClipboard(str: string): void; /** * This method creates a timestamp in the browser's performance entry buffer with the given name. * * @param {string} name - Name of the event whose performance you want to measure * * @example * ``` * performanceMark('ComponentWillMount'); * performanceMark('ComponentMounted'); * performanceMeasure('ComponentWillMount','ComponentMounted') * ``` */ declare function performanceMark(name: string): void; /** * This method returns the difference of timestamp between 2 performance marks * * @param {string} markStart - Starting mark created using performanceMark method * @param {string} markEnd - Ending mark created using performanceMark method * * @example * ``` * performanceMark('ComponentWillMount'); * performanceMark('ComponentMounted'); * console.log("Component mounted in ms - "performanceMeasure('ComponentWillMount','ComponentMounted')); * ``` */ declare function performanceMeasure(markStart: string, markEnd: string): number | undefined; /** * This method can be used to encode path variables & query params in the URL. * * @param {string} queryParam - Param that you want to encode * * @remarks * It's advisable to always encode your query param or path variables before hitting the URL * * @example * ``` * const url = `/abc/xyz/${encodeURL(searchId)}`; * ``` */ declare function encodeURLParams(queryParam: string): string; /** * @deprecated since version 0.2.0 * This method can be used to get the browser name. * * @remarks * This method depends on userAgent sniffing and therefore susciptible to spoofing. Avoid detecting browsers in business impacting code * * @example * ``` * console.log('Browser Name - ',getBrowserName()); * ``` */ declare function getBrowserName(): string; /** * This method can be used to get the browser name & version. * * @remarks * This method depends on userAgent sniffing and therefore susciptible to spoofing. Avoid detecting browsers in business impacting code * * @example * ``` * console.log('Browser Name - ',getBrowserName()); * ``` */ declare function getBrowserVersion(): { name: string; version: string; } | { name: null; version: null; }; /** * This method can be used to get the OS Name. * * @remarks * This method depends on userAgent sniffing and therefore susciptible to spoofing. Avoid detecting browsers in business impacting code * * @example * ``` * console.log('Browser Name - ',getOSName()); * ``` */ declare function getOSName(): string; /** * This function scrolls the page to the top. * If window.scroll is available and works perfectly, this function uses the smooth scroll behaviour of window * and scrolls with ease in animation. Else, It directly scrolls to top without animation in case of error with * window.scroll. * * @example * ``` * smoothScrollToTop(); // The page is scrolled to the top. With animation if window object is present, * without animation if window object is not present. * ``` */ declare function smoothScrollToTop(): void; /** * This function scrolls to the position of an element with an id. * * @param {string} elementId - id of the element to which the page needs to be scrolled to * @param {number} offset - offset from top if we want to leave some space between the element top boundary * and top of the scrolled window. this is and optional parameter. default value is 0 * * @remarks * If element with particular id is not present at the time when this function is called, * then do nothing. A console.error will be called in such a case. * * @example * ``` * smoothScrollToElementWithId('enterAmountDiv'); // scroll the div with id 'enterAmountDiv' to top of the window * smoothScrollToElementWithId('enterAmountDiv', 0); // scroll the div with id 'enterAmountDiv' to top of the window * smoothScrollToElementWithId('enterAmountDiv', 100); // scroll the div with id 'enterAmountDiv' to 100px below the top of the window * * ``` */ declare function smoothScrollToElementWithId(elementId: string, offset?: number): void; /** * This method can be used to block the input after given decimal points * * @param {React.KeyboardEvent<HTMLInputElement>} eventObject - onKeyDown event object * @param {number | string} currentValue - Current value of input field * @param {number} toFixed - How many digits allowed after decimal. Default is 2 * * @remarks * It's strongly recommended to use this method on onKeyDown event to prevent the key from registering * * @example * ``` * <input * type="number" * onInput={this.handleInput} * value={this.state.value} * onKeyDown={(eventObject) => allowedDecimalPointInput(eventObject, this.state.value, 4)} * /> * ``` */ declare function allowedDecimalPointInput(eventObject: React.KeyboardEvent<HTMLInputElement>, currentValue: number | string, toFixed?: number): void; /** * This method can be used to block all the other input except numbers and utility keys * * @param {React.KeyboardEvent<HTMLInputElement>} eventObject - onKeyDown event object * * @remarks * It's strongly recommended to use this method on onKeyDown event to prevent the key from registering * * @example * ``` * <input * type="number" * onInput={this.handleInput} * value={this.state.value} * onKeyDown={(eventObject) => allowOnlyNumberKeys(eventObject)} * /> * ``` */ declare function allowOnlyNumberKeys(eventObject: React.KeyboardEvent<HTMLInputElement>): void; /** * This method can be used to block all the other input except numbers, decimal and utility keys * * @param {React.KeyboardEvent<HTMLInputElement>} eventObject - onKeyDown event object * * @remarks * It's strongly recommended to use this method on onKeyDown event to prevent the key from registering * * @example * ``` * <input * type="number" * onInput={this.handleInput} * value={this.state.value} * onKeyDown={(eventObject) => allowNumbersAndDecimal(eventObject)} * /> * ``` */ declare function allowNumbersAndDecimal(eventObject: React.KeyboardEvent<HTMLInputElement>): void; /** * This method returns a boolean value telling if the key pressed is utility key or not. * Utility Key - ArrowLeft, ArrowRight, Backspace, Delete * * @param {string} keyValue - key which got pressed i.e eventObject.key * * @remarks * It's strongly recommended to use this method on onKeyDown event to prevent the key from registering */ declare function isUtilKeyPressed(keyValue: string): boolean; /** * This method is used to push a message along with some data to a window instance. Useful in scenarios like iFrames, Webviews or Window Modals. * Must be used in conjuction with listenToWindowMessage method above. * * @param {Window} targetWindow - Target window that needs to listen to the message. Defaults to current window. * @param {Object} postObj -This method contains different fields like action, payload, screen etc. * @example * postObj = { * action -> Action type * payload - Any payload to be passed along with the action * screen -> Screen name to navigate for webview * } * @param {string} eventIdentifier - Unique identifier for your event. Defaults to CUSTOM_MESSAGE * * @example * ``` * const postObj = { 'CHANGE_THEME', { theme: 'dark' } } * postWindowMessage(postObj, 'MY_EVENT'); * ``` */ declare function postWindowMessage(postObj?: Object, eventIdentifier?: string, targetWindow?: Window | undefined): void; /** * This method is used to listen to the message event and receive data across windows. Must be used in conjuction with postWindowMessage method above. * * @param {Function} eventCallback - Method to execute when message is received. * @param {string} eventIdentifier - Unique event identifier which is used while posting message using postWindowMessage method * * * @example * ``` * listenToWindowMessage((messageData) => { * console.log(messageData); * }, 'MY_EVENT') * ``` */ declare function listenToWindowMessage(eventCallback: Function, eventIdentifier?: string): void; /** * This method is to force a reload when page is loaded from back forward cache. * The page loaded from back forward cache may contain older data that may not be * relevant now. Example: theme change, authentication states etc. * * @remarks * A problem is caused by back-forward cache in Safari. It is supposed to * save complete state of page when user navigates * away. When user navigates back with back button page can * be loaded from cache very quickly. This is different * from normal cache which only caches HTML code. * * When page is loaded for bfcache onload event wont be triggered. * Instead you can check the persisted property of * the onpageshow event. It is set to false on initial page load. * When page is loaded from bfcache it is set to true. * * Currently not using this function in the projects. But keeping this here so * that again research is not required if such issue comes. * * This issue was with mobile Safari browsers earlier, but now seems to be fine. */ declare function disableBackForwardCache(): void; /** * Converts base64/URLEncoded data component to raw binary data held in a string and returns the raw binary string * * @param {string} dataURI base64/URLEncoded data component * * @remarks * This method is only used in places where we are using canvas to get an esign. * stackoverflow thread for context: https://stackoverflow.com/questions/12168909/blob-from-dataurl * * @returns {Blob} raw binary data blob */ declare function dataURIToBlob(dataURI: string): Blob; /** * * @param element element/input on which we want the focus * @param timeout time after which the elment will be focused * * @example * * const elem = document.getElementById("searchInput"); * const delayDuration = 500; * * forceFocusAndOpenKeyboard(elem, delayDuration); * * @remarks * this function has a usecase for mobile devices (especially webview) * * iOS requires user interaction to open keyboard. Therefore, to open a keyboard at intialization of page, we're using this approach * To read more on this: https://stackoverflow.com/questions/54424729/ios-show-keyboard-on-input-focus * */ declare function forceFocusAndOpenKeyboard(element: HTMLElement, timeout?: number): void; /** * This method can be used to get the Device details like browser name, user agent, os name and origin i.e desktop or mobile website. * * @remarks * This method depends on userAgent sniffing and therefore susciptible to spoofing. Avoid detecting browsers in business impacting code * * @example * ``` * console.log('Get Device Details - ',getDeviceDetails()); * ``` */ declare function getDeviceDetails(): "" | { browserName: string; userAgent: string; OSName: string; origin: string; }; export { allowNumbersAndDecimal, allowOnlyNumberKeys, allowedDecimalPointInput, blockSpecialChars, copyToClipboard, dataURIToBlob, disableBackForwardCache, dispatchCustomEvent, encodeURLParams, forceFocusAndOpenKeyboard, getBrowserName, getBrowserVersion, getDeviceDetails, getOSName, isUtilKeyPressed, listenToCustomEvent, listenToWindowMessage, performanceMark, performanceMeasure, postWindowMessage, scrollPageToTop, smoothScrollToElementWithId, smoothScrollToTop, unlistenToCustomEvent };