Namespace: Utilities

Utilities

The Utilities namespace contains many functions that are used within the CompactChart code. Some of these might be of interest to you as a developer, and some may even be overridden to produce more customized output.

Since:
  • 9.4.0

Methods


borderPatternToArray(width [, pattern])

This function is overrideable. Given a line width and a desired line pattern, will compute the appropriately scaled pattern to use. For a dashed line, each dash will be 5 x width in pixels. For a dotted line, eash dash will be 1 x width in pixels.

Parameters:
Name Type Argument Description
width number

Requested line width in pixels.

pattern string | Array.<number> <optional>

Requested pattern as an array of numbers, or a named pattern ("dashed", "dotted", "solid").

Since:
  • 9.4.0

Returns:

Appropriately scaled pattern.

Type
Array.<number>

buildCanvasTitle(chartDescriptor)

This function is overrideable. Given a line width and a desired line pattern, will compute the appropriately scaled pattern to use. For a dashed line, each dash will be 5 x width in pixels. For a dotted line, eash dash will be 1 x width in pixels.

Parameters:
Name Type Description
chartDescriptor ChartDescriptor

Object that contains the current state of the chart.

Since:
  • 9.4.0

Returns:

Canvas title.

Type
string

capitalize(string)

This function is overrideable. Capitalizes the first letter in a string.

Parameters:
Name Type Description
string string

String to capitalize.

Since:
  • 9.4.0 Introduced
  • 10.1.0 Made overrideable
Returns:

Canvas title.

Type
string

chooseForegroundColor( [backgroundColor])

This function is overrideable. Given a background color, chooses the better text color to use on top of it. The algorithm is based on relative luminance.

Parameters:
Name Type Argument Description
backgroundColor string <optional>

Background color in css-compatible format.

Since:
  • 9.4.0

Returns:

Text color, either white or black.

Type
string

cleanPeriodicity(_argument_)

Given a Periodicity, will normalize it to acceptable values. TimeUnit of "hour"" or "year" converted to "minute" or "month". Daily TimeUnit moved into interval field.

Parameters:
Name Type Description
_argument_ Periodicity

Periodicity to clean.

Since:
  • 9.4.0

Returns:

Cleaned periodicity.

Type
Periodicity

clone(from [, to] [, withoutPrototypeProperties])

Deep-copies an object to another object. Note both objects need to be of the same type. Otherwise consider Object.assign whereever possible.

Parameters:
Name Type Argument Default Description
from object

Source object.

to object <optional>

Target object.

withoutPrototypeProperties boolean <optional>
false

Set to true to not clone prototoype properties.

Since:
  • 9.4.0

Returns:

Clone of object.

Type
object

cloneStyle(styleObject)

Deep-copies a style declaration.

Parameters:
Name Type Description
styleObject CSSStyleDeclaration

Source style declaration.

Since:
  • 9.4.0

Returns:

Clone of style declaration.

Type
CSSStyleDeclaration

colorToHex(color)

Converts an rgb or web-safe color to hex. The alpha channel is dropped unless a hex value is passed in initially. If the color is transparent or not provided, the result will be black. The result is stored in a cache for fast retrieval if needed.

Parameters:
Name Type Description
color string

Color to convert.

Since:
  • 9.4.0

Returns:

Hex value of rgb conversion.

Type
string

colorsEqual(color1, color2)

Compares two colors for equality.

Parameters:
Name Type Description
color1 string | CanvasGradient | CanvasPattern | undefined

First color.

color2 string | CanvasGradient | CanvasPattern | undefined

Second color.

Since:
  • 9.4.0

Returns:

True if colors are equivalent.

Type
boolean

commas(val [, locale])

This function is overrideable. Given a number, will insert commas or other locale-specific separators at the appropriate places.

Parameters:
Name Type Argument Default Description
val number

Number to format.

locale string <optional>
""

Locale-code requested.

Since:
  • 9.4.0

Returns:

Formatted number.

Type
string

condenseInt(txt, qc)

This function is overrideable. Given a number, remove "insignificant digits" and replace with a thousands/millions/etc indicator.

Parameters:
Name Type Description
txt string | number

Number to format.

qc CompactChart

CompactChart instance.

Since:
  • 9.4.0

Returns:

Formatted number.

Type
string

