### Install FlowerKit Source: https://github.com/yuri-moskvin/flowerkit/blob/main/README.md Install the package using npm. ```bash npm i @web3r/flowerkit ``` -------------------------------- ### Install dependencies Source: https://github.com/yuri-moskvin/flowerkit/blob/main/CONTRIBUTING.md Use this command to install the locked dependency versions after cloning the repository. ```bash npm ci ``` -------------------------------- ### Conventional commit examples Source: https://github.com/yuri-moskvin/flowerkit/blob/main/CONTRIBUTING.md Examples of commit messages following the Conventional Commits format. ```text feat(fn): add cancelable delay utility fix(dom): preserve nodes during wrapper cleanup docs(arr): clarify grouping examples ``` -------------------------------- ### Perform HTTP GET request with getFromServer Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/net.md Executes a basic GET request to retrieve user data. ```ts const user = await getFromServer<{ userId: number }>({ url: "/api/user?id=1", method: "GET" }); ``` -------------------------------- ### Basic and Debounced Window Resize Handling Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Examples showing simple resize logging and a debounced implementation for performance-sensitive tasks. ```ts onWindowResize(() => console.log("resized")); ``` ```ts // Recalculate a responsive grid after resize with a 200 ms debounce const resize = onWindowResize(() => updateGridColumns(window.innerWidth), 200); resize.removeListener(); ``` -------------------------------- ### getStrWithCapitalized Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/str.md Gets a string with uppercase first letter. ```APIDOC ## getStrWithCapitalized(str: string) -> string ### Description Gets a string with the first letter capitalized. ### Parameters - **str** (string) - Required - Source string ### Returns - (string) - String with first character uppercased ``` -------------------------------- ### getThrottledFn Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/fn.md Gets a throttled function with specific delay. ```APIDOC ## getThrottledFn ### Description Gets a throttled function with specific delay. Returns a throttled function with cancel, flush, and pending controls. ### Signature `getThrottledFn any>(func: T, delay?: number) => TThrottledFn` ### Parameters - **func** (function) - Required - The function to throttle. - **delay** (number) - Optional - Delay in ms, 1000 by default. ``` -------------------------------- ### getStrWithThousandSeparator Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/str.md Gets a formatted string with thousands separators. ```APIDOC ## getStrWithThousandSeparator(num: number, separator?: string) -> string ### Description Gets a formatted string with thousands separators in the integer part of a number. ### Parameters - **num** (number) - Required - Source number - **separator** (string) - Optional - Separator to insert between each group of three digits ### Returns - (string) - Formatted string ``` -------------------------------- ### getStorage Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/user.md Safely gets browser local or session storage. Returns null during SSR or when storage access is blocked. ```APIDOC ## getStorage(type?: TStorageType) -> Storage | null ### Description Safely gets browser local or session storage. Returns null during SSR or when storage access is blocked. ### Parameters - **type** (TStorageType) - Optional - Storage type ### Returns - **Storage | null** - Browser storage when available ``` -------------------------------- ### getPureDate Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/date.md Gets a new Date instance without time (hours, minutes, seconds, and milliseconds). ```APIDOC ## getPureDate(date?: any) => Date | null ### Description Returns a new Date instance with time components set to zero. ### Parameters - **date** (any) - Optional - Source date ### Returns - **Date | null** - New Date instance or null for an invalid value ``` -------------------------------- ### getRandomIntFromInterval Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/num.md Gets a random integer between min and max (inclusive). ```APIDOC ## getRandomIntFromInterval ### Description Gets a random integer between min and max (inclusive). ### Signature `(min?: number, max?: number) => number` ### Parameters - **min** (number) - Min value - **max** (number) - Max value ### Returns - **number** - Random integer in [min, max] ``` -------------------------------- ### Build the project Source: https://github.com/yuri-moskvin/flowerkit/blob/main/CONTRIBUTING.md Run the build command to perform checks and generate package output and API documentation. ```bash npm run build ``` -------------------------------- ### onWindowLoad Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Runs a callback when the window load event fires. ```APIDOC ## onWindowLoad(cb, isAutoInit?) ### Description Runs a callback when the window load event fires. Executes immediately if already loaded. ### Parameters - **cb** ((e?: Event) => void) - Required - Callback to run on load - **isAutoInit** (boolean) - Optional - Attach immediately ### Example ```ts const { removeListener } = onWindowLoad(() => console.log("Loaded")); ``` ``` -------------------------------- ### Run verification commands Source: https://github.com/yuri-moskvin/flowerkit/blob/main/CONTRIBUTING.md Execute these commands to verify the package, coverage, and build before opening a pull request. ```bash npm run build npm run test:coverage npm run verify:size npm run verify:package ``` -------------------------------- ### Checking bundle sizes Source: https://github.com/yuri-moskvin/flowerkit/blob/main/README.md Commands to verify current bundle sizes and enforce regression budgets. ```bash npm run size ``` ```bash npm run verify:size ``` -------------------------------- ### getMinFromArr Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/num.md Gets min number from an array of numbers. ```APIDOC ## getMinFromArr ### Description Gets min number from an array of numbers. ### Signature `(arr: number[]) => number` ### Parameters - **arr** (number[]) - Source array of numbers (must be non-empty) ### Returns - **number** - Minimum value ``` -------------------------------- ### onWindowResize(cb, delay?, isAutoInit?) Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Registers a callback to be executed when the window is resized. Supports optional debouncing and automatic initialization. ```APIDOC ## onWindowResize ### Description Runs a callback on window resize. If `delay` is provided, the callback is debounced. ### Signature `onWindowResize(cb: (e: Event) => void, delay?: number, isAutoInit?: boolean) => { handler: (e: Event) => void; addListener: () => void; removeListener: () => void; }` ### Parameters - **cb** (function) - Required - Resize callback function. - **delay** (number) - Optional - Debounce delay in ms; if falsy, the callback is executed immediately. - **isAutoInit** (boolean) - Optional - If true, attaches the listener immediately. ### Returns - **handler** (function) - The event handler function. - **addListener** (function) - Function to attach the listener. - **removeListener** (function) - Function to detach the listener. ### Example ```ts // Basic usage onWindowResize(() => console.log("resized")); // With debounce const resize = onWindowResize(() => updateGridColumns(window.innerWidth), 200); resize.removeListener(); ``` ``` -------------------------------- ### getMaxFromArr Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/num.md Gets max number from an array of numbers. ```APIDOC ## getMaxFromArr ### Description Gets max number from an array of numbers. ### Signature `(arr: number[]) => number` ### Parameters - **arr** (number[]) - Source array of numbers (must be non-empty) ### Returns - **number** - Maximum value ``` -------------------------------- ### List utility files Source: https://github.com/yuri-moskvin/flowerkit/blob/main/AGENTS.md List all files within the src directory. ```bash rg --files src ``` ```powershell Get-ChildItem -Recurse -File src | ForEach-Object { $_.FullName } ``` -------------------------------- ### getIndexOfEl Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/dom.md Gets the index of a node relative to its siblings. ```APIDOC ## getIndexOfEl(el: HTMLElement | Element | Node | Document) => number ### Description Calculates the index of a node relative to its siblings. ### Parameters - **el** (HTMLElement | Element | Node | Document) - Required - The DOM element to find the index for. ``` -------------------------------- ### getElSiblings Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/dom.md Gets an array of all siblings of a given node. ```APIDOC ## getElSiblings(el: HTMLElement) => ChildNode[] ### Description Gets an array of all siblings of the provided DOM node. ### Parameters - **el** (HTMLElement) - Required - The target node to find siblings for. ``` -------------------------------- ### onDOMReady Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Runs a callback when the DOM is ready (DOMContentLoaded). If already ready, executes immediately. ```APIDOC ## onDOMReady ### Description Runs a callback when the DOM is ready (`DOMContentLoaded`). If already ready, executes immediately. ### Signature `onDOMReady(cb: (e?: Event | undefined) => void, isAutoInit?: boolean | undefined) => { handler: (e?: Event | undefined) => void; addListener: () => void; removeListener: () => void; }` ### Parameters - **cb** (Function) - Callback to run on DOM ready - **isAutoInit** (boolean | undefined) - Attach immediately ``` -------------------------------- ### getUnion Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/arr.md Gets union Array of two given Arrays. ```APIDOC ## getUnion ### Description Gets union Array of two given Arrays. ### Signature `getUnion(arr1: T[], arr2: T[]) => T[]` ### Parameters - **arr1** (T[]) - First source Array - **arr2** (T[]) - Second source Array ``` -------------------------------- ### Run development checks Source: https://github.com/yuri-moskvin/flowerkit/blob/main/CONTRIBUTING.md Execute these commands to run linting, type checking, and tests. ```bash npm run lint npm run typecheck npm test ``` -------------------------------- ### getIntersection Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/arr.md Gets Array of intersection of two given Arrays. ```APIDOC ## getIntersection ### Description Gets Array of intersection of two given Arrays. ### Signature `getIntersection(arr1: T[], arr2: T[]) => T[]` ### Parameters - **arr1** (T[]) - First source Array - **arr2** (T[]) - Second source Array ``` -------------------------------- ### on Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Creates a managed event listener with explicit add and remove controls. ```APIDOC ## on ### Description Creates a managed event listener with explicit add and remove controls. ### Signature `on(target: EventTarget, type: string, callback: (event: TEvent) => void, options?: boolean | AddEventListenerOptions, isAutoInit?: boolean) => TOnControls` ### Parameters - **target** (EventTarget) - Event target - **type** (string) - Event type - **callback** (Function) - Event callback - **options** (boolean | AddEventListenerOptions) - Native listener options - **isAutoInit** (boolean) - Attach immediately ``` -------------------------------- ### Importing Network Utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/net.md Import the necessary functions and types from the @web3r/flowerkit/net package. ```ts // import functions import { getExternalScript, getFormDataFromObj, getUrlWithQueryParams, getFromServer, getObjFromFormData, getQueryParams, getQueryParam } from "@web3r/flowerkit/net"; // import types import type { TGetExternalScriptArgs, TGetExternalScriptReturn, TGetFormDataFromObjArgs, TGetFormDataFromObjReturn, TGetUrlWithQueryParamsArgs, TGetUrlWithQueryParamsReturn, TGetFromServerMethod, TGetFromServerErrorKind, TGetFromServerError, TGetFromServerArgs, TGetFromServerReturn, TGetObjFromFormDataArgs, TGetObjFromFormDataReturn, TQueryParamsInput, TGetQueryParamsArgs, TGetQueryParamsReturn, TGetQueryParamArgs, TGetQueryParamReturn } from "@web3r/flowerkit/net"; ``` -------------------------------- ### Run development and verification tasks Source: https://github.com/yuri-moskvin/flowerkit/blob/main/README.md Standard sequence of commands to run before submitting a pull request. ```bash npm run lint npm run typecheck npm test npm run build npm run verify:package ``` -------------------------------- ### getDiff Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/arr.md Gets an array representing the difference between two given arrays. ```APIDOC ## getDiff ### Description Gets an array representing the difference between two given arrays. ### Signature `getDiff(arr1: T[], arr2: T[]) => T[]` ### Parameters - **arr1** (T[]) - First source array - **arr2** (T[]) - Second source array ``` -------------------------------- ### Get Element Index Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/dom.md Determine the index of a node relative to its siblings. ```typescript //
    //
  • A
  • // Text node //
  • B
  • //
  • C
  • //
