ag-charts-community
Version:
Advanced Charting / Charts supporting Javascript / Typescript / React / Angular / Vue
1,820 lines (1,802 loc) • 1.45 MB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __decorateClass = (decorators, target, key, kind) => {
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
for (var i = decorators.length - 1, decorator; i >= 0; i--)
if (decorator = decorators[i])
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
if (kind && result)
__defProp(target, key, result);
return result;
};
// packages/ag-charts-community/src/api/preset/presetModules.ts
import {
and as and3,
array as array2,
boolean as boolean6,
color as color3,
date as date2,
defined as defined2,
greaterThan as greaterThan3,
lessThan as lessThan3,
lineDashOptionsDef as lineDashOptionsDef6,
number as number6,
or as or3,
positiveNumber as positiveNumber4,
ratio as ratio3,
string as string6,
strokeOptionsDef as strokeOptionsDef6,
typeUnion as typeUnion2,
undocumented as undocumented5,
union as union4
} from "ag-charts-core";
// packages/ag-charts-community/src/chart/commonOptionsDefs.ts
import {
ErrorType,
ValidationError,
and,
array,
arrayLength,
arrayOf,
arrayOfDefs,
attachDescription,
boolean,
borderOptionsDef,
callback,
callbackDefs,
callbackOf,
color,
colorUnion,
date,
defined,
fillOptionsDef,
fontOptionsDef,
greaterThan,
highlightOptionsDef,
htmlElement,
isValidNumberFormat,
labelBoxOptionsDef,
lessThan,
lineDashOptionsDef,
number,
object,
optionsDefs,
or,
padding,
positiveNumber,
ratio,
required,
shapeHighlightOptionsDef,
string,
strokeOptionsDef,
typeUnion,
undocumented,
union,
validate
} from "ag-charts-core";
// packages/ag-charts-types/src/chart/navigatorOptions.ts
var __MINI_CHART_SERIES_OPTIONS = void 0;
var __VERIFY_MINI_CHART_SERIES_OPTIONS = void 0;
__VERIFY_MINI_CHART_SERIES_OPTIONS = __MINI_CHART_SERIES_OPTIONS;
// packages/ag-charts-types/src/chart/themeOptions.ts
var __THEME_OVERRIDES = void 0;
var __VERIFY_THEME_OVERRIDES = void 0;
__VERIFY_THEME_OVERRIDES = __THEME_OVERRIDES;
// packages/ag-charts-types/src/presets/gauge/commonOptions.ts
var __THEMEABLE_OPTIONS = void 0;
var __VERIFY_THEMEABLE_OPTIONS = void 0;
__VERIFY_THEMEABLE_OPTIONS = __THEMEABLE_OPTIONS;
var __AXIS_LABEL_OPTIONS = void 0;
var __VERIFY_AXIS_LABEL_OPTIONS = void 0;
__VERIFY_AXIS_LABEL_OPTIONS = __AXIS_LABEL_OPTIONS;
// packages/ag-charts-community/src/chart/commonOptionsDefs.ts
var legendPlacementLiterals = [
"top",
"top-right",
"top-left",
"bottom",
"bottom-right",
"bottom-left",
"right",
"right-top",
"right-bottom",
"left",
"left-top",
"left-bottom"
];
var legendPositionOptionsDef = {
floating: boolean,
placement: union(...legendPlacementLiterals),
xOffset: number,
yOffset: number
};
var legendPositionValidator = attachDescription(
(value, context) => {
let result;
if (typeof value === "string") {
const allowedValues = legendPlacementLiterals;
if (allowedValues.includes(value)) {
result = true;
} else {
result = { valid: false, invalid: [], cleared: null };
result.invalid.push(
new ValidationError(
ErrorType.Invalid,
`a legend placement string: ["${legendPlacementLiterals.join('", "')}"]`,
value,
context.path
)
);
}
} else {
const { cleared, invalid } = validate(value, legendPositionOptionsDef);
result = { valid: invalid.length === 0, cleared, invalid };
}
return result;
},
`a legend position object or placement string`
);
var shapeValidator = or(
union("circle", "cross", "diamond", "heart", "plus", "pin", "square", "star", "triangle"),
callback
);
var textWrapValidator = union("never", "always", "hyphenate", "on-space");
var tooltipPlacementValidator = union(
"top",
"right",
"bottom",
"left",
"top-right",
"bottom-right",
"bottom-left",
"top-left",
"center"
);
var rangeValidator = or(positiveNumber, union("exact", "nearest"));
var textOrSegments = or(
string,
arrayOfDefs(
{
text: required(string),
...fontOptionsDef
},
"text segments array"
)
);
var zoomAnchorPoint = union("pointer", "start", "middle", "end");
var chartCaptionOptionsDefs = {
enabled: boolean,
text: textOrSegments,
textAlign: union("left", "center", "right"),
wrapping: union("never", "always", "hyphenate", "on-space"),
spacing: positiveNumber,
maxWidth: positiveNumber,
maxHeight: positiveNumber,
...fontOptionsDef
};
chartCaptionOptionsDefs.padding = undocumented(positiveNumber);
var chartOverlayOptionsDefs = {
enabled: boolean,
text: textOrSegments,
renderer: callbackOf(or(string, htmlElement))
};
var contextMenuItemLiterals = [
"defaults",
"download",
"zoom-to-cursor",
"pan-to-cursor",
"reset-zoom",
"toggle-series-visibility",
"toggle-other-series",
"separator"
];
var contextMenuItemObjectDef = {
type: union("action", "separator"),
showOn: union("always", "series-area", "series-node", "legend-item"),
label: required(string),
enabled: boolean,
action: callback,
items: (value, context) => contextMenuItemsArray(value, context)
};
contextMenuItemObjectDef.iconUrl = undocumented(string);
var contextMenuItemObjectValidator = optionsDefs(contextMenuItemObjectDef);
var contextMenuItemValidator = attachDescription(
(value, context) => {
let result;
if (typeof value === "string") {
const allowedValues = contextMenuItemLiterals;
if (allowedValues.includes(value)) {
result = true;
} else {
result = { valid: false, invalid: [], cleared: null };
result.invalid.push(
new ValidationError(
ErrorType.Invalid,
`a context menu item string alias: ["${contextMenuItemLiterals.join('", "')}"]`,
value,
context.path
)
);
}
} else {
result = contextMenuItemObjectValidator(value, context);
}
return result;
},
`a context menu item object or string alias: [${contextMenuItemLiterals.join(", ")}]`
);
var contextMenuItemsArray = arrayOf(contextMenuItemValidator, "a menu items array", false);
var toolbarButtonOptionsDefs = {
label: string,
ariaLabel: string,
tooltip: string,
icon: union(
"align-center",
"align-left",
"align-right",
"arrow-drawing",
"arrow-down-drawing",
"arrow-up-drawing",
"callout-annotation",
"candlestick-series",
"close",
"comment-annotation",
"date-range-drawing",
"date-price-range-drawing",
"delete",
"disjoint-channel-drawing",
"drag-handle",
"fill-color",
"line-style-solid",
"line-style-dashed",
"line-style-dotted",
"high-low-series",
"hlc-series",
"hollow-candlestick-series",
"horizontal-line-drawing",
"line-color",
"line-series",
"line-with-markers-series",
"locked",
"measurer-drawing",
"note-annotation",
"ohlc-series",
"pan-end",
"pan-left",
"pan-right",
"pan-start",
"parallel-channel-drawing",
"position-bottom",
"position-center",
"position-top",
"price-label-annotation",
"price-range-drawing",
"reset",
"settings",
"step-line-series",
"text-annotation",
"trend-line-drawing",
"fibonacci-retracement-drawing",
"fibonacci-retracement-trend-based-drawing",
"unlocked",
"vertical-line-drawing",
"zoom-in",
"zoom-out"
)
};
var formatter = or(string, callbackOf(string));
var formatObjectValidator = optionsDefs({
x: formatter,
y: formatter,
angle: formatter,
radius: formatter,
size: formatter,
color: formatter,
label: formatter,
secondaryLabel: formatter,
sectorLabel: formatter,
calloutLabel: formatter,
legendItem: formatter
});
var numberFormatValidator = attachDescription(isValidNumberFormat, "a valid number format string");
var commonChartOptionsDefs = {
width: positiveNumber,
height: positiveNumber,
minWidth: positiveNumber,
minHeight: positiveNumber,
suppressFieldDotNotation: boolean,
title: chartCaptionOptionsDefs,
subtitle: chartCaptionOptionsDefs,
footnote: chartCaptionOptionsDefs,
padding: {
top: positiveNumber,
right: positiveNumber,
bottom: positiveNumber,
left: positiveNumber
},
seriesArea: {
border: borderOptionsDef,
clip: boolean,
cornerRadius: number,
padding
},
legend: {
enabled: boolean,
position: legendPositionValidator,
orientation: union("horizontal", "vertical"),
maxWidth: positiveNumber,
maxHeight: positiveNumber,
spacing: positiveNumber,
border: borderOptionsDef,
cornerRadius: number,
padding,
fill: colorUnion,
fillOpacity: ratio,
preventHidingAll: boolean,
reverseOrder: boolean,
toggleSeries: boolean,
item: {
marker: {
size: positiveNumber,
shape: shapeValidator,
padding: positiveNumber,
strokeWidth: positiveNumber
},
line: {
length: positiveNumber,
strokeWidth: positiveNumber
},
label: {
maxLength: positiveNumber,
formatter: callback,
...fontOptionsDef
},
maxWidth: positiveNumber,
paddingX: positiveNumber,
paddingY: positiveNumber,
showSeriesStroke: boolean
},
pagination: {
marker: {
size: positiveNumber,
shape: shapeValidator,
padding: positiveNumber
},
activeStyle: {
...fillOptionsDef,
...strokeOptionsDef
},
inactiveStyle: {
...fillOptionsDef,
...strokeOptionsDef
},
highlightStyle: {
...fillOptionsDef,
...strokeOptionsDef
},
label: fontOptionsDef
},
listeners: {
legendItemClick: callback,
legendItemDoubleClick: callback
}
},
gradientLegend: {
enabled: boolean,
position: legendPositionValidator,
spacing: positiveNumber,
reverseOrder: boolean,
border: borderOptionsDef,
cornerRadius: number,
padding,
fill: colorUnion,
fillOpacity: ratio,
gradient: {
preferredLength: positiveNumber,
thickness: positiveNumber
},
scale: {
label: {
...fontOptionsDef,
minSpacing: positiveNumber,
format: numberFormatValidator,
formatter: callback
},
padding: positiveNumber,
interval: {
step: number,
values: array,
minSpacing: and(positiveNumber, lessThan("maxSpacing")),
maxSpacing: and(positiveNumber, greaterThan("minSpacing"))
}
}
},
listeners: {
seriesNodeClick: callback,
seriesNodeDoubleClick: callback,
seriesVisibilityChange: callback,
click: callback,
doubleClick: callback,
annotations: callback,
zoom: callback
},
loadGoogleFonts: boolean,
highlight: {
range: union("tooltip", "node")
},
overlays: {
loading: chartOverlayOptionsDefs,
noData: chartOverlayOptionsDefs,
noVisibleSeries: chartOverlayOptionsDefs,
unsupportedBrowser: chartOverlayOptionsDefs
},
tooltip: {
enabled: boolean,
showArrow: boolean,
pagination: boolean,
delay: positiveNumber,
range: rangeValidator,
wrapping: textWrapValidator,
mode: union("single", "shared", "compact"),
position: {
anchorTo: union("pointer", "node", "chart"),
placement: or(tooltipPlacementValidator, arrayOf(tooltipPlacementValidator)),
xOffset: number,
yOffset: number
}
},
animation: {
enabled: boolean,
duration: positiveNumber
},
contextMenu: {
enabled: boolean,
items: contextMenuItemsArray
},
context: () => true,
dataSource: {
getData: callback
},
keyboard: {
enabled: boolean,
tabIndex: number
},
touch: {
dragAction: union("none", "drag", "hover")
},
ranges: {
enabled: boolean,
buttons: arrayOfDefs(
{
...toolbarButtonOptionsDefs,
value: or(number, and(arrayOf(or(number, date)), arrayLength(2, 2)), callback)
},
"range button options array"
)
},
// modules
locale: {
localeText: object,
getLocaleText: callbackOf(string)
},
background: {
visible: boolean,
fill: color,
// enterprise
image: {
url: required(string),
top: number,
right: number,
bottom: number,
left: number,
width: positiveNumber,
height: positiveNumber,
opacity: ratio
}
},
styleNonce: string,
sync: {
enabled: boolean,
groupId: string,
axes: union("x", "y", "xy"),
nodeInteraction: boolean,
zoom: boolean
},
zoom: {
enabled: boolean,
enableAxisDragging: boolean,
enableAxisScrolling: boolean,
enableDoubleClickToReset: boolean,
enablePanning: boolean,
enableScrolling: boolean,
enableSelecting: boolean,
enableTwoFingerZoom: boolean,
keepAspectRatio: boolean,
anchorPointX: zoomAnchorPoint,
anchorPointY: zoomAnchorPoint,
axisDraggingMode: union("pan", "zoom"),
axes: union("x", "y", "xy"),
deceleration: or(union("off", "short", "long"), ratio),
minVisibleItems: positiveNumber,
panKey: union("alt", "ctrl", "meta", "shift"),
scrollingStep: ratio,
autoScaling: {
enabled: boolean,
padding: ratio
},
buttons: {
enabled: boolean,
buttons: arrayOfDefs(
{
...toolbarButtonOptionsDefs,
value: union("reset", "zoom-in", "zoom-out", "pan-left", "pan-right", "pan-start", "pan-end"),
section: string
},
"zoom button options array"
),
visible: union("always", "zoomed", "hover")
}
},
formatter: or(callbackOf(string), formatObjectValidator)
};
commonChartOptionsDefs.dataSource.requestThrottle = undocumented(positiveNumber);
commonChartOptionsDefs.dataSource.updateThrottle = undocumented(positiveNumber);
commonChartOptionsDefs.dataSource.updateDuringInteraction = undocumented(boolean);
commonChartOptionsDefs.zoom.enableIndependentAxes = undocumented(boolean);
commonChartOptionsDefs.statusBar = undocumented(defined);
commonChartOptionsDefs.foreground = undocumented({
visible: boolean,
text: string,
image: {
url: string,
top: number,
right: number,
bottom: number,
left: number,
width: positiveNumber,
height: positiveNumber,
opacity: ratio
},
...fillOptionsDef
});
commonChartOptionsDefs.overrideDevicePixelRatio = undocumented(number);
commonChartOptionsDefs.sync.domainMode = undocumented(union("direction", "position", "key"));
var commonSeriesThemeableOptionsDefs = {
cursor: string,
context: () => true,
showInLegend: boolean,
nodeClickRange: rangeValidator,
listeners: {
seriesNodeClick: callback,
seriesNodeDoubleClick: callback
},
// TODO Remove in next major version
highlightStyle: {
item: { ...fillOptionsDef, ...strokeOptionsDef },
series: {
enabled: boolean,
dimOpacity: ratio,
strokeWidth: positiveNumber
}
},
highlight: highlightOptionsDef(shapeHighlightOptionsDef)
};
var commonSeriesOptionsDefs = {
...commonSeriesThemeableOptionsDefs,
id: string,
visible: boolean,
context: () => true,
data: array
};
commonSeriesOptionsDefs.seriesGrouping = undocumented(defined);
var markerOptionsDefs = {
enabled: boolean,
shape: shapeValidator,
size: positiveNumber,
itemStyler: callbackDefs({
...fillOptionsDef,
...strokeOptionsDef,
...lineDashOptionsDef,
shape: shapeValidator,
size: positiveNumber
}),
...fillOptionsDef,
...strokeOptionsDef,
...lineDashOptionsDef
};
var seriesLabelOptionsDefs = {
enabled: boolean,
formatter: callback,
format: numberFormatValidator,
itemStyler: undocumented(
callbackDefs({
enabled: boolean,
...labelBoxOptionsDef,
...fontOptionsDef
})
),
...labelBoxOptionsDef,
...fontOptionsDef
};
var autoSizedLabelOptionsDefs = {
...seriesLabelOptionsDefs,
lineHeight: positiveNumber,
minimumFontSize: positiveNumber,
wrapping: textWrapValidator,
overflowStrategy: union("ellipsis", "hide")
};
var errorBarThemeableOptionsDefs = {
visible: boolean,
cap: {
visible: boolean,
length: positiveNumber,
lengthRatio: ratio,
...strokeOptionsDef,
...lineDashOptionsDef
},
...strokeOptionsDef,
...lineDashOptionsDef
};
var errorBarOptionsDefs = {
...errorBarThemeableOptionsDefs,
xLowerKey: string,
xUpperKey: string,
yLowerKey: string,
yUpperKey: string,
xLowerName: string,
xUpperName: string,
yLowerName: string,
yUpperName: string,
itemStyler: callbackDefs({
visible: boolean,
...strokeOptionsDef,
...lineDashOptionsDef,
cap: {
visible: boolean,
length: positiveNumber,
lengthRatio: ratio,
...strokeOptionsDef,
...lineDashOptionsDef
}
})
};
var tooltipOptionsDefs = {
enabled: boolean,
showArrow: boolean,
range: rangeValidator,
renderer: callbackOf(
or(
string,
optionsDefs(
{
heading: string,
title: string,
data: arrayOfDefs({
label: required(string),
value: required(string)
})
},
"tooltip renderer result object"
)
)
),
position: {
anchorTo: union("node", "pointer", "chart"),
placement: or(tooltipPlacementValidator, arrayOf(tooltipPlacementValidator)),
xOffset: number,
yOffset: number
},
interaction: {
enabled: boolean
}
};
var shadowOptionsDefs = {
enabled: boolean,
xOffset: number,
yOffset: number,
blur: positiveNumber,
color
};
var interpolationOptionsDefs = typeUnion(
{
linear: {},
smooth: {
tension: ratio
},
step: {
position: union("start", "middle", "end")
}
},
"interpolation line options"
);
// packages/ag-charts-community/src/chart/series/cartesian/areaSeriesOptionsDef.ts
import {
boolean as boolean2,
constant,
fillOptionsDef as fillOptionsDef2,
lineDashOptionsDef as lineDashOptionsDef2,
multiSeriesHighlightOptionsDef,
number as number2,
required as required2,
shapeHighlightOptionsDef as shapeHighlightOptionsDef2,
string as string2,
strokeOptionsDef as strokeOptionsDef2
} from "ag-charts-core";
var highlight = multiSeriesHighlightOptionsDef(shapeHighlightOptionsDef2, shapeHighlightOptionsDef2);
var areaSeriesThemeableOptionsDef = {
showInMiniChart: boolean2,
connectMissingData: boolean2,
interpolation: interpolationOptionsDefs,
label: seriesLabelOptionsDefs,
marker: markerOptionsDefs,
tooltip: tooltipOptionsDefs,
shadow: shadowOptionsDefs,
...commonSeriesThemeableOptionsDefs,
...fillOptionsDef2,
...strokeOptionsDef2,
...lineDashOptionsDef2,
highlight
};
var areaSeriesOptionsDef = {
...areaSeriesThemeableOptionsDef,
...commonSeriesOptionsDefs,
highlight,
type: required2(constant("area")),
xKey: required2(string2),
yKey: required2(string2),
xName: string2,
yName: string2,
stacked: boolean2,
stackGroup: string2,
normalizedTo: number2
};
// packages/ag-charts-community/src/chart/series/cartesian/barSeriesOptionsDef.ts
import {
barHighlightOptionsDef,
boolean as boolean3,
callbackDefs as callbackDefs2,
constant as constant2,
fillOptionsDef as fillOptionsDef3,
lineDashOptionsDef as lineDashOptionsDef3,
multiSeriesHighlightOptionsDef as multiSeriesHighlightOptionsDef2,
number as number3,
positiveNumber as positiveNumber2,
required as required3,
string as string3,
strokeOptionsDef as strokeOptionsDef3,
undocumented as undocumented2,
union as union2
} from "ag-charts-core";
var highlight2 = multiSeriesHighlightOptionsDef2(barHighlightOptionsDef, barHighlightOptionsDef);
var barSeriesThemeableOptionsDef = {
direction: union2("horizontal", "vertical"),
showInMiniChart: boolean3,
cornerRadius: positiveNumber2,
itemStyler: callbackDefs2({
...fillOptionsDef3,
...strokeOptionsDef3,
...lineDashOptionsDef3,
cornerRadius: positiveNumber2
}),
crisp: boolean3,
label: {
...seriesLabelOptionsDefs,
placement: union2("inside-center", "inside-start", "inside-end", "outside-start", "outside-end"),
spacing: positiveNumber2
},
errorBar: errorBarThemeableOptionsDefs,
shadow: shadowOptionsDefs,
tooltip: tooltipOptionsDefs,
...commonSeriesThemeableOptionsDefs,
highlight: highlight2,
...fillOptionsDef3,
...strokeOptionsDef3,
...lineDashOptionsDef3
};
barSeriesThemeableOptionsDef.sparklineMode = undocumented2(boolean3);
var barSeriesOptionsDef = {
...barSeriesThemeableOptionsDef,
...commonSeriesOptionsDefs,
highlight: highlight2,
type: required3(constant2("bar")),
xKey: required3(string3),
yKey: required3(string3),
xName: string3,
yName: string3,
direction: union2("horizontal", "vertical"),
grouped: boolean3,
stacked: boolean3,
stackGroup: string3,
normalizedTo: number3,
legendItemName: string3,
errorBar: errorBarOptionsDefs
};
barSeriesOptionsDef.pickOutsideVisibleMinorAxis = undocumented2(boolean3);
barSeriesOptionsDef.focusPriority = undocumented2(number3);
// packages/ag-charts-community/src/chart/series/cartesian/lineSeriesOptionsDef.ts
import {
boolean as boolean4,
constant as constant3,
lineDashOptionsDef as lineDashOptionsDef4,
lineHighlightOptionsDef,
multiSeriesHighlightOptionsDef as multiSeriesHighlightOptionsDef3,
number as number4,
required as required4,
shapeHighlightOptionsDef as shapeHighlightOptionsDef3,
string as string4,
strokeOptionsDef as strokeOptionsDef4,
undocumented as undocumented3
} from "ag-charts-core";
var highlight3 = multiSeriesHighlightOptionsDef3(shapeHighlightOptionsDef3, lineHighlightOptionsDef);
var lineSeriesThemeableOptionsDef = {
title: string4,
showInMiniChart: boolean4,
connectMissingData: boolean4,
interpolation: interpolationOptionsDefs,
label: seriesLabelOptionsDefs,
marker: markerOptionsDefs,
tooltip: tooltipOptionsDefs,
errorBar: errorBarThemeableOptionsDefs,
...commonSeriesThemeableOptionsDefs,
...strokeOptionsDef4,
...lineDashOptionsDef4,
highlight: highlight3
};
lineSeriesThemeableOptionsDef.sparklineMode = undocumented3(boolean4);
var lineSeriesOptionsDef = {
...lineSeriesThemeableOptionsDef,
...commonSeriesOptionsDefs,
highlight: highlight3,
type: required4(constant3("line")),
xKey: required4(string4),
yKey: required4(string4),
xName: string4,
yName: string4,
stacked: boolean4,
stackGroup: string4,
normalizedTo: number4,
legendItemName: string4,
errorBar: errorBarOptionsDefs
};
lineSeriesOptionsDef.pickOutsideVisibleMinorAxis = undocumented3(boolean4);
lineSeriesOptionsDef.focusPriority = undocumented3(number4);
// packages/ag-charts-community/src/util/object.ts
import { entries, isArray, isObject, isPlainObject } from "ag-charts-core";
// packages/ag-charts-community/src/util/decorator.ts
var BREAK_TRANSFORM_CHAIN = Symbol("BREAK");
var CONFIG_KEY = "__decorator_config";
var ACCESSORS_KEY = "__decorator_accessors";
function addFakeTransformToInstanceProperty(target, propertyKeyOrSymbol) {
initialiseConfig(target, propertyKeyOrSymbol).optional = true;
}
function initialiseConfig(target, propertyKeyOrSymbol) {
if (Object.getOwnPropertyDescriptor(target, CONFIG_KEY) == null) {
Object.defineProperty(target, CONFIG_KEY, { value: {} });
}
if (Object.getOwnPropertyDescriptor(target, ACCESSORS_KEY) == null) {
const parentAccessors = Object.getPrototypeOf(target)?.[ACCESSORS_KEY];
const accessors = parentAccessors?.slice() ?? [];
Object.defineProperty(target, ACCESSORS_KEY, { value: accessors });
}
const config = target[CONFIG_KEY];
const propertyKey = propertyKeyOrSymbol.toString();
if (config[propertyKey] != null) {
return config[propertyKey];
}
config[propertyKey] = { setters: [], getters: [], observers: [] };
const descriptor = Object.getOwnPropertyDescriptor(target, propertyKeyOrSymbol);
let prevGet = descriptor?.get;
let prevSet = descriptor?.set;
if (prevGet == null || prevSet == null) {
const accessors = target[ACCESSORS_KEY];
let index = accessors.indexOf(propertyKeyOrSymbol);
if (index === -1) {
index = accessors.push(propertyKeyOrSymbol) - 1;
}
prevGet ?? (prevGet = function() {
let accessorValues = this.__accessors;
if (accessorValues == null) {
accessorValues = accessors.slice().fill(void 0);
Object.defineProperty(this, "__accessors", { value: accessorValues });
}
return accessorValues[index];
});
prevSet ?? (prevSet = function(value) {
let accessorValues = this.__accessors;
if (accessorValues == null) {
accessorValues = accessors.slice().fill(void 0);
Object.defineProperty(this, "__accessors", { value: accessorValues });
}
accessorValues[index] = value;
});
}
const getter = function() {
let value = prevGet.call(this);
for (const transformFn of config[propertyKey].getters) {
value = transformFn(this, propertyKeyOrSymbol, value);
if (value === BREAK_TRANSFORM_CHAIN) {
return;
}
}
return value;
};
const setter = function(value) {
const { setters, observers } = config[propertyKey];
let oldValue;
if (setters.some((f) => f.length > 2)) {
oldValue = prevGet.call(this);
}
for (const transformFn of setters) {
value = transformFn(this, propertyKeyOrSymbol, value, oldValue);
if (value === BREAK_TRANSFORM_CHAIN) {
return;
}
}
prevSet.call(this, value);
for (const observerFn of observers) {
observerFn(this, value, oldValue);
}
};
Object.defineProperty(target, propertyKeyOrSymbol, {
set: setter,
get: getter,
enumerable: true,
configurable: false
});
return config[propertyKey];
}
function addTransformToInstanceProperty(setTransform, getTransform, configMetadata) {
return (target, propertyKeyOrSymbol) => {
const config = initialiseConfig(target, propertyKeyOrSymbol);
config.setters.push(setTransform);
if (getTransform) {
config.getters.unshift(getTransform);
}
if (configMetadata) {
Object.assign(config, configMetadata);
}
};
}
function addObserverToInstanceProperty(setObserver) {
return (target, propertyKeyOrSymbol) => {
initialiseConfig(target, propertyKeyOrSymbol).observers.push(setObserver);
};
}
function isDecoratedObject(target) {
return typeof target !== "undefined" && CONFIG_KEY in target;
}
function listDecoratedProperties(target) {
const targets = /* @__PURE__ */ new Set();
while (isDecoratedObject(target)) {
targets.add(target?.[CONFIG_KEY]);
target = Object.getPrototypeOf(target);
}
return Array.from(targets).flatMap((configMap) => Object.keys(configMap));
}
function extractDecoratedProperties(target) {
return listDecoratedProperties(target).reduce((result, key) => {
result[String(key)] = target[key] ?? null;
return result;
}, {});
}
// packages/ag-charts-community/src/util/object.ts
function objectsEqual(a, b) {
if (Array.isArray(a)) {
if (!Array.isArray(b))
return false;
if (a.length !== b.length)
return false;
return a.every((av, i) => objectsEqual(av, b[i]));
} else if (isPlainObject(a)) {
if (!isPlainObject(b))
return false;
return objectsEqualWith(a, b, objectsEqual);
}
return a === b;
}
function objectsEqualWith(a, b, cmp2) {
if (Object.is(a, b))
return true;
for (const key of Object.keys(b)) {
if (!(key in a))
return false;
}
for (const key of Object.keys(a)) {
if (!(key in b))
return false;
if (!cmp2(a[key], b[key]))
return false;
}
return true;
}
function mergeDefaults(...sources) {
const target = {};
for (const source of sources) {
if (!isObject(source))
continue;
const keys = isDecoratedObject(source) ? listDecoratedProperties(source) : Object.keys(source);
for (const key of keys) {
if (isPlainObject(target[key]) && isPlainObject(source[key])) {
target[key] = mergeDefaults(target[key], source[key]);
} else {
target[key] ?? (target[key] = source[key]);
}
}
}
return target;
}
function merge(...sources) {
const target = {};
for (const source of sources) {
if (!isObject(source))
continue;
const keys = isDecoratedObject(source) ? listDecoratedProperties(source) : Object.keys(source);
for (const key of keys) {
if (isPlainObject(target[key]) && isPlainObject(source[key])) {
target[key] = merge(target[key], source[key]);
} else if (!(key in target)) {
target[key] ?? (target[key] = source[key]);
}
}
}
return target;
}
function mergeArrayDefaults(dataArray, ...itemDefaults) {
if (itemDefaults && isArray(dataArray)) {
return dataArray.map((item) => mergeDefaults(item, ...itemDefaults));
}
return dataArray;
}
function without(object3, keys) {
const clone2 = { ...object3 };
for (const key of keys) {
delete clone2[key];
}
return clone2;
}
function getPath(object3, path) {
const pathArray = isArray(path) ? path : path.split(".");
return pathArray.reduce((value, pathKey) => value[pathKey], object3);
}
var SKIP_JS_BUILTINS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
function setPath(object3, path, newValue) {
const pathArray = isArray(path) ? path.slice() : path.split(".");
const lastKey = pathArray.pop();
if (pathArray.some((p) => SKIP_JS_BUILTINS.has(p)))
return;
const lastObject = pathArray.reduce((value, pathKey) => value[pathKey], object3);
lastObject[lastKey] = newValue;
return lastObject[lastKey];
}
function partialAssign(keysToCopy, target, source) {
if (source === void 0) {
return target;
}
for (const key of keysToCopy) {
const value = source[key];
if (value !== void 0) {
target[key] = value;
}
}
return target;
}
function deepFreeze(obj) {
if (obj == null || typeof obj !== "object" || !isPlainObject(obj)) {
return obj;
}
Object.freeze(obj);
Object.getOwnPropertyNames(obj).forEach((prop) => {
const value = obj[prop];
if (value !== null && (typeof value === "object" || typeof value === "function") && !Object.isFrozen(value)) {
deepFreeze(value);
}
});
return obj;
}
// packages/ag-charts-community/src/api/preset/presetUtils.ts
var IGNORED_PROP = Symbol("IGNORED_PROP");
function pickProps(opts, values) {
const out = {};
for (const key of Object.keys(values)) {
const value = values[key];
if (value !== IGNORED_PROP && Object.hasOwn(opts, key)) {
out[key] = value;
}
}
return out;
}
// packages/ag-charts-community/src/api/preset/gauge.ts
function tooltipOptions(opts) {
const { enabled, mode, showArrow, range: range3, position, pagination, delay, wrapping, interaction, renderer, ...rest } = opts;
const seriesTooltipOptions = pickProps(opts, {
enabled,
showArrow,
range: range3,
position,
interaction,
renderer,
...rest
});
const chartTooltipOptions = pickProps(opts, {
enabled: IGNORED_PROP,
showArrow: IGNORED_PROP,
range: IGNORED_PROP,
position: IGNORED_PROP,
mode,
pagination,
delay,
wrapping,
...rest
});
return { chartTooltipOptions, seriesTooltipOptions };
}
function radialGaugeOptions(opts) {
const {
animation,
background,
container,
contextMenu,
context,
footnote,
height: height2,
listeners,
locale,
minHeight,
minWidth,
overrideDevicePixelRatio,
padding: padding2,
subtitle,
theme,
title,
width: width2,
type,
cursor,
nodeClickRange,
tooltip = {},
value,
scale: scale2 = {},
startAngle,
endAngle,
// eslint-disable-next-line sonarjs/deprecation
highlightStyle,
highlight: highlight5,
segmentation,
bar,
needle,
targets,
outerRadius,
innerRadius,
outerRadiusRatio,
innerRadiusRatio,
cornerRadius,
cornerMode,
label,
secondaryLabel,
spacing,
...rest
} = opts;
const { chartTooltipOptions, seriesTooltipOptions } = tooltipOptions(tooltip);
const chartOpts = pickProps(opts, {
animation,
background,
container,
contextMenu,
context,
footnote,
height: height2,
listeners,
locale,
minHeight,
minWidth,
overrideDevicePixelRatio,
padding: padding2,
subtitle,
theme,
title,
tooltip: chartTooltipOptions,
width: width2
});
const seriesOpts = pickProps(opts, {
needle: needle != null ? { enabled: true, ...needle } : IGNORED_PROP,
startAngle,
endAngle,
scale: scale2,
type,
cursor,
context,
nodeClickRange,
tooltip: seriesTooltipOptions,
value,
highlightStyle,
highlight: highlight5,
segmentation,
bar,
targets,
outerRadius,
innerRadius,
outerRadiusRatio,
innerRadiusRatio,
cornerRadius,
cornerMode,
label,
secondaryLabel,
spacing,
...rest
});
return {
...chartOpts,
series: [seriesOpts]
};
}
function linearGaugeOptions(opts) {
const {
animation,
background,
container,
contextMenu,
context,
footnote,
height: height2,
listeners,
locale,
minHeight,
minWidth,
overrideDevicePixelRatio,
padding: padding2,
subtitle,
theme,
title,
width: width2,
type,
cursor,
nodeClickRange,
tooltip = {},
value,
scale: scale2 = {},
direction = "vertical",
thickness,
// eslint-disable-next-line sonarjs/deprecation
highlightStyle,
highlight: highlight5,
segmentation,
bar,
targets,
cornerRadius,
cornerMode,
label,
...rest
} = opts;
const { chartTooltipOptions, seriesTooltipOptions } = tooltipOptions(tooltip);
const chartOpts = pickProps(opts, {
animation,
background,
container,
contextMenu,
context,
footnote,
height: height2,
listeners,
locale,
minHeight,
minWidth,
overrideDevicePixelRatio,
padding: padding2,
subtitle,
theme,
title,
tooltip: chartTooltipOptions,
width: width2
});
const seriesOpts = pickProps(opts, {
scale: scale2,
type,
cursor,
context,
nodeClickRange,
tooltip: seriesTooltipOptions,
value,
direction,
thickness,
highlightStyle,
highlight: highlight5,
segmentation,
bar,
targets,
cornerRadius,
cornerMode,
label,
...rest
});
return {
...chartOpts,
series: [seriesOpts]
};
}
function applyThemeDefaults(opts, presetTheme) {
if (presetTheme == null)
return opts;
const { targets: targetsTheme, ...gaugeTheme } = presetTheme;
opts = mergeDefaults(opts, gaugeTheme);
if (opts.targets != null && targetsTheme != null) {
opts.targets = mergeArrayDefaults(opts.targets, targetsTheme);
}
return opts;
}
function gauge(opts, presetTheme) {
switch (opts.type) {
case "radial-gauge":
return radialGaugeOptions(applyThemeDefaults(opts, presetTheme));
case "linear-gauge":
return linearGaugeOptions(applyThemeDefaults(opts, presetTheme));
default:
return {};
}
}
// packages/ag-charts-community/src/api/preset/gaugeOptionsDefs.ts
import {
and as and2,
arrayLength as arrayLength2,
arrayOf as arrayOf2,
arrayOfDefs as arrayOfDefs2,
boolean as boolean5,
callback as callback2,
color as color2,
colorStopsOrderValidator,
constant as constant4,
fillOptionsDef as fillOptionsDef4,
fontOptionsDef as fontOptionsDef2,
greaterThan as greaterThan2,
lessThan as lessThan2,
lineDashOptionsDef as lineDashOptionsDef5,
number as number5,
optionsDefs as optionsDefs2,
or as or2,
positiveNumber as positiveNumber3,
ratio as ratio2,
required as required5,
string as string5,
strokeOptionsDef as strokeOptionsDef5,
undocumented as undocumented4,
union as union3
} from "ag-charts-core";
var fillsOptionsDef = {
fills: and2(
arrayLength2(2),
arrayOf2(optionsDefs2({ color: color2, stop: number5 }, "")),
colorStopsOrderValidator
),
fillMode: union3("continuous", "discrete")
};
var linearGaugeTargetOptionsDef = {
value: required5(number5),
text: string5,
shape: or2(
union3("circle", "cross", "diamond", "heart", "plus", "pin", "square", "star", "triangle", "line"),
callback2
),
placement: union3("before", "after", "middle"),
spacing: positiveNumber3,
size: positiveNumber3,
rotation: number5,
...fillOptionsDef4,
...strokeOptionsDef5,
...lineDashOptionsDef5
};
var radialGaugeTargetOptionsDef = {
value: required5(number5),
text: string5,
shape: or2(
union3("circle", "cross", "diamond", "heart", "plus", "pin", "square", "star", "triangle", "line"),
callback2
),
placement: union3("inside", "outside", "middle"),
spacing: positiveNumber3,
size: positiveNumber3,
rotation: number5,
label: {
...seriesLabelOptionsDefs,
spacing: positiveNumber3
},
...fillOptionsDef4,
...strokeOptionsDef5,
...lineDashOptionsDef5
};
var linearGaugeSeriesThemeableOptionsDef = {
direction: union3("horizontal", "vertical"),
cornerMode: union3("container", "item"),
cornerRadius: positiveNumber3,
thickness: positiveNumber3,
segmentation: {
enabled: boolean5,
spacing: positiveNumber3,
interval: {
values: arrayOf2(number5),
step: number5,
count: number5
}
},
bar: {
enabled: boolean5,
thickness: positiveNumber3,
thicknessRatio: ratio2,
...fillsOptionsDef,
...fillOptionsDef4,
...strokeOptionsDef5,
...lineDashOptionsDef5
},
label: {
...autoSizedLabelOptionsDefs,
text: string5,
spacing: positiveNumber3,
avoidCollisions: boolean5,
placement: union3(
"inside-start",
"outside-start",
"inside-end",
"outside-end",
"inside-center",
"bar-inside",
"bar-inside-end",
"bar-outside-end",
"bar-end"
)
},
tooltip: tooltipOptionsDefs,
...without(commonSeriesThemeableOptionsDefs, ["listeners"])
};
var linearGaugeSeriesOptionsDef = {
...linearGaugeSeriesThemeableOptionsDef,
...without(commonSeriesOptionsDefs, ["listeners"]),
type: required5(constant4("linear-gauge")),
value: required5(number5),
scale: {
min: and2(number5, lessThan2("max")),
max: and2(number5, greaterThan2("min")),
label: {
enabled: boolean5,
formatter: callback2,
rotation: number5,
spacing: positiveNumber3,
minSpacing: positiveNumber3,
placement: union3("before", "after"),
avoidCollisions: boolean5,
format: numberFormatValidator,
...fontOptionsDef2
},
interval: {
values: arrayOf2(number5),
step: number5
},
...fillsOptionsDef,
...fillOptionsDef4,
...strokeOptionsDef5,
...lineDashOptionsDef5
},
targets: arrayOfDefs2(linearGaugeTargetOptionsDef, "target options array")
};
linearGaugeSeriesOptionsDef.margin = undocumented4(number5);
linearGaugeSeriesOptionsDef.defaultColorRange = undocumented4(arrayOf2(color2));
linearGaugeSeriesOptionsDef.defaultTarget = undocumented4({
...linearGaugeTargetOptionsDef,
value: number5,
label: {
...seriesLabelOptionsDefs,
spacing: number5
}
});
linearGaugeSeriesOptionsDef.defaultScale = undocumented4(linearGaugeSeriesOptionsDef.scale);
linearGaugeSeriesOptionsDef.scale.defaultFill = undocumented4(color2);
var radialGaugeSeriesThemeableOptionsDef = {
outerRadius: positiveNumber3,
innerRadius: positiveNumber3,
outerRadiusRatio: ratio2,
innerRadiusRatio: ratio2,
startAngle: number5,
endAngle: number5,
spacing: positiveNumber3,
cornerMode: union3("container", "item"),
cornerRadius: positiveNumber3,
scale: {
min: and2(number5, lessThan2("max")),
max: and2(number5, greaterThan2("min")),
label: {
enabled: boolean5,
formatter: callback2,
rotation: number5,
spacing: positiveNumber3,
minSpacing: positiveNumber3,
avoidCollisions: boolean5,
format: numberFormatValidator,
...fontOptionsDef2
},
interval: {
values: arrayOf2(number5),
step: number5
},
...fillsOptionsDef,
...fillOptionsDef4,
...strokeOptionsDef5,
...lineDashOptionsDef5
},
segmentation: {
enabled: boolean5,
spacing: positiveNumber3,
interval: {
values: arrayOf2(number5),
step: number5,
count: number5
}
},
bar: {
enabled: boolean5,
...fillsOptionsDef,
...fillOptionsDef4,
...strokeOptionsDef5,
...lineDashOptionsDef5
},
needle: {
enabled: boolean5,
spacing: positiveNumber3,
radiusRatio: ratio2,
...fillOptionsDef4,
...strokeOptionsDef5,
...lineDashOptionsDef5
},
label: {
text: string5,
spacing: positiveNumber3,
...autoSizedLabelOptionsDefs
},
secondaryLabel: {
text: string5,
...autoSizedLabelOptionsDefs
},
tooltip: tooltipOptionsDefs,
...commonSeriesThemeableOptionsDefs
};
var radialGaugeSeriesOptionsDef = {
...radialGaugeSeriesThemeableOptionsDef,
...commonSeriesOptionsDefs,
type: required5(constant4("radial-gauge")),
value: required5(number5),
targets: arrayOfDefs2(radialGaugeTargetOptionsDef, "target options array")
};
radialGaugeSeriesOptionsDef.defaultColorRange = undocumented4(arrayOf2(color2));
radialGaugeSeriesOptionsDef.defaultTarget = undocumented4({
...radialGaugeTargetOptionsDef,
value: number5,
label: {
...seriesLabelOptionsDefs,
spacing: number5
}
});
radialGaugeSeriesOptionsDef.scale.defaultFill = undocumented4(color2);
// packages/ag-charts-community/src/api/preset/priceVolumePreset.ts
import { Logger } from "ag-charts-core";
// packages/ag-charts-community/src/chart/themes/symbols.ts
var IS_DARK_THEME = Symbol("is-dark-theme");
var DEFAULT_SEPARATION_LINES_COLOUR = Symbol("default-separation-lines-colour");
var DEFAULT_SHADOW_COLOUR = Symbol("default-shadow-colour");
var DEFAULT_CAPTION_LAYOUT_STYLE = Symbol("default-caption-layout-style");
var DEFAULT_CAPTION_ALIGNMENT = Symbol("default-caption-alignment");
var PALETTE_UP_STROKE = Symbol("palette-up-stroke");
var PALETTE_DOWN_STROKE = Symbol("palette-down-stroke");
var PALETTE_UP_FILL = Symbol("palette-up-fill");
var PALETTE_DOWN_FILL = Symbol("palette-down-fill");
var PALETTE_NEUTRAL_STROKE = Symbol("palette-neutral-stroke");
var PALETTE_NEUTRAL_FILL = Symbol("palette-neutral-fill");
var PALETTE_ALT_UP_STROKE = Symbol("palette-alt-up-stroke");
var PALETTE_ALT_DOWN_STROKE = Symbol("palette-alt-down-stroke");
var PALETTE_ALT_UP_FILL = Symbol("palette-alt-up-fill");
var PALETTE_ALT_DOWN_FILL = Symbol("palette-alt-down-fill");
var PALETTE_ALT_NEUTRAL_FILL = Symbol("palette-gray-fill");
var PALETTE_ALT_NEUTRAL_STROKE = Symbol("palette-gray-stroke");
var DEFAULT_POLAR_SERIES_STROKE = Symbol("default-polar-series-stroke");
var DEFAULT_SPARKLINE_CROSSHAIR_STROKE = Symbol("default-sparkline-crosshair-stroke");
var DEFAULT_FINANCIAL_CHARTS_ANNOTATION_COLOR = Symbol(
"default-financial-charts-annotation-stroke"
);
var DEFAULT_FIBONACCI_STROKES = Symbol("default-hierarchy-strokes");
var DEFAULT_TEXT_ANNOTATION_COLOR = Symbol("default-text-annotation-color");
var DEFAULT_FINANCIAL_CHARTS_ANNOTATION_BACKGROUND_FILL = Symbol(
"default-financial-charts-annotation-background-fill"
);
var DEFAULT_ANNOTATION_HANDLE_FILL = Symbol("default-annotation-handle-fill");
var DEFAULT_ANNOTATION_STATISTICS_FILL = Symbol("default-annotation-statistics-fill");
var DEFAULT_ANNOTATION_STATISTICS_STROKE = Symbol("default-annotation-statistics-stroke");
var DEFAULT_ANNOTATION_STATISTICS_COLOR = Symbol("default-annotation-statistics-color");
var DEFAULT_ANNOTATION_STATISTICS_DIVIDER_STROKE = Symbol(
"default-annotation-statistics-divider-stroke"
);
var DEFAULT_ANNOTATION_STATISTICS_DOWN_FILL = Symbol(
"default-annotation-statistics-fill"
);
var DEFAULT_ANNOTATION_STATISTICS_DOWN_STROKE = Symbol(
"default-annotation-statistics-stroke"
);
var DEFAULT_TEXTBOX_FILL = Symbol("default-textbox-fill");
var DEFAULT_TEXTBOX_STROKE = Symbol("default-textbox-stroke");
var DEFAULT_TEXTBOX_COLOR = Symbol("default-textbox-color");
var DEFAULT_TOOLBAR_POSITION = Symbol("default-toolbar-position");
var DEFAULT_GRIDLINE_ENABLED = Symbol("default-gridline-enabled");
// packages/ag-charts-community/src/util/color.ts
import { clamp } from "ag-charts-core";
var lerp = (x, y, t) => x * (1 - t) + y * t;
var srgbToLinear = (value) => {
const sign = value < 0 ? -1 : 1;
const abs = Math.abs(value);
if (abs <= 0.04045)
return value / 12.92;
return sign * ((abs + 0.055) / 1.055) ** 2.4;
};
var srgbFromLinear = (value) => {
const sign = value < 0 ? -1 : 1;
const abs = Math.abs(value);
if (abs > 31308e-7) {
return sign * (1.055 * abs ** (1 / 2.4) - 0.055);
}
return 12.92 * value;
};
var _Color = class _Color {
/**
* Every color component should be in the [0, 1] range.
* Some easing functions (such as elastic easing) can overshoot the target value by some amount.
* So, when animating colors, if the source or target color components are already near
* or at the edge of the allowed [0, 1] range, it is possible for the intermediate color
* component value to end up outside of that range mid-animation. For this reason the constructor
* performs range checking/constraining.
* @param r Red component.
* @param g Green component.
* @param b Blue component.
* @param a Alpha (opacity) component.
*/
constructor(r, g, b, a = 1) {
this.r = clamp(0, r || 0, 1);
this.g = clamp(0, g || 0, 1);
this.b = clamp(0, b || 0, 1);
this.a = clamp(0, a || 0, 1);
}
/**
* A color string can be in one of the following formats to be valid:
* - #rgb
* - #rrggbb
* - rgb(r, g, b)
* - rgba(r, g, b, a)
* - CSS color name such as 'white', 'orange', 'cyan', etc.
*/
static validColorString(str) {
if (str.indexOf("#") >= 0) {
return !!_Color.parseHex(str);
}
if (str.indexOf("rgb") >= 0) {
return !!_Color.stringToRgba(str);
}
return _Color.nameToHex.has(str.toLowerCase());
}
/**
* The given string can be in one of the following formats:
* - #rgb
* - #rrggbb
* - rgb(r, g, b)
* - rgba(r, g, b, a)
* - CSS color name such as 'white', 'orange', 'cyan', etc.
* @param str
*/
static fromString(str) {
if (str.indexOf("#") >= 0) {
return _Color.fromHexString(str);
}
const hex = _Color.nameToHex.get(str.toLowerCase());
if (hex) {
return _Color.fromHexString(hex);
}
if (str.indexOf("rgb") >= 0) {
return _Color.fromRgbaString(str);
}
throw new Error(`Invalid color string: '${str}'`);
}
// See https://drafts.csswg.org/css-color/#hex-notation
static parseHex(input) {
input = input.replace(/ /g, "").slice(1);
let parts;
switch (input.length) {
case 6:
case 8:
parts = [];
for (let i = 0; i < input.length; i += 2) {
parts.push(parseInt(`${input[i]}${input[i + 1]}`, 16));
}
break;
case 3:
case 4:
parts = input.split("").map((p) => parseInt(p, 16)).map((p) => p + p * 16);
break;
}
if (parts?.length >= 3 && parts.every((p) => p >= 0)) {
if (parts.length === 3) {
parts.push(255);
}
return parts;
}
}
static fromHexString(str) {
const values = _Color.parseHex(str);
if (values) {
const [r, g, b, a] = values;
return new _Color(r / 255, g / 255, b / 255, a / 255);
}
throw new Error(`Malformed hexadecimal color string: '${str}'`);
}
static stringToRgba(str) {
let po = -1;
let pc = -1;
for (let i = 0; i < str.length; i++) {
const c = str[i];
if (po === -1 && c === "(") {
po = i;
} else if (c === ")") {
pc = i;
break;
}
}
if (po === -1 || pc === -1)
return;
const contents = str.substring(po + 1, pc);
const parts = contents.split(",");
const rgba = [];
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
let value = parseFloat(part);
if (!Number.isFinite(value)) {
return;
}
if (part.indexOf("%") >= 0) {
value = clamp(0, value, 100);
value /= 100;
} else if (i === 3) {
value = clamp(0, value, 1);
} else {
value = clamp(0, value, 255);
value /= 255;
}
rgba.push(value);
}
return rgba;
}
static fromRgbaString(str) {
const rgba = _Color.stringToRgba(str);
if (rgba) {
if (rgba.length === 3) {
return new _Color(rgba[0], rgba[1], rgba[2]);
} else if (rgba.length === 4) {
return new _Color(rgba[0], rgba[1], rgba[2], rgba[3]);
}
}
throw new Error(`Malformed rgb/rgba color string: '${str}'`);
}
static fromArray(arr) {
if (arr.length === 4) {
return new _Color(arr[0], arr[1], arr[2], arr[3]);
}
if (arr.length === 3) {
return new _Color(arr[0], arr[1], arr[2]);
}
throw new Error("The given array should contain 3 or 4 color components (numbers).");
}
static fromHSB(h, s, b, alpha = 1) {
const rgb = _Color.HSBtoRGB(h, s, b);
return new _Color(rgb[0], rgb[1], rgb[2], alpha);
}
static fromHSL(h, s, l, alpha = 1) {
const rgb = _Color.HSLtoRGB(h, s, l);
return new _Color(rgb[0], rgb[1], rgb[2], alpha);
}
static fromOKLCH(l, c, h, alpha = 1) {
const rgb = _Color.OKLCHtoRGB(l, c, h);
return new _Color(rgb[0], rgb[1], rgb[2], alpha);
}
static padHex(str) {
return str.length === 1 ? "0" + str : str;
}
toHexString() {
let hex = "#" + _Color.padHex(Math.round(this.r