convertTimeZone(tzJS, dt [, originalTimeZone] [, targetTimeZone])

Converts a date from one time zone to another.

Parameters:
Name Type Argument Description
tzJS Class.<TimezoneJS> | undefined

Timezone library.

dt Date

Date to convert.

originalTimeZone string <optional>

Time zone of date to convert, otherwise assumes local time zone.

targetTimeZone string <optional>

Time zone to convert to, otherwise assumes local time zone.

Since:
  • 9.4.0

Returns:

Converted date.

Type
Date | TimezoneJS.Date

convertToDataZone(browserDate, chart)

Converts a date from local time zone to the date specified in the Chart object's dataZone property.

Parameters:
Name Type Description
browserDate Date

Date to convert.

chart Chart

Chart instance.

Since:
  • 9.4.0

Returns:

Converted date.

Type
Date

copyMissingNestedProperties(target, source, properties)

Copies properties from a source object to a target object, specifically only those properties that do not exist in the target object but whose parent object does exist in the target. Note both objects need to be of the same type. Otherwise consider Object.assign whereever possible.

Parameters:
Name Type Description
target object

Target object.

source object

Source object with values to copy.

properties Array.<string>

Specific properties to copy.

Since:
  • 10.1.0

Returns:

Target object.

Type
object

dateAsDisplay(dt [, locale])

Converts a date for display according to locale settings.

Parameters:
Name Type Argument Default Description
dt Date

Date to convert.

locale string <optional>
''

Requested locale.

Since:
  • 9.4.0

Returns:

Converted date.

Type
string

decimalPlacesFromPriceTick(priceTick, idealTickSizePixels)

This function is overrideable. Given a number, determine how many decimal places are significant enough to display for a tick on the y axis. The formula used within attempts to make sure no two ticks on the axis display the same number.

Parameters:
Name Type Description
priceTick number

Price difference between ticks on the y axis.

idealTickSizePixels number

Number of pixels between each price tick on the y axis.

Since:
  • 9.4.0

Returns:

Number of decimal places.

Type
number

displayableDate(qc, dt [, includeIntraYear])

This function is overrideable. Given a date, format it for display. This is usually a function of the periodicity chosen. Internally this function is used for the crosshair date label as well as the SignalIQ date in the marker expansion.

Parameters:
Name Type Argument Description
qc CompactChart

CompactChart instance.

dt Date

Date to format.

includeIntraYear boolean <optional>

Include the year on an intraday interval.

Since:
  • 9.4.0

Returns:

Date to display as a string.

Type
string

efficientDOMUpdate(style, member, value)

Updates a CSS style value but only if different, to avoid any possible reflow issues.

Parameters:
Name Type Description
style CSSStyleDeclaration | undefined

Style declaration objecty.

member string

style name (e.g. font-size, color, display).

value string

New value for style name.

Since:
  • 9.4.0 Introduced
  • 10.1.0 Restricted use to CSSStyleDeclaration
Returns:

True if style value assignment was made, false if unnecessary since didn't change.

Type
boolean

emojify(qc, text)

Scans a text string and converts any emoji patterns into emoji characters. An emoji pattern is one whee the emoji name is between two colons (e.g. :smile:). You must have loaded the emojis.css stylesheet in order for this to work. See Config, stylesheets section.

Parameters:
Name Type Description
qc CompactChart

instance.

text string

Text to scan.

Since:
  • 9.4.0

Returns:

Text string with patterns replaced with actual emojis.

Type
string

encodePeriodicity(_argument_)

This function is overrideable. Given a Periodicity, format it for display in short form. For example, "5m", "1D", etc.

Parameters:
Name Type Description
_argument_ Periodicity

Periodicity.

Since:
  • 9.4.0

Returns:

Periodicity for display.

Type
string

ensureDefaults(target, defaults)

Copies properties that don't exist on target object from source object. Note both objects need to be of the same type. Otherwise consider Object.assign whereever possible. Also note this is not a recursive function. Only the top-level properties are copied.

Parameters:
Name Type Description
target object

Target object.

defaults object

Source object with values to copy.

Since:
  • 9.4.0

Returns:

Target object.

Type
object

equals(a, b [, exclude])

Compares one object to another to determine if property names and values are identical. Note both objects need to be of the same type.

Parameters:
Name Type Argument Description
a Record.<string, object> | object

First object.

