import { createChart as untypedLcCreateChart, CandlestickSeries, HistogramSeries, LineSeries, BaselineSeries, // } from "../modules/lightweight-charts/5.1.0/dist/lightweight-charts.standalone.development.mjs"; } from "../modules/lightweight-charts/5.1.0/dist/lightweight-charts.standalone.production.mjs"; import { createLegend } from "./legend.js"; import { capture, canCapture } from "./capture.js"; import { colors } from "./colors.js"; import { createChoiceField } from "../utils/dom.js"; import { createPersistedValue } from "../utils/persisted.js"; import { onChange as onThemeChange } from "../utils/theme.js"; import { throttle, debounce } from "../utils/timing.js"; import { serdeBool, serdeChartableIndex } from "../utils/serde.js"; import { stringToId, numberToShortUSFormat } from "../utils/format.js"; import { style } from "../utils/elements.js"; /** * @typedef {_ISeriesApi} ISeries * @typedef {_ISeriesApi<'Candlestick'>} CandlestickISeries * @typedef {_ISeriesApi<'Histogram'>} HistogramISeries * @typedef {_ISeriesApi<'Line'>} LineISeries * @typedef {_ISeriesApi<'Baseline'>} BaselineISeries * * @typedef {_LineSeriesPartialOptions} LineSeriesPartialOptions * @typedef {_HistogramSeriesPartialOptions} HistogramSeriesPartialOptions * @typedef {_BaselineSeriesPartialOptions} BaselineSeriesPartialOptions * @typedef {_CandlestickSeriesPartialOptions} CandlestickSeriesPartialOptions */ /** * @template T * @typedef {Object} Series * @property {string} key * @property {string} id * @property {number} paneIndex * @property {PersistedValue} active * @property {(value: boolean) => void} setActive * @property {() => void} show * @property {() => void} hide * @property {(order: number) => void} setOrder * @property {() => void} highlight * @property {() => void} tame * @property {() => boolean} hasData * @property {() => void} [fetch] * @property {string | null} url * @property {() => readonly T[]} getData * @property {(data: T) => void} update * @property {VoidFunction} remove */ /** * @typedef {Series} AnySeries */ /** * @typedef {_SingleValueData} SingleValueData * @typedef {_CandlestickData} CandlestickData * @typedef {_LineData} LineData * @typedef {_BaselineData} BaselineData * @typedef {_HistogramData} HistogramData * * @typedef {Object} Legend * @property {HTMLLegendElement} element * @property {function({ series: AnySeries, name: string, order: number, colors: Color[] }): void} addOrReplace * @property {function(number): void} removeFrom */ const lineWidth = /** @type {any} */ (1.5); /** * @param {Object} args * @param {string} args.id * @param {HTMLElement} args.parent * @param {BrkClient} args.brk * @param {true} [args.fitContent] * @param {HTMLElement} [args.captureElement] * @param {{unit: Unit; blueprints: AnyFetchedSeriesBlueprint[]}[]} [args.config] */ export function createChart({ parent, id: chartId, brk, fitContent, captureElement, config, }) { const baseUrl = brk.baseUrl.replace(/\/$/, ""); /** @param {ChartableIndex} idx */ const getTimeEndpoint = (idx) => idx === "height" ? brk.metrics.blocks.time.timestampMonotonic.by[idx] : brk.metrics.blocks.time.timestamp.by[idx]; const index = { /** @type {Set<(index: ChartableIndex) => void>} */ onChange: new Set(), get() { return serdeChartableIndex.deserialize(index.name.value); }, name: createPersistedValue({ defaultValue: /** @type {ChartableIndexName} */ ("date"), storageKey: "chart-index", urlKey: "i", serialize: (v) => v, deserialize: (s) => /** @type {ChartableIndexName} */ (s), onChange: () => { range.set(null); index.onChange.forEach((cb) => cb(index.get())); }, }), }; // Range state: localStorage stores all ranges per-index, URL stores current range only /** @typedef {{ from: number, to: number }} Range */ const ranges = createPersistedValue({ defaultValue: /** @type {Record} */ ({}), storageKey: "chart-ranges", serialize: JSON.stringify, deserialize: JSON.parse, }); const range = createPersistedValue({ defaultValue: /** @type {Range | null} */ (null), urlKey: "r", serialize: (v) => (v ? `${v.from.toFixed(2)}_${v.to.toFixed(2)}` : ""), deserialize: (s) => { if (!s) return null; const [from, to] = s.split("_").map(Number); return !isNaN(from) && !isNaN(to) ? { from, to } : null; }, }); /** @returns {Range | null} */ const getRange = () => range.value ?? ranges.value[index.name.value] ?? null; /** @param {Range} value */ const setRange = (value) => { ranges.set({ ...ranges.value, [index.name.value]: value }); range.set(value); }; const legends = { top: createLegend(), bottom: createLegend(), }; const elements = { root: document.createElement("div"), chart: document.createElement("div"), setup() { elements.root.classList.add("chart"); elements.chart.classList.add("lightweight-chart"); parent.append(elements.root); elements.root.append(legends.top.element); elements.root.append(elements.chart); elements.root.append(legends.bottom.element); }, }; elements.setup(); const ichart = /** @type {CreateLCChart} */ (untypedLcCreateChart)( elements.chart, /** @satisfies {DeepPartial} */ ({ autoSize: true, layout: { fontFamily: style.fontFamily, background: { color: "transparent" }, attributionLogo: false, }, grid: { vertLines: { visible: false }, horzLines: { visible: false }, }, rightPriceScale: { borderVisible: false, }, timeScale: { borderVisible: false, enableConflation: true, // conflationThresholdFactor: 8, ...(fitContent ? { minBarSpacing: 0.001, } : {}), }, localization: { priceFormatter: numberToShortUSFormat, locale: "en-us", }, crosshair: { mode: 3, }, ...(fitContent ? { handleScale: false, handleScroll: false, } : {}), // ..._options, }), ); // Takes a bit more space sometimes but it's better UX than having the scale being resized on option change ichart.priceScale("right").applyOptions({ minimumWidth: 80, }); ichart.panes().at(0)?.setStretchFactor(1); /** @typedef {(visibleBarsCount: number) => void} ZoomChangeCallback */ const initialRange = getRange(); if (initialRange) { ichart.timeScale().setVisibleLogicalRange(initialRange); } let visibleBarsCount = initialRange ? initialRange.to - initialRange.from : Infinity; /** @type {Set} */ const onZoomChange = new Set(); ichart.timeScale().subscribeVisibleLogicalRangeChange( throttle((range) => { if (!range) return; const count = range.to - range.from; if (count === visibleBarsCount) return; visibleBarsCount = count; onZoomChange.forEach((cb) => cb(count)); }, 100), ); // Debounced range persistence ichart.timeScale().subscribeVisibleLogicalRangeChange( debounce((range) => { if (range && range.from < range.to) { setRange({ from: range.from, to: range.to }); } }, 100), ); function applyColors() { const defaultColor = colors.default(); const offColor = colors.gray(); const borderColor = colors.border(); ichart.applyOptions({ layout: { textColor: offColor, panes: { separatorColor: borderColor, }, }, crosshair: { horzLine: { color: offColor, labelBackgroundColor: defaultColor, }, vertLine: { color: offColor, labelBackgroundColor: defaultColor, }, }, }); } applyColors(); const removeThemeListener = onThemeChange(applyColors); /** @type {Partial>} */ const minBarSpacingByIndex = { monthindex: 1, quarterindex: 2, semesterindex: 3, yearindex: 6, decadeindex: 60, }; /** @param {ChartableIndex} index */ function applyIndexSettings(index) { const minBarSpacing = minBarSpacingByIndex[index] ?? 0.5; ichart.applyOptions({ timeScale: { timeVisible: index === "height", ...(!fitContent ? { minBarSpacing, } : {}), }, }); } applyIndexSettings(index.get()); index.onChange.add(applyIndexSettings); // Periodic refresh of active series data const refreshInterval = setInterval(() => serieses.refreshAll(), 30_000); if (fitContent) { new ResizeObserver(() => ichart.timeScale().fitContent()).observe( elements.chart, ); } const fieldsets = { /** @type {Map) => HTMLElement }>>} */ configs: new Map(), /** * @param {number} configPaneIndex * @param {number} [targetPaneIndex] */ createForPane(configPaneIndex, targetPaneIndex = configPaneIndex) { const pane = ichart.panes().at(targetPaneIndex); if (!pane) return; const parent = pane.getHTMLElement()?.children?.item(1)?.firstChild; if (!parent) return; const configs = this.configs.get(configPaneIndex); if (!configs) return; for (const { id, position, createChild } of configs.values()) { /** @type {Element} */ (parent) .querySelectorAll(`[data-position="${position}"]`) .forEach((el) => el.remove()); const fieldset = document.createElement("fieldset"); fieldset.dataset.size = "xs"; fieldset.dataset.position = position; fieldset.id = `${id}-${configPaneIndex}`; parent.appendChild(fieldset); fieldset.append(createChild(pane)); } }, /** * @param {Object} args * @param {string} args.id * @param {number} args.paneIndex * @param {"nw" | "ne" | "se" | "sw"} args.position * @param {(pane: IPaneApi