### 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('