### String Formatting Examples Source: https://github.com/lindseysim/web-common/blob/release/README.md Demonstrates various ways to format numbers into strings using the `stringFormat` method, including controlling decimal places and scientific notation. ```javascript (-1e-4).stringFormat(); // '0.0' (-1e-4).stringFormat(null, 0); // '0' (-1e-4).stringFormat(1e-5, '0'); // '-1.000e-4' (0.0012345).stringFormat(); // '1.234e-3' (0.012345).stringFormat(); // '1.23e-2' (0.12345).stringFormat(); // '0.123' (0.345).stringFormat(); // '0.34' (12.345).stringFormat(); // '12.3' (123.45).stringFormat(); // '123' ``` -------------------------------- ### Semantic String Comparison (Chunking Example) Source: https://github.com/lindseysim/web-common/blob/release/README.md Illustrates how `semanticCompare` breaks strings into chunks for comparison, prioritizing numeric and then lexicographical order. ```javascript "a10bc40".semanticCompare("a10b50c"); // 1 ``` -------------------------------- ### Browser Information Object Example Source: https://github.com/lindseysim/web-common/blob/release/README.md This object shows the structure of the `browser` variable, including parsed browser versions and a specific browser flag. It is generated from a UserAgent string. ```javascript { chrome: 88, safari: 537, opera: 74, isOpera: true } ``` -------------------------------- ### Get URL GET Parameters Source: https://github.com/lindseysim/web-common/blob/release/README.md Retrieves GET parameters from the current URL and returns them as an object literal. ```javascript common.getUrlGetVars() ``` -------------------------------- ### common.getUrlGetVars Source: https://github.com/lindseysim/web-common/blob/release/README.md Retrieves GET parameters from the current URL and returns them as an object literal. ```APIDOC ## common.getUrlGetVars ### Description Retrieves GET parameters in the current URL as an object literal (dictionary format). ### Returns Object literal of GET parameters found in URL. ``` -------------------------------- ### Convert Date to UTC and Drop Time Information Source: https://github.com/lindseysim/web-common/blob/release/README.md Converts a Date object to UTC by first converting its local time to UTC, then dropping any time information, assuming 12:00 AM UTC. The resulting date represents the start of the day in UTC. ```javascript d = new Date(2019, 0, 1, 20); // Tue Jan 01 2019 20:00:00 GMT-0800 (Pacific Standard Time) d.toUTCDate(); // Tue Jan 01 2019 16:00:00 GMT-0800 (Pacific Standard Time) ``` -------------------------------- ### Remove All Instances of a Value from an Array Source: https://github.com/lindseysim/web-common/blob/release/README.md Removes all instances of a specified value from an array, creating a copy without modifying the original. Supports specifying a starting index and a limit for removals. ```javascript let a = [0, 1, 1, 2, 3, 5]; a.remove(1); // [0, 2, 3, 5] a.remove(1, 2); // [0, 1, 2, 3, 5] a.remove(1, null, 1); // [0, 1, 2, 3, 5] ``` -------------------------------- ### Initialize and Populate CommonTable Source: https://github.com/lindseysim/web-common/blob/release/README.md Demonstrates how to create a CommonTable instance, append it to the DOM, define columns with custom sorting and formatting, and populate it with data. Use this for setting up dynamic tables with complex data structures. ```javascript let tbl = new CommonTable("my-table-id", "my-table-class"); tbl.appendTo(document.body); // define columns (first define general centering styles to extend/reuse later) let styleCenter = {'text-align': 'center'}, optsCenter = {hdrStyles: styleCenter, colStyles: styleCenter}; // first two columns under "Name" header group tbl.addColumn({group: "Name", title: "First", key: "firstName"}) .addColumn({group: "Name", title: "Last", key: "lastName"}) // add custom sorting by position, ascending from back of field to start of field .addColumn(common.extend(optsCenter, { title: "Position", key: "position", sortFunction: (a, b) => { if(a == b) return 0; if(a.startsWith("GK")) return -1; if(b.startsWith("GK")) return 1; if(a.startsWith("DF")) return -1; if(b.startsWith("DF")) return 1; if(a.startsWith("FW")) return 1; i f(b.startsWith("FW")) return -1; } })) // add formatting for date value to date string .addColumn({ title: "Birthday", key: "birthDate", format: val => `${(val.getMonth()+1).toString()}/${val.getDate().toString()}/${val.getFullYear().toString()}` }) // general stats .addColumn(common.extend(optsCenter, {title: "Matches", key: "mp"})) .addColumn(common.extend(optsCenter, {title: "Starts", key: "ms"})) .addColumn(common.extend(optsCenter, {title: "Goals", key: "gls"})) .addColumn(common.extend(optsCenter, {title: "Assists", key: "ast"})) // last two columns under the "Expected" header ground (for advanced stats xG and xAG) .addColumn(common.extend(optsCenter, { group: "Expected", title: "xG", key: "xg", format: val => val.addCommas(1) })) .addColumn(common.extend(optsCenter, { group: "Expected", title: "xAG", key: "xag", format: val => val.addCommas(1) })); // add date and render table let data = [ {firstName: "Claire", lastName: "Emslie", position: "FW", gls: 7, ast: 2, mp: 26, ms: 24, xg: 7.7, xag: 3.7, birthDate: new DateUTC(1994, 3, 8)}, {firstName: "Kennedy", lastName: "Fuller", position: "MF", gls: 1, ast: 0, mp: 19, ms: 10, xg: 1.7, xag: 0.9, birthDate: new DateUTC(2007, 3, 9)}, {firstName: "Sarah", lastName: "Gorden", position: "DF", gls: 0, ast: 0, mp: 24, ms: 24, xg: 0.1, xag: 0.1, birthDate: new DateUTC(1992, 9, 13)}, {firstName: "Alyssa", lastName: "Thompson", position: "FW", gls: 5, ast: 7, mp: 26, ms: 24, xg: 5.8, xag: 4.7, birthDate: new DateUTC(2004, 11, 7)}, {firstName: "M.A.", lastName: "Vignola", position: "DF/FW", gls: 1, ast: 2, mp: 17, ms: 10, xg: 1.0, xag: 2.1, birthDate: new DateUTC(1998, 2, 11)}, // etc... ]; tbl.populateTable({ tableData: data, sortOnKey: "position", ascending: false // sort by position descending (from front to back) }); ``` -------------------------------- ### common.newWindow Source: https://github.com/lindseysim/web-common/blob/release/README.md Creates a new, centered browser window with specified URL and options. ```APIDOC ## common.newWindow ### Description Creates a new, centered window. ### Method POST (implied, as it opens a new window) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **url** (String) - Required - URL for new window or an object literal with all parameters as properties. - **name** (String) - Optional - New window name. - **options** (Object) - Optional - Object containing window configuration. - **options.name** (String) - New window name may also be specified in the options. - **options.width** (Number) - Width in pixels. If not specified, defaults to 600. - **options.height** (Number) - Height in pixels. If not specified, defaults to 400. - **options.minimal** (Boolean) - Optional. If truthy, forces hiding of menubar, statusbar, and location – although with many modern browsers this has no effect as it is not allowed. - **options.options** (Object) - Optional. Additional window options (passed as `windowFeatures` parameter). Specify as key-value pairing. Will overwrite any options set by function or other parameters. - **options.error** (Callback) - Optional. Callback to run when the new window is detected to have been immediately closed (likely due to pop-up blocking). Given the *WindowProxy* returned by `window.open()`. ### Returns The [*WindowProxy*](https://developer.mozilla.org/en-US/docs/Glossary/WindowProxy) returned by *window*.**open**(). ``` -------------------------------- ### Manual Help Icon Creation Source: https://github.com/lindseysim/web-common/blob/release/README.md Manually creates a help icon by using an 'i' tag with the class 'cm-icon' and the content '?'. ```html ? ``` -------------------------------- ### Get Overlapping Values Between Two Arrays Source: https://github.com/lindseysim/web-common/blob/release/README.md Retrieves overlapping values between two arrays using strict equality. Can be called on an array instance or the Array global. ```javascript [1, 2, 3].getOverlaps([4, 5, 6]); // [] Array.getOverlaps([2, 4, 6, 8], [1, 2, 3, 5, 8]); // [2, 8] ``` -------------------------------- ### Array.prototype.remove Source: https://github.com/lindseysim/web-common/blob/release/README.md Removes all occurrences of a specified value from an array, creating a new array without modifying the original. Supports specifying a starting index and a limit for removals. ```APIDOC ## Array.prototype.remove ### Description Remove all instances of a value from an array. Value matching uses strict equality. Creates a copy of the array without modifying the original array. Set `index` to define the index at which to start indexing. Negatives are allowed to find a position from reverse. If the index is greater than or equal to the length of the array, the array is not searched and nothing is removed. Set `limit` to a positive value to define a limit to the number of times the value will be removed. Otherwise, the removal allowance is unlimited. ### Method `Array.prototype.remove(value[, index[, limit]])` ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript let a = [0, 1, 1, 2, 3, 5]; a.remove(1); ``` ### Response #### Success Response (200) `Array`: A new array with the specified value removed. #### Response Example ```json [0, 2, 3, 5] ``` ``` -------------------------------- ### common.polyfills() Source: https://github.com/lindseysim/web-common/blob/release/README.md Checks for and activates polyfills as needed. This function ensures that necessary polyfills are applied to the environment. ```APIDOC ## common.polyfills() ### Description Checks for and activates polyfills as needed. ### Method N/A (This is a utility function call) ### Endpoint N/A ### Parameters None ### Response N/A (Modifies the environment in place) ``` -------------------------------- ### common.ui.setModalAsLoading Source: https://github.com/lindseysim/web-common/blob/release/README.md Opens a modal dialog pre-configured for loading states. It accepts optional content and configuration options to customize the loading indicator. ```APIDOC ## common.ui.setModalAsLoading ### Description Opens a modal dialog with default values prepped for loading. As such, no options are required, but can be provided to overwrite defaults. ### Method `setModalAsLoading([content], [options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * `content` (String) - Optional. Modal content HTML. Defaults to "Loading..". * `options` (Object) - Optional. Configuration for the loading modal. * `options.id` (String) - Defaults to "modal-loading-dialog". * `options.showBackground` (Boolean) - Defaults to `true`. * `options.notExitable` (Boolean) - Defaults to `true`. * `options.hideCloser` (Boolean) - Defaults to `true`. * `options.addDetails` (Boolean) - If truthy, adds smaller subtext below the main modal content. Defaults to `true`. * `options.addDetailsText` (String) - The content for subtext below the main modal content, if `addDetails` is truthy. Defaults to "Please wait..". ### Request Example ```javascript common.ui.setModalAsLoading('Processing request...', { addDetailsText: 'This may take a moment.' }); ``` ### Response #### Success Response (200) * `Element`: The element of the modal content div (`.cm-modal-inner`). ``` -------------------------------- ### Open New Centered Window Source: https://github.com/lindseysim/web-common/blob/release/README.md Creates a new, centered browser window. Options can specify dimensions and other window features. ```javascript common.newWindow(url[, options]) common.newWindow(url, name[, options]) ``` -------------------------------- ### CommonTable.prototype.populateTable Source: https://github.com/lindseysim/web-common/blob/release/README.md Populates the table with data. The data is automatically mapped to columns based on the keys defined when adding columns. ```APIDOC ## CommonTable.prototype.populateTable Populates the table with data. The data, sent as an array of object literals/dictionaries, is mapped to the columns automatically with the `key` defined for each column. ### Parameters - **options** (Object) - Options for populating the table. (Specific options not detailed in source) ``` -------------------------------- ### Make AJAX Request (XMLHttpRequest) Source: https://github.com/lindseysim/web-common/blob/release/README.md Mimics jQuery.ajax() using XMLHttpRequest. Can be configured for asynchronous requests, data handling, and callbacks for success, error, and completion. Optionally returns a Promise. ```javascript common.ajax(params) ``` -------------------------------- ### Importing Web Common Modules with ES6 Source: https://github.com/lindseysim/web-common/blob/release/README.md Import the main common module, CSS styles, and the optional CommonTable class using ES6 syntax. Ensure proper style handlers are configured if using a build system like Webpack. ```javascript import common from '@lawrencesim/web-common'; import '@lawrencesim/web-common/style.css'; import CommonTable from '@lawrencesim/web-common/CommonTable'; ``` -------------------------------- ### Semantic String Comparison (Handling Negatives) Source: https://github.com/lindseysim/web-common/blob/release/README.md Demonstrates enabling negative number handling in `semanticCompare` for more accurate comparisons involving negative values. ```javascript "x-2".semanticCompare("x-1"); // 1 "x-2".semanticCompare("x-1", {handleNegative: true}); // -1 ``` -------------------------------- ### common.ajax Source: https://github.com/lindseysim/web-common/blob/release/README.md Mimics jQuery.ajax() for making HTTP requests, returning either XMLHttpRequest or a Promise. ```APIDOC ## common.ajax ### Description Mimics jQuery.ajax() function call with XMLHttpRequest. Can return XMLHttpRequest or a Promise. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **params** (Object) - Required - Configuration object for the AJAX request. - **params.url** (String) - The URL of the request. - **params.async** (Boolean) - Asynchronous. Defaults to `true`. - **params.method** (String) - Method for passing data. Defaults to "GET". - **params.data** (Object) - Optional dictionary of data to send with request. - **params.dataType** (String) - Type of returned data given by [`XMLHttpRequest.responseType`](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseType). - **params.success** (Callback) - Callback on success. Passes parameters of `XMLHttpRequest.responseText`, `XMLHttpRequest.statusText`, and the `XMLHttpRequest` instance itself. - **params.error** (Callback) - Callback on error. Passes parameters the `XMLHttpRequest` instance, `XMLHttpRequest.statusText`, and `XMLHttpRequest.responseText`. - **params.complete** (Callback) - Callback on completion (whether success or error). Passes parameters the `XMLHttpRequest` instance and `XMLHttpRequest.statusText`. - **params.user** (String) - Optional username, if necessitated. - **params.password** (String) - Optional password, if necessitated. - **params.promise** (Boolean) - Optionally return as Promise that resolves when the request resolves. ### Returns XMLHttpRequest or Promise on completion for the request. ``` -------------------------------- ### Date.prototype.toUTCDate Source: https://github.com/lindseysim/web-common/blob/release/README.md Converts date by first converting the time to UTC, then dropping any time information and assuming 12:00 AM UTC. ```APIDOC ## Date.prototype.toUTCDate() ### Description Converts date by first converting the time to UTC, then dropping any time information and assuming 12:00 AM UTC. ### Method Instance method ### Returns - `Date` - A new Date object representing the UTC date with time information dropped. ### Request Example ```javascript d = new Date(2019, 0, 1, 20); // Tue Jan 01 2019 20:00:00 GMT-0800 (Pacific Standard Time) d.toUTCDate(); // Tue Jan 01 2019 16:00:00 GMT-0800 (Pacific Standard Time) ``` ``` -------------------------------- ### common.ui.appendHelpIcon Source: https://github.com/lindseysim/web-common/blob/release/README.md Appends a help icon (?) with a tooltip to specified element(s). The icon is styled with the 'cm-icon' class. ```APIDOC ## common.ui.appendHelpIcon ### Description Add help icon to element(s) as (?) styled icon with tooltip. Icon element will be created with class *cm-icon*. ### Method `common.ui.appendHelpIcon(element, options)` `common.ui.appendHelpIcon(element, message[, direction[, style[, force]]])` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **element** (--): Element(s) to add help icon too. See *common*.[**getElementList**()](#common-getElementList) for evaluation of this parameter. * **options** (*Object*): Options object, or options may be specified in flat series of parameters. * **message** (*String*): Tooltip message/HTML. * **direction** (*String*): Direction of tooltip (defaults to top). * **style** (*Object*): Dictionary of inline style key-values for icon. * **force** (*Boolean*): If truthy, forces tooltip visible. * **message** (*String*): Tooltip message/HTML. * **direction** (*String*): Direction of tooltip (defaults to top). * **style** (*Object*): Dictionary of inline style key-values for icon. * **force** (*Boolean*): If truthy, forces tooltip visible. ### Request Example ```json { "example": "common.ui.appendHelpIcon(document.getElementById('myContainer'), { message: 'Need help?', direction: 'right', style: { color: 'blue' } })" } ``` ### Response #### Success Response (200) * None explicitly documented. #### Response Example ```json { "example": "No specific response example provided." } ``` ``` -------------------------------- ### Date.prototype.asUTCDate Source: https://github.com/lindseysim/web-common/blob/release/README.md Converts date by dropping any time information and assuming 12:00 AM UTC. Does not convert localtime to UTC and simply passes the time values as they exist. ```APIDOC ## Date.prototype.asUTCDate() ### Description Converts date by dropping any time information and assuming 12:00 AM UTC. This method does not convert localtime to UTC; it simply passes the time values as they exist. ### Method Instance method ### Returns - `Date` - A new Date object with time information dropped and set to 12:00 AM UTC. ### Request Example ```javascript d = new Date(2019, 0, 1, 20); // Tue Jan 01 2019 20:00:00 GMT-0800 (Pacific Standard Time) d.asUTCDate(); // Mon Dec 31 2018 16:00:00 GMT-0800 (Pacific Standard Time) ``` ``` -------------------------------- ### Element.prototype.center Source: https://github.com/lindseysim/web-common/blob/release/README.md Centers an HTML element on the screen using absolute positioning, taking into account window dimensions and scroll position. ```APIDOC ## Element.prototype.center ### Description Will center an element on screen using absolute positioning using `window` inner width/heights and offsets, adjusted by the scroll position. ### Method `Element.prototype.center()` ### Endpoint N/A ### Parameters N/A ### Request Example ```javascript myElem.center(); ``` ### Response N/A (This method modifies the element's style in place and does not return a value.) ``` -------------------------------- ### common.extend(obj, extend[, options]) Source: https://github.com/lindseysim/web-common/blob/release/README.md Copies a base object and extends it with new values. The original objects are not modified unless the 'modify' option is set to true. Supports deep copying and overwrite options. ```APIDOC ## common.extend(obj, extend[, options]) ### Description Copy given object and extended with new values. The passed objects are not modified in any way unless `modify` is set as truthy. ### Method N/A (This is a utility function call) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **obj** (*Object*): Base object. - **extend** (*Object*): Object of extensions to the copy of the base object. - **options** (*Object*): Options object, or options may be specified in flat series of parameters. - **overwrite** (*Boolean*): Unless true, items in `extend` matching existing values in `obj` by key are not copied over. - **allowOverwrite** (*Boolean*): Same as above. - **deep** (*Boolean*): If true, all values are copied via `structuredClone()` or, as a fallback, `JSON.parse(JSON.stringify())`. - **deepCopy** (*Boolean*): Same as above. - **modify** (*Boolean*): If true, the input base object (`obj`) is modified directly, instead of cloning. - **modifyObj** (*Boolean*): Same as above. ### Returns The object with extended values (if `modify` is falsy, this is a new object). ### Example ```javascript let a = {x: 1, y: 2}; // below returns {x: 1, y: 2, p: 10, q: 20} common.extend(a, {p: 10, q: 20}); // the first below will not overwrite values for x and y, to do so, set the overwrite option to true common.extend(a, {x: 10, y: 20}); common.extend(a, {x: 10, y: 20}, {overwrite: true}); ``` ``` -------------------------------- ### DateUTC Source: https://github.com/lindseysim/web-common/blob/release/README.md Creates a datetime, forced as UTC. Month is to be indicated as a number from 1-12. ```APIDOC ## DateUTC(year, month[, day[, hour[, min[, sec]]]]) ### Description Creates a datetime, forced as UTC. Month is to be indicated as a number from 1-12 (unlike traditional Date constructor as 0-11). ### Parameters #### Path Parameters - **year** (number) - Required - The year. - **month** (number) - Required - The month (1-12). - **day** (number) - Optional - The day. - **hour** (number) - Optional - The hour. - **min** (number) - Optional - The minute. - **sec** (number) - Optional - The second. ### Returns - `Date` - A new Date object set to UTC. ``` -------------------------------- ### Create Dropdown Menu Source: https://github.com/lindseysim/web-common/blob/release/README.md Creates a dropdown menu on a specified element. The menu structure is defined by an array of objects, supporting nested submenus. Use this for interactive navigation or action menus. ```javascript common.ui.createDropdown("#menu", [ { id: "menu-btn-1", text: "Homepage", href: "index.html", style: {"font-weight": "bold"}, onClick: () => console.log("menu item 1 clicked") }, { id: "submenu", text: "Totally Work Related", style: {"font-style": "italic"}, menu: [ {text: "Business Stuff", href: "https://youtube.com"}, {text: "Project Stuff", href: "https://reddit.com"} ] } ] ); ``` -------------------------------- ### CommonTable Constructor Source: https://github.com/lindseysim/web-common/blob/release/README.md Creates a new CommonTable instance. It can be initialized with options or directly with table properties like ID, class, and container. ```APIDOC ## CommonTable Constructor Creates new CommonTable. The table will be given the class of *cm-table*, more classes can be appended through the options. Arguments may be given flat or as key-values within a single object literal argument. ### Parameters #### Options Object - **tableId** (String) - Table ID - **tableClass** (String | String[]) - Table classname (use array to add multiple) - **container** (Element | String) - Element or element query selector to append table to ``` -------------------------------- ### common.ui.setModal / common.ui.openModal Source: https://github.com/lindseysim/web-common/blob/release/README.md Creates a new modal dialog or closes an existing one. The `openModal` function is an alias for `setModal` with the `visible` parameter defaulted to true. Various options can customize the modal's appearance and behavior. ```APIDOC ## common.ui.setModal / common.ui.openModal ### Description Creates a new modal dialog (or closes, if `visible` is falsy). Function `openModal()` is the same with `visible` defaulted to *true*. ### Method `setModal(visible, content, [options])` `openModal(content, [options])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * `visible` (Boolean) - Whether to open or close modal. * `content` (String) - Modal content HTML. * `options` (Object) - Optional configuration for the modal. * `options.id` (String) - Id of inner modal dialog element. * `options.showBackground` (Boolean) - If truthy, creates a semi-transparent background over window. * `options.notExitable` (Boolean) - If truthy, prevents modal from closing on outside click. * `options.hideCloser` (Boolean) - If truthy, does not apply the automatically placed "X" to close dialog. * `options.onClose` (Callback) - Callback to run on modal being closed. ### Request Example ```javascript common.ui.openModal('

