global: snapshot

This commit is contained in:
nym21
2026-01-20 15:04:00 +01:00
parent 486871379c
commit 9613fce919
53 changed files with 1811 additions and 4081 deletions

View File

@@ -1,5 +1,6 @@
import {
createChart as _createChart,
createSeriesMarkers,
CandlestickSeries,
HistogramSeries,
LineSeries,
@@ -35,15 +36,15 @@ import { resources } from "../resources.js";
* @template T
* @typedef {Object} Series
* @property {string} id
* @property {() => ISeries} inner
* @property {number} paneIndex
* @property {Signal<boolean>} active
* @property {Signal<boolean>} highlighted
* @property {Signal<boolean>} hasData
* @property {Signal<string | null>} url
* @property {() => Record<string, any>} getOptions
* @property {(options: Record<string, any>) => void} applyOptions
* @property {() => readonly T[]} getData
* @property {(data: T) => void} update
* @property {(markers: TimeSeriesMarker[]) => void} setMarkers
* @property {VoidFunction} clearMarkers
* @property {VoidFunction} remove
*/
@@ -97,6 +98,10 @@ export function createChartElement({
div.classList.add("chart");
parent.append(div);
// Registry for shared legend signals (same name = linked across panes)
/** @type {Map<string, Signal<boolean>>} */
const sharedActiveSignals = new Map();
const legendTop = createLegend(signals);
div.append(legendTop.element);
@@ -165,7 +170,10 @@ export function createChartElement({
});
};
const seriesList = signals.createSignal(/** @type {Set<AnySeries>} */ (new Set()), { equals: false });
const seriesList = signals.createSignal(
/** @type {Set<AnySeries>} */ (new Set()),
{ equals: false },
);
const seriesCount = signals.createMemo(() => seriesList().size);
const markers = createMinMaxMarkers({
chart: ichart,
@@ -186,7 +194,7 @@ export function createChartElement({
() => visibleBarsCountBucket() >= 2,
);
const shouldUpdateMarkers = signals.createMemo(
() => visibleBarsCount() * seriesCount() <= 5000,
() => visibleBarsCount() * seriesCount() <= 20_000,
);
signals.createEffect(shouldUpdateMarkers, (should) => {
@@ -337,12 +345,20 @@ export function createChartElement({
paneIndex,
position: "sw",
createChild(pane) {
const { field, selected } = createChoiceField({
const defaultValue =
unit.id === "usd" && seriesType !== "Baseline" ? "log" : "lin";
const selected = signals.createPersistedSignal({
defaultValue,
storageKey: `${id}-scale-${paneIndex}`,
urlKey: paneIndex === 0 ? "price_scale" : "unit_scale",
serialize: (v) => v,
deserialize: (s) => /** @type {"lin" | "log"} */ (s),
});
const field = createChoiceField({
choices: /** @type {const} */ (["lin", "log"]),
id: stringToId(`${id} ${paneIndex} ${unit}`),
defaultValue:
unit.id === "usd" && seriesType !== "Baseline" ? "log" : "lin",
key: `${id}-price-scale-${paneIndex}`,
defaultValue,
selected,
signals,
});
@@ -366,21 +382,19 @@ export function createChartElement({
* @param {number} args.order
* @param {Color[]} args.colors
* @param {LCSeriesType} args.seriesType
* @param {() => ISeries} args.inner
* @param {AnyMetricPattern} [args.metric]
* @param {Accessor<WhitespaceData[]>} [args.data]
* @param {number} args.paneIndex
* @param {boolean} [args.defaultActive]
* @param {(ctx: { active: Signal<boolean> }) => void} args.setup
* @param {(ctx: { active: Signal<boolean>, highlighted: Signal<boolean> }) => void} args.setup
* @param {() => readonly any[]} args.getData
* @param {(data: any[]) => void} args.setData
* @param {(data: any) => void} args.update
* @param {() => Record<string, any>} args.getOptions
* @param {(options: Record<string, any>) => void} args.applyOptions
* @param {(markers: TimeSeriesMarker[]) => void} args.setMarkers
* @param {VoidFunction} args.clearMarkers
* @param {() => void} args.onRemove
*/
function addSeries({
inner,
metric,
name,
unit,
@@ -394,22 +408,34 @@ export function createChartElement({
getData,
setData,
update,
getOptions,
applyOptions,
setMarkers,
clearMarkers,
onRemove,
}) {
return signals.createRoot((dispose) => {
const id = `${stringToId(name)}-${paneIndex}`;
const urlId = stringToId(name);
const active = signals.createSignal(defaultActive ?? true, {
save: {
keyPrefix: "",
key: id,
// Reuse existing signal if same name (links legends across panes)
let active = sharedActiveSignals.get(urlId);
if (!active) {
active = signals.createPersistedSignal({
defaultValue: defaultActive ?? true,
storageKey: id,
urlKey: urlId,
...serdeBool,
},
});
});
sharedActiveSignals.set(urlId, active);
}
setup({ active });
const highlighted = signals.createSignal(true);
setup({ active, highlighted });
// Update markers when active changes
signals.createEffect(active, () => {
if (shouldUpdateMarkers()) markers.scheduleUpdate();
});
const hasData = signals.createSignal(false);
let lastTime = -Infinity;
@@ -420,15 +446,15 @@ export function createChartElement({
/** @type {AnySeries} */
const series = {
active,
highlighted,
hasData,
id,
inner,
paneIndex,
url: signals.createSignal(/** @type {string | null} */ (null)),
getOptions,
applyOptions,
getData,
update,
setMarkers,
clearMarkers,
remove() {
dispose();
onRemove();
@@ -705,8 +731,10 @@ export function createChartElement({
)
);
// Marker plugin always on candlestick (has true min/max via high/low)
const markerPlugin = createSeriesMarkers(candlestickISeries, [], { autoScale: false });
const series = addSeries({
inner: () => (showLine ? lineISeries : candlestickISeries),
colors: [upColor, downColor],
name,
order,
@@ -716,22 +744,34 @@ export function createChartElement({
data,
defaultActive,
metric,
setup: ({ active }) => {
setup: ({ active, highlighted }) => {
candlestickISeries.setSeriesOrder(order);
lineISeries.setSeriesOrder(order);
signals.createEffect(
() => ({
shouldShow: shouldShowLine(),
active: active(),
highlighted: highlighted(),
barsCount: visibleBarsCount(),
}),
({ shouldShow, active, barsCount }) => {
({ shouldShow, active, highlighted, barsCount }) => {
if (barsCount === Infinity) return;
const wasLine = showLine;
showLine = shouldShow;
candlestickISeries.applyOptions({ visible: active && !showLine });
// Use transparent when showing the other mode, otherwise use highlight
const up = showLine ? "transparent" : upColor.highlight(highlighted);
const down = showLine ? "transparent" : downColor.highlight(highlighted);
const line = showLine ? colors.default.highlight(highlighted) : "transparent";
candlestickISeries.applyOptions({
visible: active,
upColor: up,
downColor: down,
wickUpColor: up,
wickDownColor: down,
});
lineISeries.applyOptions({
visible: active && showLine,
visible: active,
color: line,
priceLineVisible: active && showLine,
});
if (wasLine !== showLine && shouldUpdateMarkers())
@@ -749,12 +789,8 @@ export function createChartElement({
lineISeries.update({ time: data.time, value: data.close });
},
getData: () => candlestickISeries.data(),
getOptions: () =>
showLine ? lineISeries.options() : candlestickISeries.options(),
applyOptions: (options) =>
showLine
? lineISeries.applyOptions(options)
: candlestickISeries.applyOptions(options),
setMarkers: (m) => markerPlugin.setMarkers(m),
clearMarkers: () => markerPlugin.setMarkers([]),
onRemove: () => {
ichart.removeSeries(candlestickISeries);
ichart.removeSeries(lineISeries);
@@ -803,8 +839,9 @@ export function createChartElement({
)
);
const markerPlugin = createSeriesMarkers(iseries, [], { autoScale: false });
const series = addSeries({
inner: () => iseries,
colors: isDualColor ? [positiveColor, negativeColor] : [positiveColor],
name,
order,
@@ -814,10 +851,16 @@ export function createChartElement({
data,
defaultActive,
metric,
setup: ({ active }) => {
setup: ({ active, highlighted }) => {
iseries.setSeriesOrder(order);
signals.createEffect(active, (active) =>
iseries.applyOptions({ visible: active }),
signals.createEffect(
() => ({ active: active(), highlighted: highlighted() }),
({ active, highlighted }) => {
iseries.applyOptions({
visible: active,
color: positiveColor.highlight(highlighted),
});
},
);
},
setData: (data) => {
@@ -837,8 +880,8 @@ export function createChartElement({
},
update: (data) => iseries.update(data),
getData: () => iseries.data(),
getOptions: () => iseries.options(),
applyOptions: (options) => iseries.applyOptions(options),
setMarkers: (m) => markerPlugin.setMarkers(m),
clearMarkers: () => markerPlugin.setMarkers([]),
onRemove: () => ichart.removeSeries(iseries),
});
return series;
@@ -883,8 +926,9 @@ export function createChartElement({
)
);
const markerPlugin = createSeriesMarkers(iseries, [], { autoScale: false });
const series = addSeries({
inner: () => iseries,
colors: [color],
name,
order,
@@ -894,17 +938,23 @@ export function createChartElement({
data,
defaultActive,
metric,
setup: ({ active }) => {
setup: ({ active, highlighted }) => {
iseries.setSeriesOrder(order);
signals.createEffect(active, (active) =>
iseries.applyOptions({ visible: active }),
signals.createEffect(
() => ({ active: active(), highlighted: highlighted() }),
({ active, highlighted }) => {
iseries.applyOptions({
visible: active,
color: color.highlight(highlighted),
});
},
);
},
setData: (data) => iseries.setData(data),
update: (data) => iseries.update(data),
getData: () => iseries.data(),
getOptions: () => iseries.options(),
applyOptions: (options) => iseries.applyOptions(options),
setMarkers: (m) => markerPlugin.setMarkers(m),
clearMarkers: () => markerPlugin.setMarkers([]),
onRemove: () => ichart.removeSeries(iseries),
});
return series;
@@ -951,8 +1001,9 @@ export function createChartElement({
)
);
const markerPlugin = createSeriesMarkers(iseries, [], { autoScale: false });
const series = addSeries({
inner: () => iseries,
colors: [color],
name,
order,
@@ -962,10 +1013,16 @@ export function createChartElement({
data,
defaultActive,
metric,
setup: ({ active }) => {
setup: ({ active, highlighted }) => {
iseries.setSeriesOrder(order);
signals.createEffect(active, (active) =>
iseries.applyOptions({ visible: active }),
signals.createEffect(
() => ({ active: active(), highlighted: highlighted() }),
({ active, highlighted }) => {
iseries.applyOptions({
visible: active,
color: color.highlight(highlighted),
});
},
);
signals.createEffect(visibleBarsCountBucket, (bucket) => {
const radius = bucket === 3 ? 1 : bucket >= 1 ? 1.5 : 2;
@@ -975,8 +1032,8 @@ export function createChartElement({
setData: (data) => iseries.setData(data),
update: (data) => iseries.update(data),
getData: () => iseries.data(),
getOptions: () => iseries.options(),
applyOptions: (options) => iseries.applyOptions(options),
setMarkers: (m) => markerPlugin.setMarkers(m),
clearMarkers: () => markerPlugin.setMarkers([]),
onRemove: () => ichart.removeSeries(iseries),
});
return series;
@@ -990,6 +1047,8 @@ export function createChartElement({
* @param {AnyMetricPattern} [args.metric]
* @param {number} [args.paneIndex]
* @param {boolean} [args.defaultActive]
* @param {Color} [args.topColor]
* @param {Color} [args.bottomColor]
* @param {BaselineSeriesPartialOptions} [args.options]
*/
addBaselineSeries({
@@ -1000,6 +1059,8 @@ export function createChartElement({
paneIndex: _paneIndex,
defaultActive,
data,
topColor = colors.green,
bottomColor = colors.red,
options,
}) {
const paneIndex = _paneIndex ?? 0;
@@ -1015,8 +1076,8 @@ export function createChartElement({
price: options?.baseValue?.price ?? 0,
},
...options,
topLineColor: options?.topLineColor ?? colors.green(),
bottomLineColor: options?.bottomLineColor ?? colors.red(),
topLineColor: topColor(),
bottomLineColor: bottomColor(),
priceLineVisible: false,
bottomFillColor1: "transparent",
bottomFillColor2: "transparent",
@@ -1028,12 +1089,10 @@ export function createChartElement({
)
);
const markerPlugin = createSeriesMarkers(iseries, [], { autoScale: false });
const series = addSeries({
inner: () => iseries,
colors: [
() => options?.topLineColor ?? colors.green(),
() => options?.bottomLineColor ?? colors.red(),
],
colors: [topColor, bottomColor],
name,
order,
paneIndex,
@@ -1042,17 +1101,24 @@ export function createChartElement({
data,
defaultActive,
metric,
setup: ({ active }) => {
setup: ({ active, highlighted }) => {
iseries.setSeriesOrder(order);
signals.createEffect(active, (active) =>
iseries.applyOptions({ visible: active }),
signals.createEffect(
() => ({ active: active(), highlighted: highlighted() }),
({ active, highlighted }) => {
iseries.applyOptions({
visible: active,
topLineColor: topColor.highlight(highlighted),
bottomLineColor: bottomColor.highlight(highlighted),
});
},
);
},
setData: (data) => iseries.setData(data),
update: (data) => iseries.update(data),
getData: () => iseries.data(),
getOptions: () => iseries.options(),
applyOptions: (options) => iseries.applyOptions(options),
setMarkers: (m) => markerPlugin.setMarkers(m),
clearMarkers: () => markerPlugin.setMarkers([]),
onRemove: () => ichart.removeSeries(iseries),
});
return series;

View File

@@ -1,9 +1,6 @@
import { createLabeledInput, createSpanName } from "../utils/dom.js";
import { stringToId } from "../utils/format.js";
/** @param {string} color */
const tameColor = (color) => `${color.slice(0, -1)} / 50%)`;
/**
* @param {Signals} signals
*/
@@ -52,6 +49,11 @@ export function createLegend(signals) {
type: "checkbox",
});
// Sync checkbox with signal (for shared signals across panes)
signals.createEffect(series.active, (active) => {
input.checked = active;
});
const spanMain = window.document.createElement("span");
spanMain.classList.add("main");
label.append(spanMain);
@@ -72,6 +74,11 @@ export function createLegend(signals) {
const shouldHighlight = () => !hovered() || hovered() === series;
// Update series highlighted state
signals.createEffect(shouldHighlight, (shouldHighlight) => {
series.highlighted.set(shouldHighlight);
});
const spanColors = window.document.createElement("span");
spanColors.classList.add("colors");
spanMain.prepend(spanColors);
@@ -80,45 +87,13 @@ export function createLegend(signals) {
spanColors.append(spanColor);
signals.createEffect(
() => ({
color: color(),
shouldHighlight: shouldHighlight(),
}),
({ color, shouldHighlight }) => {
if (shouldHighlight) {
spanColor.style.backgroundColor = color;
} else {
spanColor.style.backgroundColor = tameColor(color);
}
() => color.highlight(shouldHighlight()),
(c) => {
spanColor.style.backgroundColor = c;
},
);
});
const initialColors = /** @type {Record<string, any>} */ ({});
const darkenedColors = /** @type {Record<string, any>} */ ({});
const seriesOptions = series.getOptions();
if (!seriesOptions) return;
Object.entries(seriesOptions).forEach(([k, v]) => {
if (k.toLowerCase().includes("color") && typeof v === "string") {
if (!v.startsWith("oklch")) return;
initialColors[k] = v;
darkenedColors[k] = tameColor(v);
} else if (k === "lastValueVisible" && v) {
initialColors[k] = true;
darkenedColors[k] = false;
}
});
signals.createEffect(shouldHighlight, (shouldHighlight) => {
if (shouldHighlight) {
series.applyOptions(initialColors);
} else {
series.applyOptions(darkenedColors);
}
});
const anchor = window.document.createElement("a");
signals.createEffect(series.url, (url) => {

View File

@@ -1,4 +1,3 @@
import { createSeriesMarkers } from "../modules/lightweight-charts/5.1.0/dist/lightweight-charts.standalone.production.mjs";
import { throttle } from "../utils/timing.js";
/**
@@ -9,20 +8,7 @@ import { throttle } from "../utils/timing.js";
* @param {(value: number) => string} args.formatValue
*/
export function createMinMaxMarkers({ chart, seriesList, colors, formatValue }) {
/** @type {WeakMap<ISeries, SeriesMarkersPlugin>} */
const pluginCache = new WeakMap();
/** @param {ISeries} iseries */
function getOrCreatePlugin(iseries) {
let plugin = pluginCache.get(iseries);
if (!plugin) {
plugin = createSeriesMarkers(iseries, [], { autoScale: false });
pluginCache.set(iseries, plugin);
}
return plugin;
}
/** @type {Set<ISeries>} */
/** @type {Set<AnySeries>} */
const prevMarkerSeries = new Set();
function update() {
@@ -37,7 +23,7 @@ export function createMinMaxMarkers({ chart, seriesList, colors, formatValue })
const t1 = /** @type {number} */ (tRight ?? range.to);
const color = colors.gray();
/** @type {Map<number, { minV: number, minT: Time, minS: ISeries, maxV: number, maxT: Time, maxS: ISeries }>} */
/** @type {Map<number, { minV: number, minT: Time, minS: AnySeries, maxV: number, maxT: Time, maxS: AnySeries }>} */
const byPane = new Map();
for (const series of seriesList()) {
@@ -57,16 +43,15 @@ export function createMinMaxMarkers({ chart, seriesList, colors, formatValue })
if (lo >= len) continue;
const paneIndex = series.paneIndex;
const iseries = series.inner();
let pane = byPane.get(paneIndex);
if (!pane) {
pane = {
minV: Infinity,
minT: /** @type {Time} */ (0),
minS: iseries,
minS: series,
maxV: -Infinity,
maxT: /** @type {Time} */ (0),
maxS: iseries,
maxS: series,
};
byPane.set(paneIndex, pane);
}
@@ -79,17 +64,18 @@ export function createMinMaxMarkers({ chart, seriesList, colors, formatValue })
if (v && v < pane.minV) {
pane.minV = v;
pane.minT = pt.time;
pane.minS = iseries;
pane.minS = series;
}
if (h && h > pane.maxV) {
pane.maxV = h;
pane.maxT = pt.time;
pane.maxS = iseries;
pane.maxS = series;
}
}
}
// Set new markers
/** @type {Set<AnySeries>} */
const used = new Set();
for (const { minV, minT, minS, maxV, maxT, maxS } of byPane.values()) {
if (!Number.isFinite(minV) || !Number.isFinite(maxV) || minT === maxT)
@@ -115,23 +101,23 @@ export function createMinMaxMarkers({ chart, seriesList, colors, formatValue })
used.add(minS);
used.add(maxS);
if (minS === maxS) {
getOrCreatePlugin(minS).setMarkers([minM, maxM]);
minS.setMarkers([minM, maxM]);
} else {
getOrCreatePlugin(minS).setMarkers([minM]);
getOrCreatePlugin(maxS).setMarkers([maxM]);
minS.setMarkers([minM]);
maxS.setMarkers([maxM]);
}
}
// Clear stale
for (const s of prevMarkerSeries) {
if (!used.has(s)) getOrCreatePlugin(s).setMarkers([]);
if (!used.has(s)) s.clearMarkers();
}
prevMarkerSeries.clear();
for (const s of used) prevMarkerSeries.add(s);
}
function clear() {
for (const s of prevMarkerSeries) getOrCreatePlugin(s).setMarkers([]);
for (const s of prevMarkerSeries) s.clearMarkers();
prevMarkerSeries.clear();
}

View File

@@ -1,96 +1,59 @@
import {
readParam,
readNumberParam,
writeParam,
} from "../utils/url.js";
import { readParam, writeParam } from "../utils/url.js";
import { readStored, writeToStorage } from "../utils/storage.js";
/**
* @typedef {{ from: number | null, to: number | null }} Range
*/
const INDEX_KEY = "chart-index";
const RANGES_KEY = "chart-ranges";
const RANGE_SEP = "_";
/**
* @param {Signals} signals
*/
export function createChartState(signals) {
const index = signals.createPersistedSignal({
storageKey: "chart-index",
urlKey: "index",
defaultValue: /** @type {ChartableIndexName} */ ("date"),
serialize: (v) => v,
deserialize: (s) => /** @type {ChartableIndexName} */ (s),
});
// Ranges stored per-index in localStorage only
/** @type {Record<string, Range>} */
let ranges = {};
try {
const stored = localStorage.getItem(RANGES_KEY);
const stored = readStored(RANGES_KEY);
if (stored) ranges = JSON.parse(stored);
} catch {}
const saveRanges = () => {
try {
localStorage.setItem(RANGES_KEY, JSON.stringify(ranges));
} catch {}
};
// Read index: URL > localStorage > default
/** @type {ChartableIndexName} */
const defaultIndex = "date";
const urlIndex = readParam("index");
/** @type {ChartableIndexName} */
let initialIndex = defaultIndex;
if (urlIndex) {
initialIndex = /** @type {ChartableIndexName} */ (urlIndex);
} else {
try {
const stored = localStorage.getItem(INDEX_KEY);
if (stored) initialIndex = /** @type {ChartableIndexName} */ (stored);
} catch {}
// Initialize from URL if present
const urlRange = readParam("range");
if (urlRange) {
const [from, to] = urlRange.split(RANGE_SEP).map(Number);
if (!isNaN(from) && !isNaN(to)) {
ranges[index()] = { from, to };
writeToStorage(RANGES_KEY, JSON.stringify(ranges));
}
}
// Read range: URL > localStorage (per index)
const urlFrom = readNumberParam("from");
const urlTo = readNumberParam("to");
const storedRange = ranges[initialIndex] ?? { from: null, to: null };
const initialRange = {
from: urlFrom ?? storedRange.from,
to: urlTo ?? storedRange.to,
};
// Save URL range to localStorage if present
if (urlFrom !== null || urlTo !== null) {
ranges[initialIndex] = initialRange;
saveRanges();
}
const index = signals.createSignal(/** @type {ChartableIndexName} */ (initialIndex));
const currentRange = signals.createSignal(initialRange);
// Save index changes to localStorage + URL
signals.createEffect(index, (value) => {
try {
localStorage.setItem(INDEX_KEY, value);
} catch {}
writeParam("index", value !== defaultIndex ? value : null);
});
// When index changes, switch to that index's saved range
signals.createEffect(index, (i) => {
const range = ranges[i] ?? { from: null, to: null };
currentRange.set(range);
// Update URL with new range
writeParam("from", range.from !== null ? String(range.from) : null);
writeParam("to", range.to !== null ? String(range.to) : null);
});
return {
index,
/** @type {Accessor<Range>} */
range: currentRange,
/**
* @param {Range} value
*/
/** @returns {Range} */
range: () => ranges[index()] ?? { from: null, to: null },
/** @param {Range} value */
setRange(value) {
const i = index();
ranges[i] = value;
currentRange.set(value);
saveRanges();
writeParam("from", value.from !== null ? String(value.from) : null);
writeParam("to", value.to !== null ? String(value.to) : null);
ranges[index()] = value;
writeToStorage(RANGES_KEY, JSON.stringify(ranges));
if (value.from !== null && value.to !== null) {
// Round to 2 decimals for cleaner URLs
const f = Math.floor(value.from * 100) / 100;
const t = Math.floor(value.to * 100) / 100;
writeParam("range", `${f}${RANGE_SEP}${t}`);
} else {
writeParam("range", null);
}
},
};
}