b Record.<string, object> | object

Second object.

exclude Record.<string, boolean> <optional>

Object containing field names to exclude from comparison.

Since:
  • 9.4.0

Returns:

True if same.

Type
boolean

extend(target, source [, shallow] [, extendUndefinedProp])

Deep-copies an object onto another object. This is different from Utilities.clone in that properties in the target that are not in the source are preserved. Note both objects need to be of the same type. Otherwise consider Object.assign whereever possible.

Parameters:
Name Type Argument Description
target object

Target object.

source object

Source object.

shallow boolean <optional>

Set to true to perform a shallow copy.

extendUndefinedProp boolean <optional>

Set to true to copy properties that have a value of undefined.

Since:
  • 9.4.0

Returns:

Extended object, same as target.

Type
object

fixPrice(price)

This function is overrideable. Given a number, will attempt to fix floating point errors.

Parameters:
Name Type Argument Description
price number <nullable>

Periodicity.

Since:
  • 9.4.0

Returns:

Stripped number.

Type
number | null

hexToRgba(color, opacity)

Converts a hex color to rgb(a) format.

Parameters:
Name Type Description
color string

Color to convert.

opacity number

Opacity. Can be either 1-100 or 0-1 (decimal).

Since:
  • 9.4.0

Returns:

rgb(a) representation of color.

Type
string | null

hsl(color)

Converts a CSS color to hsl format.

Parameters:
Name Type Description
color string

Color to convert.

Since:
  • 9.4.0

Returns:

Array representing [hue, saturation, luminosity].

Type
Array.<number>

isDailyInterval(interval)

Determines if an interval is for daily periodicity or intraday.

Parameters:
Name Type Description
interval TimeUnit | number

Interval to check.

Since:
  • 9.4.0

Returns:

True if daily periodicity.

Type
boolean

isEmpty(o)

Determines if an object has no "own" properties.

Parameters:
Name Type Description
o object

Object to check.

Since:
  • 9.4.0

Returns:

True if has no "own" properties.

Type
boolean

isPlatform(type)

Determines if a device is running a given platform, mainly through userAgent checks.

Parameters:
Name Type Description
type string

Platform to check. Valid values are:

  • android
  • ipad
  • iphone
  • edge
  • safari
  • chrome
  • firefox
  • mobile
  • surface
Since:
  • 9.4.0

Returns:

True if running that platform.

Type
boolean

isTransparent(color)

Determines if a color is transparent.

Parameters:
Name Type Description
color string | CanvasGradient | CanvasPattern | undefined

Color to check.

Since:
  • 9.4.0

Returns:

True if color is transparent (0 opacity or literally "transparent").

Type
boolean

makeContextFont(configPath)

Builds a "font" style shortcut from its components.

Parameters:
Name Type Description
configPath XAxisConfig | YAxisConfig

Settings from axis configuration.

Since:
  • 9.4.0

Returns:

Font style shortcut, e.g. "italic bold 12px Times".

Type
string

monthAsDisplay(i [, locale] [, params])

Converts a month for display according to locale settings.

Parameters:
Name Type Argument Default Description
i number

Month number (0-11).

locale string <optional>
''

Requested locale.

params MonthDisplayParams <optional>
{}

Display parameters.

Since:
  • 9.4.0

Returns:

Converted month.

Type
string

monthDayAsDisplay(m, d [, locale])

Converts a month and day for display according to locale settings.

Parameters:
Name Type Argument Default Description
m number

Month number (0-11).

d number

Day number (0-31).

locale string <optional>
''

Requested locale.

Since:
  • 9.4.0

Returns:

Converted month + day.

Type
string

newChild(div, tagName [, className] [, txt])

Creates a DOM element and populates it.

Parameters:
Name Type Argument Description
div HTMLElement

Parent element.

tagName string

Type of element to create.

className string <optional>

Optional classname for element.

txt string <optional>

Optional text to place inside element. Note this text will not evaluate to markup (innerText is used for assignment).

Since:
  • 9.4.0

Returns:

New element.

Type
HTMLElement

override(overrideObject)

Override one or more Utility functions. Functions that are overrideable are marked as such in this documentation. To override a function(s), assign it to a UtilityOverrides object and pass into this function.

Parameters:
Name Type Description
overrideObject UtilityOverrides

Object containing overrides to be applied.