Hello World

', { id: 'my-modal', showBackground: true, notExitable: false }); ``` ### Response #### Success Response (200) * `Element`: The element of the modal content div (`.cm-modal-inner`). ``` -------------------------------- ### CommonTable.prototype.populateTable Source: https://github.com/lindseysim/web-common/blob/release/README.md Populates and redraws the table with the provided data. It accepts an array of objects for table data and optional parameters for sorting. ```APIDOC ## CommonTable.prototype.populateTable ### Description Populates and redraws the table with the provided data. It accepts an array of objects for table data and optional parameters for sorting. ### Method Signature `CommonTable.prototype.populateTable(tableData[, sortOnKey[, ascending]])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **tableData** (*Object[]*) - Required - Array of objects, representing data by row. Data is not stored to object or dynamically bound in any way. To update table, must be redrawn, passing the updated data array. * **sortOnKey** (*String*) - Optional - Key to sort on. * **ascending** (*Boolean*) - Optional - If sorting, whether ascending or descending order. ### Request Example ```javascript let tbl = new CommonTable("my-table-id", "my-table-class"); tbl.appendTo(document.body); // ... column definitions ... let data = [ {firstName: "Claire", lastName: "Emslie", position: "FW", gls: 7, ast: 2, mp: 26, ms: 24, xg: 7.7, xag: 3.7, birthDate: new DateUTC(1994, 3, 8)}, // ... more data ]; tbl.populateTable({ tableData: data, sortOnKey: "position", ascending: false }); ``` ### Response #### Success Response * **self** (*Object*) - Returns the CommonTable instance for chaining functions. #### Response Example (Chaining implies the instance is returned, no specific JSON example for this return value) ``` -------------------------------- ### Manual Tooltip Application Source: https://github.com/lindseysim/web-common/blob/release/README.md Manually applies tooltips by adding specific classes and attributes to an element. Use classes like 'cm-tooltip-left', 'cm-tooltip-top', etc., and the 'cm-tooltip-msg' attribute for the message. ```html
...
``` -------------------------------- ### common.ui.addTooltip Source: https://github.com/lindseysim/web-common/blob/release/README.md Adds a hover tooltip to specified element(s). Tooltips can be configured with a message, direction, and force visibility option. ```APIDOC ## common.ui.addTooltip ### Description Adds hover tooltip to element(s). Elements will be created with classes prefixed by *cm-tooltip*. ### Method `common.ui.addTooltip(element, options)` `common.ui.addTooltip(element, message[, direction[, force]])` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * **element** (--): Element(s) to add tooltip to. See *common*.[**getElementList**()](#common-getElementList) for evaluation of this parameter. * **options** (*Object*): Options object, or options may be specified in flat series of parameters. * **message** (*String*): Tooltip message/HTML. * **direction** (*String*): Direction of tooltip (defaults to top). * **force** (*Boolean*): If truthy, forces tooltip visible. * **message** (*String*): Tooltip message/HTML. * **direction** (*String*): Direction of tooltip (defaults to top). * **force** (*Boolean*): If truthy, forces tooltip visible. ### Request Example ```json { "example": "common.ui.addTooltip(document.getElementById('myElement'), { message: 'This is a tooltip', direction: 'bottom' })" } ``` ### Response #### Success Response (200) * None explicitly documented. #### Response Example ```json { "example": "No specific response example provided." } ``` ``` -------------------------------- ### common.animate Source: https://github.com/lindseysim/web-common/blob/release/README.md Mimics jQuery.animate() using CSS transitions for element animations. ```APIDOC ## common.animate ### Description Mimics jQuery.animate() function using CSS transitions by first applying a [transition](https://developer.mozilla.org/en-US/docs/Web/CSS/transition) property for the requisite CSS properties to be applied, then, after a short delay (5 ms), applying the properties. All this is done as modifications to the element's inline styles, and will thus overwrite any existing inline styles and will be subject to any CSS rule overrides (such as an existing, applicable CSS rule with the `!imporant` flag). ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (Object) - Required - Options for the animation. - **element** (Element) - Required - The Element to animate. - **properties** (Object) - Required - The CSS properties to animate. - **duration** (Number) - Required - The duration of the animation in milliseconds. ### Returns Promise ``` -------------------------------- ### Number.prototype.stringFormat Source: https://github.com/lindseysim/web-common/blob/release/README.md Formats a number into a string with dynamic precision based on its value, with options to customize zero formatting and minimum value thresholds. ```APIDOC ## Number.prototype.stringFormat ### Description Basically wraps *Number*.prototype.[**addCommas**()](#common-numberAddCommas) with heuristic guessing on precision to use. The `minimum` parameter rounds any value whose absolute value is less than this to zero. The `zeroFormat` parameter can be used to customize how zero values are printed. By default it is "0.0". Current heuristics are: * Evaluation to zero is always written in the zero format (default "0.0") * <0.01 as scientific notation with three significant figures * <0.1 as scientific notation with two significant figures * <0.3 as number with three decimal places * <1.0 as number with two decimal places * <100 as number with one decimal place * ≥100 as number with no decimal places ### Method `Number.prototype.stringFormat([minimum=0.001[, zeroFormat="0.0"]])` ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript (1.2345e7).stringFormat(); ``` ### Response #### Success Response (200) `string`: The formatted number string. #### Response Example ```json '12345000' ``` ``` -------------------------------- ### common.ui.createDropdown Source: https://github.com/lindseysim/web-common/blob/release/README.md Creates a dropdown menu attached to a specified element. The menu's structure and behavior are defined by a JSON array of object literals, supporting nested submenus and click actions. ```APIDOC ## common.ui.createDropdown ### Description Create a dropdown menu on an element. *menu* parameter is an array of object literals defining the menu. The parameters `id`, `class`, `style`, and `html`/`text`, if they exist, are applied. For functionality, either add `href` and optionally `target` parameters or supply a callback to an `onClick` parameter. To create a submenu, simply add a `menu` parameter with the same nested structure. Elements with be created with classes prefixed by "cm-dropdown". ### Method common.ui.createDropdown ### Parameters #### Path Parameters - **element** (--): Element(s) to add dropdown to. See *common*.[**getElementList**()](#common-getElementList) for evaluation of this parameter. - **menu** (*Object*[]): JSON map of menu ### Request Example ```javascript common.ui.createDropdown("#menu", [ { id: "menu-btn-1", text: "Homepage", href: "index.html", style: {"font-weight": "bold"}, onClick: () => console.log("menu item 1 clicked") }, { id: "submenu", text: "Totally Work Related", style: {"font-style": "italic"}, menu: [ {text: "Business Stuff", href: "https://youtube.com"}, {text: "Project Stuff", href: "https://reddit.com"} ] } ] ); ``` ``` -------------------------------- ### Append Help Icon with Tooltip Source: https://github.com/lindseysim/web-common/blob/release/README.md Appends a help icon with an associated tooltip to element(s). The icon is styled with the 'cm-icon' class. Options can be provided as an object or individual parameters. ```javascript common.ui.appendHelpIcon(element, options); common.ui.appendHelpIcon(element, message, direction, style, force); ``` -------------------------------- ### CommonTable.prototype.prependTo Source: https://github.com/lindseysim/web-common/blob/release/README.md Prepends the table to a specified container element. This method is chainable. ```APIDOC ## CommonTable.prototype.prependTo Prepends table to element. ### Parameters - **container** (Element) - Element to prepend table in ### Returns *self* for chaining functions. ``` -------------------------------- ### common.getElementList(input) Source: https://github.com/lindseysim/web-common/blob/release/README.md Given an input, converts it into an array of Elements (or objects derived from the Element prototype). Supports NodeLists, arrays, iterables, jQuery objects, and strings. ```APIDOC ## common.getElementList(input) ### Description Given an input, converts it into an array of [Elements](https://developer.mozilla.org/en-US/docs/Web/API/Element) (or objects derived from the Element prototype). ### Method N/A (This is a utility function call) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **input** (--): Input to filter for and/or convert to an array of *Elements*. ### Response #### Success Response - **Element[]** (Element[]): An array of Element objects. ### Returns * If a *NodeList*, array, or other iterable is provided, converts to an array via *Array*.**from**(), then filters for elements that are derived from the *Element* prototype. * If a *jQuery* object is provided, returns array given by calling [**get**()](https://api.jquery.com/get/) on it. * If a string is provided, returns result of *document*.[**querySelectorAll**()](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll), using the string as the selector, converted into an array. * Otherwise, wraps the input in an array, then filters for elements that are derived from the *Element* prototype. ``` -------------------------------- ### Date.prototype.toUTC Source: https://github.com/lindseysim/web-common/blob/release/README.md Creates a new DateUTC using the UTC datetime of this object, converted from localtime. This function is mostly symbolic and does not perform any actual time conversion. ```APIDOC ## Date.prototype.toUTC() ### Description Creates a new `DateUTC` using the UTC datetime of this object, converted from localtime. As printing is always done in localtime, this conversion is mostly symbolic and the function is left in for completeness but does not perform any actual time conversion. ### Method Instance method ### Returns - `Date` - A new Date object representing the UTC equivalent. ### Request Example ```javascript d = new Date(2019, 0, 1, 20); // Tue Jan 01 2019 20:00:00 GMT-0800 (Pacific Standard Time) d.toUTC(); // Tue Jan 01 2019 20:00:00 GMT-0800 (Pacific Standard Time) ``` ``` -------------------------------- ### Element.prototype.css Source: https://github.com/lindseysim/web-common/blob/release/README.md Applies inline CSS styles to an HTML element, similar to jQuery's `css()` function. Styles can be set individually or as a batch using an object. ```APIDOC ## Element.prototype.css ### Description Much like the JQuery **css**() function, sets inline style, either as style name and value provided as strings, or as a dictionary-like object of style names and values and key-value pairs. ### Method `Element.prototype.css(style[, value])` or `Element.prototype.css(stylesObject)` ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```javascript myElem.css('text-align', 'center'); myElem.css({ 'text-align': 'center', 'text-decoration': 'underline' }); ``` ### Response N/A (This method modifies the element in place and does not return a value.) ``` -------------------------------- ### String.prototype.capitalize Source: https://github.com/lindseysim/web-common/blob/release/README.md Capitalizes the first letter of each word in a string. Words are delineated by whitespace by default, but custom break characters can be provided. ```APIDOC ## String.prototype.capitalize ### Description Capitalizes the first letter of each word in a string. Words are delineated by whitespace by default, but custom break characters can be provided. ### Method `String.prototype.capitalize([breaks])` ### Parameters * **breaks** (string|Array, optional) - An array or string of characters to use as word delimiters. ### Returns * `string` - The string with each word capitalized. ### Examples ```javascript "web common".capitalize(); // "Web Common" "@lawrencesim/web-common".capitalize() // "@lawrencesim/web-common" "@lawrencesim/web-common".capitalize("@/-") // "@Lawrencesim/Web-Common" ``` ``` -------------------------------- ### Date.prototype.asUTC Source: https://github.com/lindseysim/web-common/blob/release/README.md Converts datetime to UTC assuming the time given (assumed localtime) was actually meant as UTC time. The date/time in localtime will be kept as the UTC date/time, only changing the timezone to UTC. ```APIDOC ## Date.prototype.asUTC() ### Description Converts datetime to UTC assuming the time given (assumed localtime) was actually meant as UTC time. This method does not convert localtime to UTC; it simply passes the time values as they exist, changing the timezone to UTC. ### Method Instance method ### Returns - `Date` - A new Date object representing the UTC equivalent. ### Request Example ```javascript d = new Date(2019, 0, 1, 20); // Tue Jan 01 2019 20:00:00 GMT-0800 (Pacific Standard Time) d.asUTC(); // Tue Jan 01 2019 12:00:00 GMT-0800 (Pacific Standard Time) ``` ``` -------------------------------- ### Center an Element on Screen Source: https://github.com/lindseysim/web-common/blob/release/README.md Centers an element on the screen using absolute positioning, calculating position based on window dimensions and scroll offsets. ```javascript myElem.css({ position: "absolute", top: (window.innerHeight - this.offsetHeight) / 2 + window.scrollY, left: (window.innerWidth - this.offsetWidth) / 2 + window.scrollX }); ``` -------------------------------- ### Element.prototype.setAttributes Source: https://github.com/lindseysim/web-common/blob/release/README.md Sets multiple attributes on an HTML element simultaneously using a key-value pair object. ```APIDOC ## Element.prototype.setAttributes ### Description Sets multiple attributes (given as a dictionary-like object of key-value pairs) at once. ### Method `Element.prototype.setAttributes(attrs)` ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **attrs** (object) - Required - An object where keys are attribute names and values are the attribute values. ### Request Example ```javascript myInput.setAttributes({ type: 'text', name: 'username', minlength: 6 }); ``` ### Response N/A (This method modifies the element in place and does not return a value.) ``` -------------------------------- ### Date.prototype.daysInMonth Source: https://github.com/lindseysim/web-common/blob/release/README.md Returns the number of days in the month for the current date. ```APIDOC ## Date.prototype.daysInMonth() ### Description Returns the number of days in the month for this date. ### Method Instance method ### Returns - `number` - The number of days in the month. ``` -------------------------------- ### Semantic String Comparison (Basic) Source: https://github.com/lindseysim/web-common/blob/release/README.md Compares strings semantically, treating numeric parts as numbers rather than characters. Returns -1, 0, or 1. ```javascript "x01x02".semanticCompare("x1x2"); // 0 is semantically equal "x20".semanticCompare("x1"); // 1 comes after "x9".semanticCompare("x999"); // -1 comes before "b1".semanticCompare("a2"); // 1 comes after ``` -------------------------------- ### Date.prototype.monthOfYear Source: https://github.com/lindseysim/web-common/blob/release/README.md Returns the month of the year as a 1-12 number. ```APIDOC ## Date.prototype.monthOfYear() ### Description Returns the month of the year as a 1-12 number (as opposed to 0-11 for `getMonth()`). ### Method Instance method ### Returns - `number` - The month of the year (1-12). ``` -------------------------------- ### common.getElement(element) Source: https://github.com/lindseysim/web-common/blob/release/README.md Given an input, returns an Element (or object derived from the Element prototype) as best determined from what is provided. Handles various input types including Elements, jQuery objects, arrays, NodeLists, and strings. ```APIDOC ## common.getElement(element) ### Description Given an input, returns an [*Element*](https://developer.mozilla.org/en-US/docs/Web/API/Element) (or object derived from the *Element* prototype) as best determined from what is provided. ### Method N/A (This is a utility function call) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **element** (--): Input to filter for and/or convert to *Element*. ### Response #### Success Response - **Element** (Element): Returns the determined Element object. ### Returns * If a single *Element* is provided, simply returns it. * If a *jQuery* object is provided, returns first *Element* given by calling [**get**()](https://api.jquery.com/get/) on it. * If an array is provided, returns the first item this is an *Element* or *undefined*. * If a *NodeList* or other iterable is provided, returns value of **next**() or *null* if done. * If string is provided, returns result of *document*.[**querySelector**()](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector) using the string as the selector. * If none of the above apply, returns *undefined*. ``` -------------------------------- ### Extend Object In-Place Source: https://github.com/lindseysim/web-common/blob/release/README.md Extends an object by merging properties from other objects. Use 'overwrite: true' and 'modify: true' to modify the original object in place. ```javascript console.log(a); // {x: 1, y: 2} // but the below will overwrite a in place common.extend(a, {x: 10, y: 20}, {overwrite: true, modify: true}); console.log(a); // {x: 10, y: 20} ```