common-util.ts
Overview
common-util.ts is a utility module providing a collection of general-purpose helper functions for data manipulation, formatting, conversion, and color parsing. These utilities are designed to simplify common tasks across the application, such as:
Checking and transforming data structures,
Formatting numbers and file sizes,
Sorting factory lists by a predefined order,
Converting between string and typed array representations,
Parsing CSS color values to RGB components.
This file acts as a shared toolkit that can be imported wherever these functionalities are needed, promoting code reuse, consistency, and maintainability throughout the system.
Functions and Exports
isFormData(data: unknown): data is FormData
Description: Type guard that checks whether the provided data is an instance of the
FormDataobject.Parameters:
data: Data of unknown type.
Returns:
trueifdataisFormData, otherwisefalse.Usage example:
if (isFormData(someData)) { // Handle FormData specific logic }
convertTheKeysOfTheObjectToSnake(data: unknown): unknown
Description: Converts the keys of an object from camelCase or other formats to snake_case, excluding certain fields and
FormDataobjects.Parameters:
data: Input data expected to be an object.
Returns: A new object with keys converted to snake_case, or returns the
dataunchanged if it is not an object or isFormData.Implementation details:
Uses lodash's
isObjectandsnakeCase.Excludes keys in
excludedFields('img2txt_id','mcpServers') and any keys whose values areFormData.
Usage example:
const camelObj = { someKey: 'value', img2txt_id: 123 }; const snakeObj = convertTheKeysOfTheObjectToSnake(camelObj); // snakeObj = { some_key: 'value', img2txt_id: 123 }
getSearchValue(key: string): string | null
Description: Retrieves the value of a query parameter from the current page's URL.
Parameters:
key: The query parameter key to look for.
Returns: The value of the parameter if present, or
nullif not found.Usage example:
const userId = getSearchValue('user_id');
formatNumberWithThousandsSeparator(numberStr: string): string
Description: Adds thousands separators (commas) to a numeric string for readability.
Parameters:
numberStr: Numeric string without formatting.
Returns: Formatted string with commas inserted.
Usage example:
formatNumberWithThousandsSeparator('1000000'); // "1,000,000"
sortLLmFactoryListBySpecifiedOrder(list: IFactory[]): IFactory[]
Description: Sorts a list of LLM factory objects according to a predefined order specified in
orderFactoryList. Factories not in the order list are appended at the end.Parameters:
list: Array ofIFactoryobjects to sort.
Returns: A new array of
IFactorysorted by the specified order.Implementation details:
Uses
LLMFactoryconstants to define the desired order.Iterates over the order list to pick matching factories.
Appends any remaining factories at the end.
Usage example:
const sortedFactories = sortLLmFactoryListBySpecifiedOrder(factoryList);
filterOptionsByInput(input: string, option?: { label: string; value: string }): boolean
Description: Filters selectable options by checking if the option's label includes the input string, case-insensitive.
Parameters:
input: The search input string.option: An object withlabelandvalueproperties orundefined.
Returns:
trueif the option label contains the input, otherwisefalse.Usage example:
const isMatch = filterOptionsByInput('apple', { label: 'Apple Pie', value: '1' });
toFixed(value: unknown, fixed = 2): unknown
Description: Converts a numeric value to a string fixed to a specified number of decimal places.
Parameters:
value: The value to format; only formats if a number.fixed: Number of decimal places (default 2).
Returns: The fixed decimal string if value is a number, otherwise returns the original value.
Usage example:
toFixed(3.14159, 3); // "3.142" toFixed('text'); // "text"
stringToUint8Array(str: string): Uint8Array
Description: Converts a Python-style byte string representation (e.g.
"b'abc'") into aUint8Array.Parameters:
str: String to convert.
Returns:
Uint8Arrayof character codes.Implementation details:
Strips the leading
b'and trailing'.Converts each character to its char code.
Usage example:
const arr = stringToUint8Array("b'hello'");
hexStringToUint8Array(hex: string): Uint8Array | undefined
Description: Converts a hexadecimal string into a
Uint8Array.Parameters:
hex: Hexadecimal string (e.g. "ff00a1").
Returns:
Uint8Arrayrepresenting the bytes orundefinedif the input is invalid.Usage example:
const arr = hexStringToUint8Array("ff00a1");
hexToArrayBuffer(input: string): ArrayBuffer
Description: Converts a hex string into an
ArrayBuffer.Parameters:
input: Hexadecimal string. Must have even length.
Returns: An
ArrayBuffercontaining the byte values.Throws:
TypeErrorif input is not a string.RangeErrorif input length is odd.
Usage example:
const buffer = hexToArrayBuffer("0a0b0c");
formatFileSize(bytes: number, si = true, dp = 1): string
Description: Formats a file size in bytes into a human-readable string with units.
Parameters:
bytes: Number of bytes.si: If true, uses SI units (1000-based), otherwise binary units (1024-based).dp: Number of decimal places.
Returns: Formatted file size string (e.g., "1.2 MB").
Usage example:
formatFileSize(1024); // "1.0 kB" formatFileSize(1024, false); // "1.0 KiB"
parseColorToRGBA(color: string): [number, number, number]
Description: Parses a CSS color string (hex, rgb, or CSS variable) and returns an RGB array.
Parameters:
color: Color string (e.g.,#ff5733,rgb(255,87,51), orvar(--accent-primary)).
Returns: A tuple
[R, G, B]of numbers, or[0, 0, 0]if parsing fails.Implementation details:
Supports CSS variable resolution via
getCSSVariableValue.Supports 3 or 6 character hex codes.
Supports rgb format (though there's an apparent regex bug, see notes).
Logs errors on unsupported formats.
Usage example:
parseColorToRGBA('#ff0000'); // [255, 0, 0] parseColorToRGBA('var(--main-color)');
Internal Helper Functions
isExcludedField(key: string): boolean
Description: Checks if a key is in the
excludedFieldslist.Parameters:
key: The object key to test.
Returns:
trueif the key is excluded, otherwisefalse.
getCSSVariableValue(variableName: string): string
Description: Retrieves the computed value of a CSS variable from the document's root.
Parameters:
variableName: The CSS variable name (e.g.--accent-primary).
Returns: The CSS variable's value as a string.
Throws: Error if the variable is not defined.
Important Implementation Details & Notes
The file uses lodash utilities for robust type checking (
isObject) and string manipulation (snakeCase).The
sortLLmFactoryListBySpecifiedOrderfunction depends on constants imported fromLLMFactoryand theIFactoryinterface, indicating integration with a module handling LLM (Large Language Model) factories.Color parsing supports CSS variables by extracting their computed values but may have a regex bug in the RGB parsing section:
const rgbMatch = colorStr.match(/rgb$$(\d+),\s*(\d+),\s*(\d+)$$/);The regex uses
$$which likely intends to be(and)to capturergb(...)— this should be reviewed.stringToUint8Arrayassumes input strings are in a Python bytes literal format (starting withb'), which may be specific to the application domain.File size formatting supports both SI (decimal) and binary units with customizable decimal precision.
Interactions with Other Parts of the System
Imports constants and interfaces from:
@/constants/llm— for LLM factory constants.@/interfaces/database/llm— for theIFactoryinterface.
Utilizes lodash utilities (
isObject,snakeCase).Accesses global
documentobject to:Extract URL search parameters.
Get CSS computed styles for variable resolution.
Expected to be imported and used by components and services needing common data formatting, conversion, and utility functions.
Visual Diagram
flowchart TD
A[common-util.ts] --> B[isFormData]
A --> C[convertTheKeysOfTheObjectToSnake]
A --> D[getSearchValue]
A --> E[formatNumberWithThousandsSeparator]
A --> F[sortLLmFactoryListBySpecifiedOrder]
A --> G[filterOptionsByInput]
A --> H[toFixed]
A --> I[stringToUint8Array]
A --> J[hexStringToUint8Array]
A --> K[hexToArrayBuffer]
A --> L[formatFileSize]
A --> M[parseColorToRGBA]
subgraph "Helper Functions"
N[isExcludedField]
O[getCSSVariableValue]
end
C --> N
M --> O
Summary
The common-util.ts file is a key utility module offering a broad set of helper functions that:
Handle data type checks and transformations.
Facilitate formatting tasks (numbers, file sizes).
Provide conversions between string and binary data formats.
Parse and resolve CSS color values.
Organize and sort factory-related entities.
It serves as a foundational toolkit to support consistent and efficient code across the application, especially for modules working with LLM factories and UI-related data processing.
If you have any questions about specific functions or need usage examples for particular contexts, feel free to ask!