getIndexOfEl(document.querySelector("#c")!) // 2 ``` ```typescript // Find the index of a clicked tab among its element siblings tabs.addEventListener("click", (event) => { if (event.target instanceof Element) selectTab(getIndexOfEl(event.target)); }); ``` -------------------------------- ### Creating Typed Storage Namespaces Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/user.md Initializes a JSON-backed storage controller with optional namespace and error handling. ```ts const settings = createStorage<{ theme: "light"|"dark" }>({ namespace: "app" }); settings.set("theme", "dark"); ``` ```ts // Persist a typed shopping cart and restore it with a fallback const cartStorage = createStorage<{ items: Array<{ id: string; quantity: number; }> }>({ namespace: "shop", }); cartStorage.set("items", cartItems); const savedItems = cartStorage.get("items", []); ``` -------------------------------- ### getAsyncMap Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/arr.md Gets an aggregated result of an async operation for each element of a given array. ```APIDOC ## getAsyncMap ### Description Gets an aggregated result of an async operation for each element of a given array. ### Signature `getAsyncMap(arr: T[], callback: (value: T, index: number, array: T[]) => U or Promise) => Promise` ### Parameters - **arr** (T[]) - Source array - **callback** (function) - Callback function (can be sync or async) ``` -------------------------------- ### Handle window load events with onWindowLoad Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Executes a callback when the window load event fires, or immediately if the window is already loaded. ```ts const { removeListener } = onWindowLoad(() => console.log("Loaded")); ``` ```ts // Hide a loading screen after images and stylesheets finish loading onWindowLoad(() => document.querySelector("[data-loader]")?.remove()); ``` -------------------------------- ### getDateDiff Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/date.md Gets the signed elapsed-time difference (left - right) in a selected unit. ```APIDOC ## getDateDiff(left: TDateInput, right: TDateInput, unit?: TDateDiffUnit) => number ### Description Calculates the signed difference between two dates in the specified unit. ### Parameters - **left** (TDateInput) - Required - Left date - **right** (TDateInput) - Required - Right date - **unit** (TDateDiffUnit) - Optional - Unit of time for the difference ### Returns - **number** - Signed difference, which may be fractional ``` -------------------------------- ### Importing User Utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/user.md Import necessary functions and types from the @web3r/flowerkit/user package. ```ts // import functions import { copyToClipboard, getStorage, createStorage, setCookie, deleteCookie, getCookie, getScrollbarWidth, isAdblock, isMobileDevice, isTouchDevice } from "@web3r/flowerkit/user"; // import types import type { TCopyToClipboardArgs, TCopyToClipboardReturn, TStorageType, TGetStorageArgs, TGetStorageReturn, TStorageController, TCreateStorageArgs, TCreateStorageReturn, TSetCookieArgs, TSetCookieReturn, TDeleteCookieArgs, TDeleteCookieReturn, TGetCookieArgs, TGetCookieReturn, TGetScrollbarWidthArgs, TGetScrollbarWidthReturn, TIsAdblockArgs, TIsAdblockReturn, TIsMobileDeviceArgs, TIsMobileDeviceReturn, TIsTouchDeviceArgs, TIsTouchDeviceReturn } from "@web3r/flowerkit/user"; ``` -------------------------------- ### getLastFromIterable Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/arr.md Gets the last element of an iterable object such as Array, NodeList, HTMLCollection, etc. ```APIDOC ## getLastFromIterable ### Description Gets the last element of an iterable object such as Array, NodeList, HTMLCollection, etc. ### Signature `getLastFromIterable(obj: ArrayLike and Iterable) => T or null` ``` -------------------------------- ### Importing Object Utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/obj.md Import the necessary functions and types from the @web3r/flowerkit/obj package. ```typescript // import functions import { getAllSamePropsFromObj, getCopyOfObj, getMapFromObj, getMergedObj, getObjFromFormData, getObjLength, getObjValueByPath, getObjWithFallbacks, getObjWithoutUndefined, getObjWithOmittedProps, getObjWithPickedProps, isObjEmpty, isObjEqual, isObjHasOwnProp, isObjPromise, isObjPrototypeOf } from "@web3r/flowerkit/obj"; // import types import type { TGetAllSamePropsFromObjArgs, TGetAllSamePropsFromObjReturn, TGetCopyOfObjArgs, TGetCopyOfObjReturn, TGetMapFromObjArgs, TGetMapFromObjReturn, TGetMergedObjArgs, TGetMergedObjReturn, TGetObjFromFormDataArgs, TGetObjFromFormDataReturn, TGetObjLengthArgs, TGetObjLengthReturn, TObjPath, TGetObjValueByPathArgs, TGetObjValueByPathReturn, TGetObjWithFallbacksArgs, TGetObjWithFallbacksReturn, TGetObjWithoutUndefinedArgs, TGetObjWithoutUndefinedReturn, TGetObjWithOmittedPropsArgs, TGetObjWithOmittedPropsReturn, TGetObjWithPickedPropsArgs, TGetObjWithPickedPropsReturn, TIsObjEmptyArgs, TIsObjEmptyReturn, TIsObjEqualArgs, TIsObjEqualReturn, TIsObjHasOwnPropArgs, TIsObjHasOwnPropReturn, TIsObjPromiseArgs, TIsObjPromiseReturn, TIsObjPrototypeOfArgs, TIsObjPrototypeOfReturn } from "@web3r/flowerkit/obj"; ``` -------------------------------- ### Get Element Siblings Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/dom.md Retrieve an array of sibling nodes for a given DOM element. ```typescript // How to get all siblings of `li` DOM-element with specific ID? //
    //
  • One
  • //
  • Two
  • //
  • Three
  • //
      const secondItem = document.getElementById("item2"); getElSiblings(secondItem).filter(item => item !== secondItem) // [ li#item1, li#item3 ] ``` ```typescript // Remove the active state from sibling tabs before selecting a new tab getElSiblings(activeTab).forEach((tab) => tab.classList.remove("active")); ``` -------------------------------- ### Execute project maintenance commands Source: https://github.com/yuri-moskvin/flowerkit/blob/main/AGENTS.md Standard npm commands for managing dependencies, linting, testing, and building the project. ```bash npm.cmd install ``` ```bash npm.cmd run lint ``` ```bash npm.cmd exec -- eslint lib rollup.config.ts eslint.config.ts commitlint.config.ts ``` ```bash npm.cmd run typecheck ``` ```bash npm.cmd test ``` ```bash npm.cmd run test:coverage ``` ```bash node ./lib/scripts/docs.ts ``` ```bash npm.cmd run verify:size ``` ```bash npm.cmd run verify:package ``` ```bash npm.cmd run build ``` -------------------------------- ### getFromServer Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/net.md Performs an HTTP request using fetch with built-in defaults, content-type handling, and query parameter construction. ```APIDOC ## getFromServer ### Description Performs an HTTP request with handy defaults, content-type handling, query param building, and optional bubbling of a "getFromServer" event. ### Signature `getFromServer(props?: TGetFromServerArgs) => Promise` ### Parameters - **props** (TGetFromServerArgs) - Optional - Request parameters including url, method, data, headers, and fetch configuration. ### Example ```ts const user = await getFromServer<{ userId: number }>({ url: "/api/user?id=1", method: "GET" }); ``` ``` -------------------------------- ### Get minimum value from array in TypeScript Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/num.md Retrieves the smallest number from a non-empty array of numbers. ```ts // How to get min number from Array of numbers? const arr = [ 100, 200, 300 ]; const min = getMinFromArr(arr); console.log(min); // 100 ``` ```ts // Find the lowest product price in a catalog const lowestPrice = getMinFromArr(products.map((product) => product.price)); ``` -------------------------------- ### Import Flowerkit Date Utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/date.md Import the necessary functions and types from the @web3r/flowerkit/date package. ```ts // import functions import { getDateAdded, getDateDiff, getDateFormatted, isValidDate, getPureDate } from "@web3r/flowerkit/date"; // import types import type { TDateInput, TGetDateAddedArgs, TGetDateAddedReturn, TGetDateDiffArgs, TGetDateDiffReturn, TGetDateFormattedArgs, TGetDateFormattedReturn, TIsValidDateArgs, TIsValidDateReturn, TGetPureDateArgs, TGetPureDateReturn } from "@web3r/flowerkit/date"; ``` -------------------------------- ### Get maximum value from array in TypeScript Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/num.md Retrieves the largest number from a non-empty array of numbers. ```ts // How to get max number from Array of numbers? const arr = [ 100, 200, 300 ]; const max = getMaxFromArr(arr); console.log(max); // 300 ``` ```ts // Find the highest value for a chart scale const chartMax = getMaxFromArr(points.map((point) => point.value)); ``` -------------------------------- ### Get CSS variable values Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/css.md Retrieve the value of a CSS custom property, optionally formatted as a number. ```ts // How to get CSS3 variable value from an element? const block = document.querySelector("#myBlock"); //
      getCSSVar(block, "--myVar"); // or just "myVar" ``` ```ts // Read a numeric spacing token from CSS in JavaScript const spacing = getCSSVar(document.documentElement, "spacing", true); console.log(spacing); // number ``` -------------------------------- ### Import FlowerKit Event Utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Import the necessary functions and types from the @web3r/flowerkit/evt package. ```ts // import functions import { bubble, on, onClickOutside, onDOMReady, onIntersection, onMediaQueryChange, onResizeObserved, onSwipe, onWindowLoad, onWindowResize } from "@web3r/flowerkit/evt"; // import types import type { TBubbleArgs, TBubbleReturn, TOnControls, TOnArgs, TOnReturn, TOnClickOutsideOptions, TOnClickOutsideArgs, TOnClickOutsideReturn, TOnDOMReadyArgs, TOnDOMReadyReturn, TOnIntersectionArgs, TOnIntersectionReturn, TOnMediaQueryChangeArgs, TOnMediaQueryChangeReturn, TOnResizeObservedArgs, TOnResizeObservedReturn, TOnSwipeArgs, TOnSwipeReturn, TOnWindowLoadArgs, TOnWindowLoadReturn, TOnWindowResizeArgs, TOnWindowResizeReturn } from "@web3r/flowerkit/evt"; ``` -------------------------------- ### Get computed CSS values Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/css.md Retrieve the computed value of a specific CSS property for a DOM element. ```ts // How to get "height" prop of div from JS? const block = document.querySelector("#myBlock"); getCSSValue(block, "height"); ``` ```ts // Check whether a responsive navigation element is currently hidden const display = getCSSValue(navigation, "display"); const isNavigationHidden = display === "none"; ``` -------------------------------- ### Importing DOM Utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/dom.md Import the necessary functions and types from the @web3r/flowerkit/dom package. ```typescript // import functions import { getElSiblings, getElWrapper, getHTMLFromStr, getIndexOfEl, getScrollParent, isNode, removeChildNodes } from "@web3r/flowerkit/dom"; // import types import type { TGetElSiblingsArgs, TGetElSiblingsReturn, TGetElWrapperArgs, TGetElWrapperReturn, TGetHTMLFromStrArgs, TGetHTMLFromStrReturn, TGetIndexOfElArgs, TGetIndexOfElReturn, TScrollAxis, TGetScrollParentArgs, TGetScrollParentReturn, TIsNodeArgs, TIsNodeReturn, TRemoveChildNodesArgs, TRemoveChildNodesReturn } from "@web3r/flowerkit/dom"; ``` -------------------------------- ### Get Scroll Parent Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/dom.md Find the nearest ancestor element that acts as a scroll container for a specific axis. ```typescript const scrollContainer = getScrollParent(dropdownTrigger); scrollContainer?.addEventListener("scroll", repositionDropdown); ``` ```typescript // Use the vertical scroll parent as an IntersectionObserver root const root = getScrollParent(loadMoreButton, "y"); const observer = new IntersectionObserver(loadNextPage, { root }); ``` -------------------------------- ### Importing Flowerkit string utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/str.md Import the necessary functions and types from the @web3r/flowerkit/str module. ```ts // import functions import { getId, getStrDeclination, getStrEscaped, getStrTruncated, getStrUnescaped, getStrWithCamelCase, getStrWithCapitalized, getStrWithKebabCase, getStrWithNormalizedSpaces, getStrWithSlug, getStrWithSnakeCase, getStrWithThousandSeparator, getStrWithZeroFromNum, getWords, isStrInCamelCase, isStrInKebabCase, isStrInSnakeCase, isStrUrl } from "@web3r/flowerkit/str"; // import types import type { TGetIdArgs, TGetIdReturn, TGetStrDeclinationArgs, TGetStrDeclinationReturn, TGetStrEscapedArgs, TGetStrEscapedReturn, TGetStrTruncatedArgs, TGetStrTruncatedReturn, TGetStrUnescapedArgs, TGetStrUnescapedReturn, TGetStrWithCamelCaseArgs, TGetStrWithCamelCaseReturn, TGetStrWithCapitalizedArgs, TGetStrWithCapitalizedReturn, TGetStrWithKebabCaseArgs, TGetStrWithKebabCaseReturn, TGetStrWithNormalizedSpacesArgs, TGetStrWithNormalizedSpacesReturn, TGetStrWithSlugArgs, TGetStrWithSlugReturn, TGetStrWithSnakeCaseArgs, TGetStrWithSnakeCaseReturn, TGetStrWithThousandSeparatorArgs, TGetStrWithThousandSeparatorReturn, TGetStrWithZeroFromNumArgs, TGetStrWithZeroFromNumReturn, TGetWordsArgs, TGetWordsReturn, TIsStrInCamelCaseArgs, TIsStrInCamelCaseReturn, TIsStrInKebabCaseArgs, TIsStrInKebabCaseReturn, TIsStrInSnakeCaseArgs, TIsStrInSnakeCaseReturn, TIsStrUrlArgs, TIsStrUrlReturn } from "@web3r/flowerkit/str"; ``` -------------------------------- ### Importing Array Utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/arr.md Import the necessary functions and types from the @web3r/flowerkit/arr module. ```typescript // import functions import { getArrSortedBy, getAsyncMap, getChunkedArr, getDiff, getGroupedBy, getIntersection, getLastFromIterable, getUnion, getUniqueBy, isItemsEqual, isIterable, isNonEmptyArr } from "@web3r/flowerkit/arr"; // import types import type { TArrSortDirection, TArrSortNulls, TArrSortValue, TGetArrSortedByOptions, TGetArrSortedByArgs, TGetArrSortedByReturn, TGetAsyncMapArgs, TGetAsyncMapReturn, TGetChunkedArrArgs, TGetChunkedArrReturn, TGetDiffArgs, TGetDiffReturn, TGetGroupedByArgs, TGetGroupedByReturn, TGetIntersectionArgs, TGetIntersectionReturn, TGetLastFromIterableArgs, TGetLastFromIterableReturn, TGetUnionArgs, TGetUnionReturn, TGetUniqueByArgs, TGetUniqueByReturn, TIsItemsEqualArgs, TIsItemsEqualReturn, TIsIterableArgs, TIsIterableReturn, TIsNonEmptyArrArgs, TIsNonEmptyArrReturn } from "@web3r/flowerkit/arr"; ``` -------------------------------- ### Test media queries Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/css.md Check if a media query string matches the current environment. ```ts // How to check if a user device has portrait or landscape orientation? const mediaQuery = "(orientation: portrait)"; const isPortrait = isMediaQuery(mediaQuery); console.log(isPortrait); // => false ``` ```ts // Disable decorative animation when the user prefers reduced motion const shouldReduceMotion = isMediaQuery("(prefers-reduced-motion: reduce)"); ``` -------------------------------- ### Get CSS transform values Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/css.md Retrieve x, y, and z translation values from an element's transform style. ```ts // How to get `translate3d` values of a `div`? //
      const block = document.getElementById("block"); const values = getCSSTransformValues(block); console.log(values); // => { x: 10, y: 15, z: 35 } ``` ```ts // Read the current translated position before continuing a drag animation const { x, y } = getCSSTransformValues(draggableElement); draggableElement.style.transform = `translate(${x + 20}px, ${y}px)${` ``` -------------------------------- ### Import JSON utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/json.md Import the necessary functions and types from the @web3r/flowerkit/json module. ```ts // import functions import { getJSONFromStr, isJSON } from "@web3r/flowerkit/json"; // import types import type { TGetJSONFromStrArgs, TGetJSONFromStrReturn, TIsJSONArgs, TIsJSONReturn } from "@web3r/flowerkit/json"; ``` -------------------------------- ### isMediaQuery Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/css.md Tests a CSS media query string against the current environment. ```APIDOC ## isMediaQuery(str: string) ### Description Tests a CSS media query string and returns whether it matches the current environment. ### Parameters - **str** (string) - Required - The media query string to test. ### Returns - **boolean** - True if the media query matches, false otherwise. ``` -------------------------------- ### Validate camelCase strings with isStrInCamelCase Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/str.md Checks if a string starts with lowercase letters and contains at least one capitalized segment. ```ts isStrInCamelCase("abcDef"); // true isStrInCamelCase("Word"); // false ``` ```ts // Validate JavaScript-style keys imported from a configuration file const invalidKeys = Object.keys(config).filter((key) => !isStrInCamelCase(key)); ``` -------------------------------- ### Strip Time from Dates Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/date.md Get a new Date instance with time components (hours, minutes, seconds, milliseconds) set to zero. ```ts // How to get a date without time e.g., hours, minutes, seconds, and milliseconds? const dateWithTime = new Date(); console.log(dateWithTime.getMilliseconds()); // => {number} const dateWithoutTime = getPureDate(dateWithTime); console.log(dateWithoutTime.getMilliseconds()); // => 0 ``` ```ts // Compare calendar dates while ignoring their time values const isDueToday = getPureDate(task.dueAt)?.getTime() === getPureDate(new Date())?.getTime(); ``` -------------------------------- ### Importing FlowerKit utilities Source: https://github.com/yuri-moskvin/flowerkit/blob/main/README.md Use subpath imports to optimize bundle size or import via namespace kits. Supports both ESM and CommonJS environments. ```ts // ESM import { getUniqueBy } from "@web3r/flowerkit/arr"; import { onIntersection, onSwipe } from "@web3r/flowerkit/evt"; // Namespace kits import { arrKit, evtKit } from "@web3r/flowerkit"; // CommonJS const { getUniqueBy } = require("@web3r/flowerkit/arr"); // Public types import type { TOnSwipeArgs, TOnSwipeReturn } from "@web3r/flowerkit/evt"; ``` -------------------------------- ### Import CSS utility functions and types Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/css.md Import the necessary functions and TypeScript types from the package. ```ts // import functions import { getCSSTransformValues, getCSSValue, getCSSVar, isMediaQuery, isSelectorValid, removeCSSVar, setCSSVar } from "@web3r/flowerkit/css"; // import types import type { TGetCSSTransformValuesArgs, TGetCSSTransformValuesReturn, TGetCSSValueArgs, TGetCSSValueReturn, TGetCSSVarArgs, TGetCSSVarReturn, TIsMediaQueryArgs, TIsMediaQueryReturn, TIsSelectorValidArgs, TIsSelectorValidReturn, TRemoveCSSVarArgs, TRemoveCSSVarReturn, TSetCSSVarArgs, TSetCSSVarReturn } from "@web3r/flowerkit/css"; ``` -------------------------------- ### Find SSR-window usage Source: https://github.com/yuri-moskvin/flowerkit/blob/main/AGENTS.md Search for references to ssr-window within the source code. ```bash rg "ssr-window" src ``` ```powershell Get-ChildItem -Recurse -File src | Select-String -Pattern "ssr-window" ``` -------------------------------- ### Manage media query listeners with onMediaQueryChange Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Attaches listeners to CSS media queries with automatic cleanup support. Safe to use in SSR environments where matchMedia is unavailable. ```ts onMediaQueryChange("(prefers-color-scheme: dark)", ({ matches }) => setDark(matches)); ``` ```ts // React to a desktop breakpoint without leaking a matchMedia listener const desktop = onMediaQueryChange("(min-width: 1024px)", ({ matches }) => { setSidebarExpanded(matches); }); desktop.removeListener(); ``` -------------------------------- ### onMediaQueryChange Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Creates a managed listener for changes to a CSS media query. ```APIDOC ## onMediaQueryChange(query, callback, isAutoInit?) ### Description Creates a managed listener for changes to a CSS media query. It is a no-op when matchMedia is unavailable. ### Parameters - **query** (string) - Required - Media query - **callback** ((event: MediaQueryListEvent) => void) - Required - Change callback - **isAutoInit** (boolean) - Optional - Attach immediately ### Example ```ts onMediaQueryChange("(prefers-color-scheme: dark)", ({ matches }) => setDark(matches)); ``` ``` -------------------------------- ### Importing Number Utility Functions and Types Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/num.md Import the necessary utility functions and their corresponding TypeScript types from the @web3r/flowerkit/num package. ```typescript // import functions import { getClampedNum, getCurrencyFormatted, getMaxFromArr, getMinFromArr, getNumberFormatted, getRandomIntFromInterval, getRounded } from "@web3r/flowerkit/num"; // import types import type { TGetClampedNumArgs, TGetClampedNumReturn, TGetCurrencyFormattedArgs, TGetCurrencyFormattedReturn, TGetMaxFromArrArgs, TGetMaxFromArrReturn, TGetMinFromArrArgs, TGetMinFromArrReturn, TGetNumberFormattedArgs, TGetNumberFormattedReturn, TGetRandomIntFromIntervalArgs, TGetRandomIntFromIntervalReturn, TGetRoundedArgs, TGetRoundedReturn } from "@web3r/flowerkit/num"; ``` -------------------------------- ### createStorage Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/user.md Creates a typed, JSON-backed and SSR-safe storage namespace. Operations return fallbacks or false when storage is unavailable. ```APIDOC ## createStorage(options?: { namespace?: string; onError?: (error: unknown) => void; storage?: Storage | null; }) -> TStorageController ### Description Creates a typed, JSON-backed and SSR-safe storage namespace. Operations return fallbacks or false when storage is unavailable. ### Parameters - **options** (Object) - Optional - Options; namespace defaults to "flowerkit" ### Returns - **TStorageController** - Storage controller ``` -------------------------------- ### Calculate per-kit public utility counts via PowerShell Source: https://github.com/yuri-moskvin/flowerkit/blob/main/AGENTS.md Iterates through specific utility kits to report the count of exported functions for each. ```powershell foreach($m in 'arr','css','date','dom','evt','fn','json','net','num','obj','str','user'){ $counts = Get-ChildItem "src/$m" -Recurse -File -Filter index.ts | ForEach-Object { ([regex]::Matches((Get-Content -Raw $_.FullName), '(?m)^export const\s+(?!_)\w+\s*=')).Count }; "$m=$(($counts | Measure-Object -Sum).Sum)" } ``` -------------------------------- ### Create Managed Event Listeners with on Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Create event listeners that return controls for manual removal, useful for component lifecycle management. ```ts const listener = on(window, "online", () => sync()); listener.removeListener(); ``` ```ts // Attach a keyboard shortcut now and remove it during component cleanup const escapeKey = on(document, "keydown", (event) => { if (event.key === "Escape") closeDialog(); }); escapeKey.removeListener(); ``` -------------------------------- ### Importing Flowerkit Functions Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/fn.md Import the necessary utility functions and their corresponding TypeScript types from the package. ```typescript // import functions import { getAbortSignal, getAsyncPool, getCurryFn, getDebouncedFn, getMemoizedFn, getLatestAsyncFn, getRetriedFn, getThrottledFn, isFnAsync, isFnClass, once, wait } from "@web3r/flowerkit/fn"; // import types import type { TAbortSignalControls, TGetAbortSignalOptions, TGetAbortSignalArgs, TGetAbortSignalReturn, TGetAsyncPoolOptions, TGetAsyncPoolResult, TGetAsyncPoolArgs, TGetAsyncPoolReturn, TGetCurryFnArgs, TGetCurryFnReturn, TDebouncedFn, TGetDebouncedFnArgs, TGetDebouncedFnReturn, TMemoizedFn, TGetMemoizedFnArgs, TGetMemoizedFnReturn, TGetLatestAsyncFnOptions, TLatestAsyncFn, TLatestAsyncSource, TGetLatestAsyncFnArgs, TGetLatestAsyncFnReturn, TRetryOptions, TGetRetriedFnArgs, TGetRetriedFnReturn, TThrottledFn, TGetThrottledFnArgs, TGetThrottledFnReturn, TIsFnAsyncArgs, TIsFnAsyncReturn, TIsFnClassArgs, TIsFnClassReturn, TOnceArgs, TOnceReturn, TWaitOptions, TWaitArgs, TWaitReturn } from "@web3r/flowerkit/fn"; ``` -------------------------------- ### Handle DOM Ready State with onDOMReady Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/evt.md Execute code once the DOM is fully parsed, or immediately if the event has already fired. ```ts onDOMReady(() => console.log("DOM ready")); ``` ```ts // Initialize client-side widgets after the HTML document is parsed const ready = onDOMReady(() => initializeWidgets("[data-widget]")); ready.removeListener(); ``` -------------------------------- ### Handle getFromServer errors Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/net.md Demonstrates error handling for network requests, specifically checking for HTTP-related errors. ```ts import type { TGetFromServerError } from "@web3r/flowerkit/net"; try { await getFromServer({ url: "/api/user" }); } catch (error) { if (error instanceof Error && error.name === "GetFromServerError") { const requestError = error as TGetFromServerError; if (requestError.kind === "http") { console.error(requestError.status, requestError.response); } } } ``` -------------------------------- ### Verify package integrity Source: https://github.com/yuri-moskvin/flowerkit/blob/main/README.md Executes the verification script to test the packed artifact against public entry points. ```bash npm run verify:package ``` -------------------------------- ### isStrInKebabCase(str: string) => boolean Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/str.md Checks if a string follows kebab-case naming conventions. ```APIDOC ## isStrInKebabCase(str: string) ### Description Checks if a string is in kebab-case. Rules: Lowercase letters separated by single hyphens, with no leading or trailing hyphens. ### Parameters - **str** (string) - Required - The source string to check. ### Returns - **boolean** - True if the string is kebab-case. ``` -------------------------------- ### getElWrapper Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/dom.md Wraps a specific DOM element with a provided HTML layout string. ```APIDOC ## getElWrapper(el: HTMLElement, str: string) => HTMLElement ### Description Wraps a specific element with a provided HTML layout string, supporting nested blocks. ### Parameters - **el** (HTMLElement) - Required - The DOM element to wrap. - **str** (string) - Required - The HTML layout string to use as a wrapper. ``` -------------------------------- ### getStrWithSlug Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/str.md Creates a lowercase Unicode slug. ```APIDOC ## getStrWithSlug(str: string, options?: { separator?: string; locale?: string }) -> string ### Description Creates a lowercase Unicode slug. Diacritics are removed, while non-Latin letters such as Cyrillic are preserved. ### Parameters - **str** (string) - Required - Source string - **options** (object) - Optional - Slug options (separator, locale) ### Returns - (string) - Slug ``` -------------------------------- ### wait(ms, options) Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/fn.md Returns a Promise that resolves after a specified duration. It supports optional cancellation using an AbortSignal. ```APIDOC ## wait(ms, options) ### Description Gets a Promise that resolves after a specific time. This is useful for introducing delays in asynchronous sequences or handling timeouts. ### Signature `(ms?: number, options?: TWaitOptions) => Promise` ### Parameters - **ms** (number) - Optional - The delay duration in milliseconds. - **options** (TWaitOptions) - Optional - Configuration object containing an optional cancellation signal. ### Usage Example ```ts // Delay the next step in an async animation sequence await wait(200); element.classList.add("is-visible"); // Cancel a pending delay during component cleanup const lifecycle = new AbortController(); await wait(1_000, { signal: lifecycle.signal }); lifecycle.abort(); ``` ``` -------------------------------- ### getStrWithKebabCase Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/str.md Converts a string to kebab-case. ```APIDOC ## getStrWithKebabCase(str: string) -> string ### Description Converts a string to kebab-case. ### Parameters - **str** (string) - Required - Source string ### Returns - (string) - kebab-case string ``` -------------------------------- ### Using getCurryFn Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/fn.md Transform functions into sequences of unary functions for partial application. ```typescript function sum(a: number, b: number) { return a + b; } const curried = getCurryFn(sum); curried(1)(2); // 3 ``` ```typescript // Build reusable field validators from a curried range check const isInRange = getCurryFn((min: number, max: number, value: number) => { return value >= min && value <= max; }); const isValidPercentage = isInRange(0)(100); ``` -------------------------------- ### getFormDataFromObj Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/net.md Builds a FormData instance from a plain object. ```APIDOC ## getFormDataFromObj ### Description Builds a FormData instance from a plain object. ### Signature `(obj?: TSourceObject, fd?: FormData, setItem?: TSetItemFunction) => FormData` ### Parameters - **obj** (object) - Optional - Source object - **fd** (FormData) - Optional - Existing FormData to append to - **setItem** (function) - Optional - Custom setter per entry ### Returns Result FormData ``` -------------------------------- ### Find all tests Source: https://github.com/yuri-moskvin/flowerkit/blob/main/AGENTS.md Locate all test files ending in index.test.ts. ```bash rg --files src | rg "index\.test\.ts$" ``` ```powershell Get-ChildItem -Recurse -File src -Filter index.test.ts | ForEach-Object { $_.FullName } ``` -------------------------------- ### Handle Repeated Form Values Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/net.md Demonstrates how the utility preserves multiple values for the same key, such as checkboxes. ```ts // Preserve repeated checkbox values when converting a form submission const data = new FormData(form); const values = getObjFromFormData(data); console.log(values.category); // string, File, or an array of repeated values ``` -------------------------------- ### Detect ad-blockers with isAdblock Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/user.md Infers the presence of an ad-blocker by measuring the visibility of an injected ad-like element. ```ts const blocked = isAdblock(); console.log(blocked); // => false ``` ```ts // Offer an ad-free subscription when an ad blocker is detected if (isAdblock()) showAdFreeSubscriptionNotice(); ``` -------------------------------- ### copyToClipboard Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/user.md Copies text to the clipboard using the Clipboard API with a legacy fallback. Returns false when clipboard access is unavailable or denied. ```APIDOC ## copyToClipboard(text: string) -> Promise ### Description Copies text to the clipboard using the Clipboard API with a legacy fallback. Returns false when clipboard access is unavailable or denied. ### Parameters - **text** (string) - Required - Text to copy ### Returns - **boolean** - Whether copying succeeded ``` -------------------------------- ### getQueryParam Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/net.md Retrieves the first value of a specific URL query parameter. ```APIDOC ## getQueryParam ### Description Gets the first value of a URL query parameter. ### Signature `(name: string, input?: TQueryParamsInput) => string | null` ### Parameters - **name** (string) - Required - Parameter name. - **input** (TQueryParamsInput) - Optional - URL, query string, or URLSearchParams; defaults to current URL. ### Example ```ts getQueryParam("page", "?page=2"); // "2" ``` ``` -------------------------------- ### Find exported symbols in kit indexes Source: https://github.com/yuri-moskvin/flowerkit/blob/main/AGENTS.md Locate exported types or objects within index files in the src subdirectories. ```bash rg "^export (type )?\{" src/*/index.ts ``` ```powershell Get-ChildItem -File src/*/index.ts | Select-String -Pattern "^export (type )?\{" ``` -------------------------------- ### Format Dates Source: https://github.com/yuri-moskvin/flowerkit/blob/main/docs/date.md Format a date using Intl.DateTimeFormat. ```ts getDateFormatted(new Date("2024-01-02T00:00:00Z"), "en-US", { timeZone: "UTC" }); ``` ```ts // Format an order date for a Russian storefront const label = getDateFormatted(order.createdAt, "ru-RU", { dateStyle: "long", timeZone: "Europe/Moscow", }); ```