Since:
  • 9.4.0 Introduced
  • 10.1.0 Parameters consolidated into overrideObject, allowing overriding of multiple functions at once.
Example

Override the capitalize function:

const capitalize = (str) => str.toUpperCase();
Utilities.override({ capitalize });

percentFormatter(qc, panel [, price])

This function is overrideable. Formats a number assuming it is a percentage, to display on the y axis.

Parameters:
Name Type Argument Description
qc CompactChart

CompactChart instance.

panel Panel

Panel containing y axis.

price number <optional>

Price to format.

Since:
  • 9.4.0

Returns:

Formatted number, including percent sign.

Type
string

resizeObserver(element [, listener])

Creates or removes a ResizeObserver on an element.

Parameters:
Name Type Argument Description
element HTMLElement

Element to observe/unobserve.

listener function <optional>

If provided, a ResizeObserver is created that will call the function when a resize is detected. If not provided, the ResizeObserver on that element is destroyed. The function takes no parameters and does not return any type.

Since:
  • 9.4.0


safeAssign(_element, _string [, _type] [, _mode])

This function is overrideable. Converts a date string to a date. If a native Date object is passed in, it will be returned.

Parameters:
Name Type Argument Default Description
_element HTMLElement

Element in which to place text.

_string string

Text to sanitize.

_type string <optional>
'html'

Type of sink the text will be placed. Valid values are "html", "url", or "script".

_mode string <optional>
'inner'

For type="html", specifies where text will go. Valid values are "inner" or "outer" to use innerHTML or outerHTML, respectively, or any value accepted by the position argument of insertAdjacentHTML.

Since:
  • 9.9.0


strToDateTime(dt)

This function is overrideable. Converts a date string to a date. If a native Date object is passed in, it will be returned.

Parameters:
Name Type Description
dt string | Date

Date to convert.

Since:
  • 9.4.0

Returns:

Date object.

Type
Date

style(qc, className [, pseudo])

Creates an element with the given classname and returns the computed style.

Parameters:
Name Type Argument Description
qc CompactChart

CompactChart instance.

className string

Class name to assign to element.

pseudo string <optional>

Pseudo class (e.g. ":before").

Since:
  • 9.4.0

Returns:

CSS Style Declaration.

Type
CSSStyleDeclaration

timeAsDisplay(dt [, locale] [, precision])

Converts a time for display according to locale settings.

Parameters:
Name Type Argument Default Description
dt Date

Time to convert.

locale string <optional>
''

Requested locale.

precision 0 | 1 <optional>
0

Millisecond precision.

Since:
  • 9.4.0

Returns:

Converted time.

Type
string

uniqueID( [generateUUID])

Creates a unique string.

Parameters:
Name Type Argument Description
generateUUID boolean <optional>

Set to create string in the form of a uuid. Otherwise a 10-character date-based string is created.

Since:
  • 9.4.0

Returns:

Unique string.

Type
string

yIntersection(vector, x)

Attempt to compute the y value of a point on a line extended from a given vector and the x value.

Parameters:
Name Type Description
vector CoordPair

Two points to define a line.

x number

Value of x.

Since:
  • 9.4.0

Returns:

Value of y, if computable. Otherwise, returns null if there is no intersection.

Type
number | null

yearMonthAsDisplay(y, m [, locale])

Converts a year and month for display according to locale settings.

Parameters:
Name Type Argument Default Description
y number

Year.

m number

Month number (0-11).

locale string <optional>
''

Requested locale.

Since:
  • 9.4.0

Returns:

Converted year + month.

Type
string

Type Definitions


CoordPair

A pair of points.

Type:
  • object
Properties:
Name Type Description
x0 number

First x value.

y0 number

First y value.

x1 number

Second x value.

y1 number

Second y value.

Since:
  • 9.4.0


MonthDisplayParams

Parameters used for locale-based month display.

Type:
  • object
Properties:
Name Type Argument Description
displayLetters boolean <optional>

True for narrow mode, otherwise long mode.

maximumShortMonthLength number <optional>

Number of characters to display of month name when displaying in short mode.

Since:
  • 9.4.0


UtilityOverrides

Object that facilitates overriding of utility functions. The key(s) are the names of the function to override, while the values are the definitions.

Type:
  • Record.<string, function()>
Since:
  • 10.1.0