mirror of
https://github.com/bitcoinresearchkit/brk.git
synced 2026-04-25 07:09:59 -07:00
global: snapshot
This commit is contained in:
@@ -1,13 +1,14 @@
|
||||
import { ios } from "../../utils/env.js";
|
||||
import { domToBlob } from "../../modules/modern-screenshot/4.6.7/dist/index.mjs";
|
||||
import { ios, canShare } from "../utils/env.js";
|
||||
import { domToBlob } from "../modules/modern-screenshot/4.6.7/dist/index.mjs";
|
||||
|
||||
export const canCapture = !ios || canShare;
|
||||
|
||||
/**
|
||||
* @param {Object} args
|
||||
* @param {Element} args.element
|
||||
* @param {string} args.name
|
||||
* @param {string} args.title
|
||||
*/
|
||||
export async function screenshot({ element, name, title }) {
|
||||
export async function capture({ element, name }) {
|
||||
const blob = await domToBlob(element, {
|
||||
scale: 2,
|
||||
});
|
||||
@@ -16,15 +17,13 @@ export async function screenshot({ element, name, title }) {
|
||||
const file = new File(
|
||||
[blob],
|
||||
`bitview-${name}-${new Date().toJSON().split(".")[0]}.png`,
|
||||
{
|
||||
type: "image/png",
|
||||
},
|
||||
{ type: "image/png" },
|
||||
);
|
||||
|
||||
try {
|
||||
await navigator.share({
|
||||
files: [file],
|
||||
title: `${title} on ${window.document.location.hostname}`,
|
||||
title: `${name} on ${window.document.location.hostname}`,
|
||||
});
|
||||
return;
|
||||
} catch (err) {
|
||||
@@ -1,8 +1,26 @@
|
||||
import { oklchToRgba } from "./oklch.js";
|
||||
|
||||
/** @type {Map<string, string>} */
|
||||
const rgbaCache = new Map();
|
||||
|
||||
/**
|
||||
* Convert oklch to rgba with caching
|
||||
* @param {string} color - oklch color string
|
||||
*/
|
||||
function toRgba(color) {
|
||||
if (color === "transparent") return color;
|
||||
const cached = rgbaCache.get(color);
|
||||
if (cached) return cached;
|
||||
const rgba = oklchToRgba(color);
|
||||
rgbaCache.set(color, rgba);
|
||||
return rgba;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reduce color opacity to 50% for dimming effect
|
||||
* @param {string} color - oklch color string
|
||||
*/
|
||||
export function tameColor(color) {
|
||||
function tameColor(color) {
|
||||
if (color === "transparent") return color;
|
||||
return `${color.slice(0, -1)} / 50%)`;
|
||||
}
|
||||
@@ -23,9 +41,10 @@ export function tameColor(color) {
|
||||
* @returns {Color}
|
||||
*/
|
||||
function createColor(getter) {
|
||||
const color = /** @type {Color} */ (() => getter());
|
||||
color.tame = () => tameColor(getter());
|
||||
color.highlight = (highlighted) => highlighted ? getter() : tameColor(getter());
|
||||
const color = /** @type {Color} */ (() => toRgba(getter()));
|
||||
color.tame = () => toRgba(tameColor(getter()));
|
||||
color.highlight = (highlighted) =>
|
||||
highlighted ? toRgba(getter()) : toRgba(tameColor(getter()));
|
||||
return color;
|
||||
}
|
||||
|
||||
@@ -1,18 +1,16 @@
|
||||
import {
|
||||
createChart as _createChart,
|
||||
createSeriesMarkers,
|
||||
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 { createMinMaxMarkers } from "./markers.js";
|
||||
import { createLegend } from "./legend.js";
|
||||
import { capture, canCapture } from "./capture.js";
|
||||
|
||||
const createChart = /** @type {CreateChart} */ (_createChart);
|
||||
const lcCreateChart = /** @type {CreateLCChart} */ (untypedLcCreateChart);
|
||||
import { createChoiceField } from "../utils/dom.js";
|
||||
import { createOklchToRGBA } from "./oklch.js";
|
||||
import { throttle } from "../utils/timing.js";
|
||||
import { serdeBool } from "../utils/serde.js";
|
||||
import { stringToId, numberToShortUSFormat } from "../utils/format.js";
|
||||
@@ -43,8 +41,6 @@ import { resources } from "../resources.js";
|
||||
* @property {Signal<string | null>} url
|
||||
* @property {() => readonly T[]} getData
|
||||
* @property {(data: T) => void} update
|
||||
* @property {(markers: TimeSeriesMarker[]) => void} setMarkers
|
||||
* @property {VoidFunction} clearMarkers
|
||||
* @property {VoidFunction} remove
|
||||
*/
|
||||
|
||||
@@ -65,8 +61,6 @@ import { resources } from "../resources.js";
|
||||
* @property {function(number): void} removeFrom
|
||||
*/
|
||||
|
||||
const oklchToRGBA = createOklchToRGBA();
|
||||
|
||||
const lineWidth = /** @type {any} */ (1.5);
|
||||
|
||||
/**
|
||||
@@ -80,9 +74,10 @@ const lineWidth = /** @type {any} */ (1.5);
|
||||
* @param {((unknownTimeScaleCallback: VoidFunction) => void)} [args.timeScaleSetCallback]
|
||||
* @param {number | null} [args.initialVisibleBarsCount]
|
||||
* @param {true} [args.fitContent]
|
||||
* @param {HTMLElement} [args.captureElement]
|
||||
* @param {{unit: Unit; blueprints: AnySeriesBlueprint[]}[]} [args.config]
|
||||
*/
|
||||
export function createChartElement({
|
||||
export function createChart({
|
||||
parent,
|
||||
signals,
|
||||
colors,
|
||||
@@ -92,6 +87,7 @@ export function createChartElement({
|
||||
timeScaleSetCallback,
|
||||
initialVisibleBarsCount,
|
||||
fitContent,
|
||||
captureElement,
|
||||
config,
|
||||
}) {
|
||||
const div = window.document.createElement("div");
|
||||
@@ -112,7 +108,7 @@ export function createChartElement({
|
||||
const legendBottom = createLegend(signals);
|
||||
div.append(legendBottom.element);
|
||||
|
||||
const ichart = createChart(
|
||||
const ichart = lcCreateChart(
|
||||
chartDiv,
|
||||
/** @satisfies {DeepPartial<ChartOptions>} */ ({
|
||||
autoSize: true,
|
||||
@@ -120,8 +116,6 @@ export function createChartElement({
|
||||
fontFamily: style.fontFamily,
|
||||
background: { color: "transparent" },
|
||||
attributionLogo: false,
|
||||
colorSpace: "display-p3",
|
||||
colorParsers: [oklchToRGBA],
|
||||
},
|
||||
grid: {
|
||||
vertLines: { visible: false },
|
||||
@@ -133,6 +127,7 @@ export function createChartElement({
|
||||
timeScale: {
|
||||
borderVisible: false,
|
||||
enableConflation: true,
|
||||
// conflationThresholdFactor: 8,
|
||||
...(fitContent
|
||||
? {
|
||||
minBarSpacing: 0.001,
|
||||
@@ -144,7 +139,7 @@ export function createChartElement({
|
||||
locale: "en-us",
|
||||
},
|
||||
crosshair: {
|
||||
mode: 3,
|
||||
mode: 0,
|
||||
},
|
||||
...(fitContent
|
||||
? {
|
||||
@@ -170,18 +165,6 @@ export function createChartElement({
|
||||
});
|
||||
};
|
||||
|
||||
const seriesList = signals.createSignal(
|
||||
/** @type {Set<AnySeries>} */ (new Set()),
|
||||
{ equals: false },
|
||||
);
|
||||
const seriesCount = signals.createMemo(() => seriesList().size);
|
||||
const markers = createMinMaxMarkers({
|
||||
chart: ichart,
|
||||
seriesList,
|
||||
colors,
|
||||
formatValue: numberToShortUSFormat,
|
||||
});
|
||||
|
||||
const visibleBarsCount = signals.createSignal(
|
||||
initialVisibleBarsCount ?? Infinity,
|
||||
);
|
||||
@@ -193,20 +176,11 @@ export function createChartElement({
|
||||
const shouldShowLine = signals.createMemo(
|
||||
() => visibleBarsCountBucket() >= 2,
|
||||
);
|
||||
const shouldUpdateMarkers = signals.createMemo(
|
||||
() => visibleBarsCount() * seriesCount() <= 20_000,
|
||||
);
|
||||
|
||||
signals.createEffect(shouldUpdateMarkers, (should) => {
|
||||
if (should) markers.update();
|
||||
else markers.clear();
|
||||
});
|
||||
|
||||
ichart.timeScale().subscribeVisibleLogicalRangeChange(
|
||||
throttle((range) => {
|
||||
if (range) {
|
||||
visibleBarsCount.set(range.to - range.from);
|
||||
if (shouldUpdateMarkers()) markers.update();
|
||||
}
|
||||
}, 100),
|
||||
);
|
||||
@@ -273,7 +247,7 @@ export function createChartElement({
|
||||
activeResources.forEach((v) => {
|
||||
v.fetch();
|
||||
});
|
||||
}),
|
||||
}, 10_000),
|
||||
);
|
||||
|
||||
if (fitContent) {
|
||||
@@ -386,12 +360,10 @@ export function createChartElement({
|
||||
* @param {Accessor<WhitespaceData[]>} [args.data]
|
||||
* @param {number} args.paneIndex
|
||||
* @param {boolean} [args.defaultActive]
|
||||
* @param {(ctx: { active: Signal<boolean>, highlighted: Signal<boolean> }) => void} args.setup
|
||||
* @param {(ctx: { active: Signal<boolean>, highlighted: Signal<boolean>, zOrder: number }) => void} args.setup
|
||||
* @param {() => readonly any[]} args.getData
|
||||
* @param {(data: any[]) => void} args.setData
|
||||
* @param {(data: any) => void} args.update
|
||||
* @param {(markers: TimeSeriesMarker[]) => void} args.setMarkers
|
||||
* @param {VoidFunction} args.clearMarkers
|
||||
* @param {() => void} args.onRemove
|
||||
*/
|
||||
function addSeries({
|
||||
@@ -408,8 +380,6 @@ export function createChartElement({
|
||||
getData,
|
||||
setData,
|
||||
update,
|
||||
setMarkers,
|
||||
clearMarkers,
|
||||
onRemove,
|
||||
}) {
|
||||
return signals.createRoot((dispose) => {
|
||||
@@ -430,12 +400,7 @@ export function createChartElement({
|
||||
|
||||
const highlighted = signals.createSignal(true);
|
||||
|
||||
setup({ active, highlighted });
|
||||
|
||||
// Update markers when active changes
|
||||
signals.createEffect(active, () => {
|
||||
if (shouldUpdateMarkers()) markers.scheduleUpdate();
|
||||
});
|
||||
setup({ active, highlighted, zOrder: -order });
|
||||
|
||||
const hasData = signals.createSignal(false);
|
||||
let lastTime = -Infinity;
|
||||
@@ -453,22 +418,15 @@ export function createChartElement({
|
||||
url: signals.createSignal(/** @type {string | null} */ (null)),
|
||||
getData,
|
||||
update,
|
||||
setMarkers,
|
||||
clearMarkers,
|
||||
remove() {
|
||||
dispose();
|
||||
onRemove();
|
||||
if (_valuesResource) {
|
||||
activeResources.delete(_valuesResource);
|
||||
}
|
||||
seriesList().delete(series);
|
||||
seriesList.set(seriesList());
|
||||
},
|
||||
};
|
||||
|
||||
seriesList().add(series);
|
||||
seriesList.set(seriesList());
|
||||
|
||||
if (metric) {
|
||||
signals.createScopedEffect(index, (index) => {
|
||||
// Get timestamp metric from tree based on index type
|
||||
@@ -496,138 +454,149 @@ export function createChartElement({
|
||||
return `${base}${valuesResource.path}`;
|
||||
});
|
||||
|
||||
signals.createScopedEffect(active, (active) => {
|
||||
if (active) {
|
||||
timeResource.fetch();
|
||||
valuesResource.fetch();
|
||||
activeResources.add(valuesResource);
|
||||
|
||||
const timeRange = timeResource.range();
|
||||
const valuesRange = valuesResource.range();
|
||||
const valuesCacheKey = signals.createMemo(() => {
|
||||
const res = valuesRange.response();
|
||||
if (!res?.data?.length) return null;
|
||||
if (!timeRange.response()?.data?.length) return null;
|
||||
return `${res.version}|${res.stamp}|${res.total}|${res.start}|${res.end}`;
|
||||
});
|
||||
signals.createEffect(valuesCacheKey, (cacheKey) => {
|
||||
if (!cacheKey) return;
|
||||
const _indexes = timeRange.response()?.data;
|
||||
const values = valuesRange.response()?.data;
|
||||
if (!_indexes?.length || !values?.length) return;
|
||||
|
||||
const indexes = /** @type {number[]} */ (_indexes);
|
||||
const length = Math.min(indexes.length, values.length);
|
||||
|
||||
// Find start index for processing
|
||||
let startIdx = 0;
|
||||
if (hasData()) {
|
||||
// Binary search to find first index where time >= lastTime
|
||||
let lo = 0;
|
||||
let hi = length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if (indexes[mid] < lastTime) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
startIdx = lo;
|
||||
if (startIdx >= length) return; // No new data
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} i
|
||||
* @param {(number | null | [number, number, number, number])[]} vals
|
||||
* @returns {LineData | CandlestickData}
|
||||
*/
|
||||
function buildDataPoint(i, vals) {
|
||||
const time = /** @type {Time} */ (indexes[i]);
|
||||
const v = vals[i];
|
||||
if (v === null) {
|
||||
return { time, value: NaN };
|
||||
} else if (typeof v === "number") {
|
||||
return { time, value: v };
|
||||
} else {
|
||||
if (!Array.isArray(v) || v.length !== 4)
|
||||
throw new Error(`Expected OHLC tuple, got: ${v}`);
|
||||
const [open, high, low, close] = v;
|
||||
return { time, open, high, low, close };
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasData()) {
|
||||
// Initial load: build full array
|
||||
const data = /** @type {LineData[] | CandlestickData[]} */ (
|
||||
Array.from({ length })
|
||||
);
|
||||
|
||||
let prevTime = null;
|
||||
let timeOffset = 0;
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
const time = indexes[i];
|
||||
const sameTime = prevTime === time;
|
||||
if (sameTime) {
|
||||
timeOffset += 1;
|
||||
}
|
||||
const offsetedI = i - timeOffset;
|
||||
const point = buildDataPoint(i, values);
|
||||
if (sameTime && "open" in point) {
|
||||
const prev = /** @type {CandlestickData} */ (
|
||||
data[offsetedI]
|
||||
);
|
||||
point.open = prev.open;
|
||||
point.high = Math.max(prev.high, point.high);
|
||||
point.low = Math.min(prev.low, point.low);
|
||||
}
|
||||
data[offsetedI] = point;
|
||||
prevTime = time;
|
||||
}
|
||||
|
||||
data.length -= timeOffset;
|
||||
|
||||
setData(data);
|
||||
hasData.set(true);
|
||||
if (shouldUpdateMarkers()) markers.scheduleUpdate();
|
||||
lastTime =
|
||||
/** @type {number} */ (data.at(-1)?.time) ?? -Infinity;
|
||||
|
||||
if (fitContent) {
|
||||
ichart.timeScale().fitContent();
|
||||
}
|
||||
|
||||
timeScaleSetCallback?.(() => {
|
||||
if (
|
||||
index === "quarterindex" ||
|
||||
index === "semesterindex" ||
|
||||
index === "yearindex" ||
|
||||
index === "decadeindex"
|
||||
) {
|
||||
setVisibleLogicalRange({ from: -1, to: data.length });
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Incremental update: only process new data points
|
||||
for (let i = startIdx; i < length; i++) {
|
||||
const point = buildDataPoint(i, values);
|
||||
update(point);
|
||||
lastTime = /** @type {number} */ (point.time);
|
||||
}
|
||||
}
|
||||
});
|
||||
} else {
|
||||
activeResources.delete(valuesResource);
|
||||
}
|
||||
// Create memo outside active check (cheap, just checks data existence)
|
||||
const timeRange = timeResource.range();
|
||||
const valuesRange = valuesResource.range();
|
||||
const valuesCacheKey = signals.createMemo(() => {
|
||||
const res = valuesRange.response();
|
||||
if (!res?.data?.length) return null;
|
||||
if (!timeRange.response()?.data?.length) return null;
|
||||
return `${res.version}|${res.stamp}|${res.total}|${res.start}|${res.end}`;
|
||||
});
|
||||
|
||||
// Combined effect for active + data processing (flat, uses prev comparison)
|
||||
signals.createEffect(
|
||||
() => ({ isActive: active(), cacheKey: valuesCacheKey() }),
|
||||
(curr, prev) => {
|
||||
const becameActive = curr.isActive && (!prev || !prev.isActive);
|
||||
const becameInactive = !curr.isActive && prev?.isActive;
|
||||
|
||||
if (becameInactive) {
|
||||
activeResources.delete(valuesResource);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!curr.isActive) return;
|
||||
|
||||
if (becameActive) {
|
||||
timeResource.fetch();
|
||||
valuesResource.fetch();
|
||||
activeResources.add(valuesResource);
|
||||
}
|
||||
|
||||
// Process data only if cacheKey changed
|
||||
if (!curr.cacheKey || curr.cacheKey === prev?.cacheKey) return;
|
||||
|
||||
const _indexes = timeRange.response()?.data;
|
||||
const values = valuesRange.response()?.data;
|
||||
if (!_indexes?.length || !values?.length) return;
|
||||
|
||||
const indexes = /** @type {number[]} */ (_indexes);
|
||||
const length = Math.min(indexes.length, values.length);
|
||||
|
||||
// Find start index for processing
|
||||
let startIdx = 0;
|
||||
if (hasData()) {
|
||||
// Binary search to find first index where time >= lastTime
|
||||
let lo = 0;
|
||||
let hi = length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if (indexes[mid] < lastTime) {
|
||||
lo = mid + 1;
|
||||
} else {
|
||||
hi = mid;
|
||||
}
|
||||
}
|
||||
startIdx = lo;
|
||||
if (startIdx >= length) return; // No new data
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} i
|
||||
* @param {(number | null | [number, number, number, number])[]} vals
|
||||
* @returns {LineData | CandlestickData}
|
||||
*/
|
||||
function buildDataPoint(i, vals) {
|
||||
const time = /** @type {Time} */ (indexes[i]);
|
||||
const v = vals[i];
|
||||
if (v === null) {
|
||||
return { time, value: NaN };
|
||||
} else if (typeof v === "number") {
|
||||
return { time, value: v };
|
||||
} else {
|
||||
if (!Array.isArray(v) || v.length !== 4)
|
||||
throw new Error(`Expected OHLC tuple, got: ${v}`);
|
||||
const [open, high, low, close] = v;
|
||||
return { time, open, high, low, close };
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasData()) {
|
||||
// Initial load: build full array
|
||||
const data = /** @type {LineData[] | CandlestickData[]} */ (
|
||||
Array.from({ length })
|
||||
);
|
||||
|
||||
let prevTime = null;
|
||||
let timeOffset = 0;
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
const time = indexes[i];
|
||||
const sameTime = prevTime === time;
|
||||
if (sameTime) {
|
||||
timeOffset += 1;
|
||||
}
|
||||
const offsetedI = i - timeOffset;
|
||||
const point = buildDataPoint(i, values);
|
||||
if (sameTime && "open" in point) {
|
||||
const prev = /** @type {CandlestickData} */ (
|
||||
data[offsetedI]
|
||||
);
|
||||
point.open = prev.open;
|
||||
point.high = Math.max(prev.high, point.high);
|
||||
point.low = Math.min(prev.low, point.low);
|
||||
}
|
||||
data[offsetedI] = point;
|
||||
prevTime = time;
|
||||
}
|
||||
|
||||
data.length -= timeOffset;
|
||||
|
||||
setData(data);
|
||||
hasData.set(true);
|
||||
lastTime =
|
||||
/** @type {number} */ (data.at(-1)?.time) ?? -Infinity;
|
||||
|
||||
if (fitContent) {
|
||||
ichart.timeScale().fitContent();
|
||||
}
|
||||
|
||||
timeScaleSetCallback?.(() => {
|
||||
if (
|
||||
index === "quarterindex" ||
|
||||
index === "semesterindex" ||
|
||||
index === "yearindex" ||
|
||||
index === "decadeindex"
|
||||
) {
|
||||
setVisibleLogicalRange({ from: -1, to: data.length });
|
||||
}
|
||||
});
|
||||
} else {
|
||||
// Incremental update: only process new data points
|
||||
for (let i = startIdx; i < length; i++) {
|
||||
const point = buildDataPoint(i, values);
|
||||
update(point);
|
||||
lastTime = /** @type {number} */ (point.time);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
} else if (data) {
|
||||
signals.createEffect(data, (data) => {
|
||||
setData(data);
|
||||
hasData.set(true);
|
||||
if (shouldUpdateMarkers()) markers.scheduleUpdate();
|
||||
|
||||
if (fitContent) {
|
||||
ichart.timeScale().fitContent();
|
||||
}
|
||||
@@ -698,7 +667,6 @@ export function createChartElement({
|
||||
const defaultRed = inverse ? colors.green : colors.red;
|
||||
const upColor = customColors?.[0] ?? defaultGreen;
|
||||
const downColor = customColors?.[1] ?? defaultRed;
|
||||
let showLine = shouldShowLine();
|
||||
|
||||
/** @type {CandlestickISeries} */
|
||||
const candlestickISeries = /** @type {any} */ (
|
||||
@@ -710,7 +678,7 @@ export function createChartElement({
|
||||
wickUpColor: upColor(),
|
||||
wickDownColor: downColor(),
|
||||
borderVisible: false,
|
||||
visible: false,
|
||||
visible: defaultActive !== false,
|
||||
...options,
|
||||
},
|
||||
paneIndex,
|
||||
@@ -731,8 +699,7 @@ export function createChartElement({
|
||||
)
|
||||
);
|
||||
|
||||
// Marker plugin always on candlestick (has true min/max via high/low)
|
||||
const markerPlugin = createSeriesMarkers(candlestickISeries, [], { autoScale: false });
|
||||
let showLine = false;
|
||||
|
||||
const series = addSeries({
|
||||
colors: [upColor, downColor],
|
||||
@@ -744,38 +711,28 @@ export function createChartElement({
|
||||
data,
|
||||
defaultActive,
|
||||
metric,
|
||||
setup: ({ active, highlighted }) => {
|
||||
candlestickISeries.setSeriesOrder(order);
|
||||
lineISeries.setSeriesOrder(order);
|
||||
setup: ({ active, highlighted, zOrder }) => {
|
||||
candlestickISeries.setSeriesOrder(zOrder);
|
||||
lineISeries.setSeriesOrder(zOrder);
|
||||
signals.createEffect(
|
||||
() => ({
|
||||
shouldShow: shouldShowLine(),
|
||||
active: active(),
|
||||
highlighted: highlighted(),
|
||||
barsCount: visibleBarsCount(),
|
||||
}),
|
||||
({ shouldShow, active, highlighted, barsCount }) => {
|
||||
if (barsCount === Infinity) return;
|
||||
const wasLine = showLine;
|
||||
({ shouldShow, active, highlighted }) => {
|
||||
showLine = shouldShow;
|
||||
// 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,
|
||||
visible: active && !showLine,
|
||||
upColor: upColor.highlight(highlighted),
|
||||
downColor: downColor.highlight(highlighted),
|
||||
wickUpColor: upColor.highlight(highlighted),
|
||||
wickDownColor: downColor.highlight(highlighted),
|
||||
});
|
||||
lineISeries.applyOptions({
|
||||
visible: active,
|
||||
color: line,
|
||||
priceLineVisible: active && showLine,
|
||||
visible: active && showLine,
|
||||
color: colors.default.highlight(highlighted),
|
||||
});
|
||||
if (wasLine !== showLine && shouldUpdateMarkers())
|
||||
markers.scheduleUpdate();
|
||||
},
|
||||
);
|
||||
},
|
||||
@@ -789,8 +746,6 @@ export function createChartElement({
|
||||
lineISeries.update({ time: data.time, value: data.close });
|
||||
},
|
||||
getData: () => candlestickISeries.data(),
|
||||
setMarkers: (m) => markerPlugin.setMarkers(m),
|
||||
clearMarkers: () => markerPlugin.setMarkers([]),
|
||||
onRemove: () => {
|
||||
ichart.removeSeries(candlestickISeries);
|
||||
ichart.removeSeries(lineISeries);
|
||||
@@ -839,8 +794,6 @@ export function createChartElement({
|
||||
)
|
||||
);
|
||||
|
||||
const markerPlugin = createSeriesMarkers(iseries, [], { autoScale: false });
|
||||
|
||||
const series = addSeries({
|
||||
colors: isDualColor ? [positiveColor, negativeColor] : [positiveColor],
|
||||
name,
|
||||
@@ -851,8 +804,8 @@ export function createChartElement({
|
||||
data,
|
||||
defaultActive,
|
||||
metric,
|
||||
setup: ({ active, highlighted }) => {
|
||||
iseries.setSeriesOrder(order);
|
||||
setup: ({ active, highlighted, zOrder }) => {
|
||||
iseries.setSeriesOrder(zOrder);
|
||||
signals.createEffect(
|
||||
() => ({ active: active(), highlighted: highlighted() }),
|
||||
({ active, highlighted }) => {
|
||||
@@ -880,8 +833,6 @@ export function createChartElement({
|
||||
},
|
||||
update: (data) => iseries.update(data),
|
||||
getData: () => iseries.data(),
|
||||
setMarkers: (m) => markerPlugin.setMarkers(m),
|
||||
clearMarkers: () => markerPlugin.setMarkers([]),
|
||||
onRemove: () => ichart.removeSeries(iseries),
|
||||
});
|
||||
return series;
|
||||
@@ -926,8 +877,6 @@ export function createChartElement({
|
||||
)
|
||||
);
|
||||
|
||||
const markerPlugin = createSeriesMarkers(iseries, [], { autoScale: false });
|
||||
|
||||
const series = addSeries({
|
||||
colors: [color],
|
||||
name,
|
||||
@@ -938,8 +887,8 @@ export function createChartElement({
|
||||
data,
|
||||
defaultActive,
|
||||
metric,
|
||||
setup: ({ active, highlighted }) => {
|
||||
iseries.setSeriesOrder(order);
|
||||
setup: ({ active, highlighted, zOrder }) => {
|
||||
iseries.setSeriesOrder(zOrder);
|
||||
signals.createEffect(
|
||||
() => ({ active: active(), highlighted: highlighted() }),
|
||||
({ active, highlighted }) => {
|
||||
@@ -953,8 +902,6 @@ export function createChartElement({
|
||||
setData: (data) => iseries.setData(data),
|
||||
update: (data) => iseries.update(data),
|
||||
getData: () => iseries.data(),
|
||||
setMarkers: (m) => markerPlugin.setMarkers(m),
|
||||
clearMarkers: () => markerPlugin.setMarkers([]),
|
||||
onRemove: () => ichart.removeSeries(iseries),
|
||||
});
|
||||
return series;
|
||||
@@ -1001,8 +948,6 @@ export function createChartElement({
|
||||
)
|
||||
);
|
||||
|
||||
const markerPlugin = createSeriesMarkers(iseries, [], { autoScale: false });
|
||||
|
||||
const series = addSeries({
|
||||
colors: [color],
|
||||
name,
|
||||
@@ -1013,8 +958,8 @@ export function createChartElement({
|
||||
data,
|
||||
defaultActive,
|
||||
metric,
|
||||
setup: ({ active, highlighted }) => {
|
||||
iseries.setSeriesOrder(order);
|
||||
setup: ({ active, highlighted, zOrder }) => {
|
||||
iseries.setSeriesOrder(zOrder);
|
||||
signals.createEffect(
|
||||
() => ({ active: active(), highlighted: highlighted() }),
|
||||
({ active, highlighted }) => {
|
||||
@@ -1032,8 +977,6 @@ export function createChartElement({
|
||||
setData: (data) => iseries.setData(data),
|
||||
update: (data) => iseries.update(data),
|
||||
getData: () => iseries.data(),
|
||||
setMarkers: (m) => markerPlugin.setMarkers(m),
|
||||
clearMarkers: () => markerPlugin.setMarkers([]),
|
||||
onRemove: () => ichart.removeSeries(iseries),
|
||||
});
|
||||
return series;
|
||||
@@ -1089,8 +1032,6 @@ export function createChartElement({
|
||||
)
|
||||
);
|
||||
|
||||
const markerPlugin = createSeriesMarkers(iseries, [], { autoScale: false });
|
||||
|
||||
const series = addSeries({
|
||||
colors: [topColor, bottomColor],
|
||||
name,
|
||||
@@ -1101,8 +1042,8 @@ export function createChartElement({
|
||||
data,
|
||||
defaultActive,
|
||||
metric,
|
||||
setup: ({ active, highlighted }) => {
|
||||
iseries.setSeriesOrder(order);
|
||||
setup: ({ active, highlighted, zOrder }) => {
|
||||
iseries.setSeriesOrder(zOrder);
|
||||
signals.createEffect(
|
||||
() => ({ active: active(), highlighted: highlighted() }),
|
||||
({ active, highlighted }) => {
|
||||
@@ -1117,8 +1058,6 @@ export function createChartElement({
|
||||
setData: (data) => iseries.setData(data),
|
||||
update: (data) => iseries.update(data),
|
||||
getData: () => iseries.data(),
|
||||
setMarkers: (m) => markerPlugin.setMarkers(m),
|
||||
clearMarkers: () => markerPlugin.setMarkers([]),
|
||||
onRemove: () => ichart.removeSeries(iseries),
|
||||
});
|
||||
return series;
|
||||
@@ -1179,10 +1118,38 @@ export function createChartElement({
|
||||
});
|
||||
});
|
||||
|
||||
if (captureElement && canCapture) {
|
||||
const domain = window.document.createElement("p");
|
||||
domain.innerText = window.location.host;
|
||||
domain.id = "domain";
|
||||
|
||||
addFieldsetIfNeeded({
|
||||
id: "capture",
|
||||
paneIndex: 0,
|
||||
position: "ne",
|
||||
createChild() {
|
||||
const button = window.document.createElement("button");
|
||||
button.id = "capture";
|
||||
button.innerText = "capture";
|
||||
button.title = "Capture chart as image";
|
||||
button.addEventListener("click", async () => {
|
||||
captureElement.dataset.screenshot = "true";
|
||||
captureElement.append(domain);
|
||||
try {
|
||||
await capture({ element: captureElement, name: chartId });
|
||||
} catch {}
|
||||
captureElement.removeChild(domain);
|
||||
captureElement.dataset.screenshot = "false";
|
||||
});
|
||||
return button;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
return chart;
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {typeof createChartElement} CreateChartElement
|
||||
* @typedef {ReturnType<createChartElement>} Chart
|
||||
* @typedef {typeof createChart} CreateChart
|
||||
* @typedef {ReturnType<createChart>} Chart
|
||||
*/
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
import { throttle } from "../utils/timing.js";
|
||||
|
||||
/**
|
||||
* @param {Object} args
|
||||
* @param {IChartApi} args.chart
|
||||
* @param {Accessor<Set<AnySeries>>} args.seriesList
|
||||
* @param {Colors} args.colors
|
||||
* @param {(value: number) => string} args.formatValue
|
||||
*/
|
||||
export function createMinMaxMarkers({ chart, seriesList, colors, formatValue }) {
|
||||
/** @type {Set<AnySeries>} */
|
||||
const prevMarkerSeries = new Set();
|
||||
|
||||
function update() {
|
||||
const timeScale = chart.timeScale();
|
||||
const width = timeScale.width();
|
||||
const range = timeScale.getVisibleRange();
|
||||
if (!range) return;
|
||||
|
||||
const tLeft = timeScale.coordinateToTime(30);
|
||||
const tRight = timeScale.coordinateToTime(width - 30);
|
||||
const t0 = /** @type {number} */ (tLeft ?? range.from);
|
||||
const t1 = /** @type {number} */ (tRight ?? range.to);
|
||||
const color = colors.gray();
|
||||
|
||||
/** @type {Map<number, { minV: number, minT: Time, minS: AnySeries, maxV: number, maxT: Time, maxS: AnySeries }>} */
|
||||
const byPane = new Map();
|
||||
|
||||
for (const series of seriesList()) {
|
||||
if (!series.active() || !series.hasData()) continue;
|
||||
|
||||
const data = series.getData();
|
||||
const len = data.length;
|
||||
if (!len) continue;
|
||||
|
||||
// Binary search for start
|
||||
let lo = 0, hi = len;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1;
|
||||
if (/** @type {number} */ (data[mid].time) < t0) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
if (lo >= len) continue;
|
||||
|
||||
const paneIndex = series.paneIndex;
|
||||
let pane = byPane.get(paneIndex);
|
||||
if (!pane) {
|
||||
pane = {
|
||||
minV: Infinity,
|
||||
minT: /** @type {Time} */ (0),
|
||||
minS: series,
|
||||
maxV: -Infinity,
|
||||
maxT: /** @type {Time} */ (0),
|
||||
maxS: series,
|
||||
};
|
||||
byPane.set(paneIndex, pane);
|
||||
}
|
||||
|
||||
for (let i = lo; i < len; i++) {
|
||||
const pt = data[i];
|
||||
if (/** @type {number} */ (pt.time) > t1) break;
|
||||
const v = pt.low ?? pt.value;
|
||||
const h = pt.high ?? pt.value;
|
||||
if (v && v < pane.minV) {
|
||||
pane.minV = v;
|
||||
pane.minT = pt.time;
|
||||
pane.minS = series;
|
||||
}
|
||||
if (h && h > pane.maxV) {
|
||||
pane.maxV = h;
|
||||
pane.maxT = pt.time;
|
||||
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)
|
||||
continue;
|
||||
|
||||
const minM = /** @type {TimeSeriesMarker} */ ({
|
||||
time: minT,
|
||||
position: "belowBar",
|
||||
shape: "arrowUp",
|
||||
color,
|
||||
size: 0,
|
||||
text: formatValue(minV),
|
||||
});
|
||||
const maxM = /** @type {TimeSeriesMarker} */ ({
|
||||
time: maxT,
|
||||
position: "aboveBar",
|
||||
shape: "arrowDown",
|
||||
color,
|
||||
size: 0,
|
||||
text: formatValue(maxV),
|
||||
});
|
||||
|
||||
used.add(minS);
|
||||
used.add(maxS);
|
||||
if (minS === maxS) {
|
||||
minS.setMarkers([minM, maxM]);
|
||||
} else {
|
||||
minS.setMarkers([minM]);
|
||||
maxS.setMarkers([maxM]);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear stale
|
||||
for (const s of prevMarkerSeries) {
|
||||
if (!used.has(s)) s.clearMarkers();
|
||||
}
|
||||
prevMarkerSeries.clear();
|
||||
for (const s of used) prevMarkerSeries.add(s);
|
||||
}
|
||||
|
||||
function clear() {
|
||||
for (const s of prevMarkerSeries) s.clearMarkers();
|
||||
prevMarkerSeries.clear();
|
||||
}
|
||||
|
||||
return {
|
||||
update,
|
||||
scheduleUpdate: throttle(update, 100),
|
||||
clear,
|
||||
};
|
||||
}
|
||||
@@ -1,100 +1,107 @@
|
||||
export function createOklchToRGBA() {
|
||||
{
|
||||
/**
|
||||
*
|
||||
* @param {readonly [number, number, number, number, number, number, number, number, number]} A
|
||||
* @param {readonly [number, number, number]} B
|
||||
* @returns
|
||||
*/
|
||||
function multiplyMatrices(A, B) {
|
||||
return /** @type {const} */ ([
|
||||
A[0] * B[0] + A[1] * B[1] + A[2] * B[2],
|
||||
A[3] * B[0] + A[4] * B[1] + A[5] * B[2],
|
||||
A[6] * B[0] + A[7] * B[1] + A[8] * B[2],
|
||||
]);
|
||||
}
|
||||
/**
|
||||
* @param {readonly [number, number, number]} param0
|
||||
*/
|
||||
function oklch2oklab([l, c, h]) {
|
||||
return /** @type {const} */ ([
|
||||
l,
|
||||
isNaN(h) ? 0 : c * Math.cos((h * Math.PI) / 180),
|
||||
isNaN(h) ? 0 : c * Math.sin((h * Math.PI) / 180),
|
||||
]);
|
||||
}
|
||||
/**
|
||||
* @param {readonly [number, number, number]} rgb
|
||||
*/
|
||||
function srgbLinear2rgb(rgb) {
|
||||
return rgb.map((c) =>
|
||||
Math.abs(c) > 0.0031308
|
||||
? (c < 0 ? -1 : 1) * (1.055 * Math.abs(c) ** (1 / 2.4) - 0.055)
|
||||
: 12.92 * c,
|
||||
);
|
||||
}
|
||||
/**
|
||||
* @param {readonly [number, number, number]} lab
|
||||
*/
|
||||
function oklab2xyz(lab) {
|
||||
const LMSg = multiplyMatrices(
|
||||
/** @type {const} */ ([
|
||||
1, 0.3963377773761749, 0.2158037573099136, 1, -0.1055613458156586,
|
||||
-0.0638541728258133, 1, -0.0894841775298119, -1.2914855480194092,
|
||||
]),
|
||||
lab,
|
||||
);
|
||||
const LMS = /** @type {[number, number, number]} */ (
|
||||
LMSg.map((val) => val ** 3)
|
||||
);
|
||||
return multiplyMatrices(
|
||||
/** @type {const} */ ([
|
||||
1.2268798758459243, -0.5578149944602171, 0.2813910456659647,
|
||||
-0.0405757452148008, 1.112286803280317, -0.0717110580655164,
|
||||
-0.0763729366746601, -0.4214933324022432, 1.5869240198367816,
|
||||
]),
|
||||
LMS,
|
||||
);
|
||||
}
|
||||
/**
|
||||
* @param {readonly [number, number, number]} xyz
|
||||
*/
|
||||
function xyz2rgbLinear(xyz) {
|
||||
return multiplyMatrices(
|
||||
[
|
||||
3.2409699419045226, -1.537383177570094, -0.4986107602930034,
|
||||
-0.9692436362808796, 1.8759675015077202, 0.04155505740717559,
|
||||
0.05563007969699366, -0.20397695888897652, 1.0569715142428786,
|
||||
],
|
||||
xyz,
|
||||
);
|
||||
}
|
||||
|
||||
/** @param {string} oklch */
|
||||
return function (oklch) {
|
||||
oklch = oklch.replace("oklch(", "");
|
||||
oklch = oklch.replace(")", "");
|
||||
let splitOklch = oklch.split(" / ");
|
||||
let alpha = 1;
|
||||
if (splitOklch.length === 2) {
|
||||
alpha = Number(splitOklch.pop()?.replace("%", "")) / 100;
|
||||
}
|
||||
splitOklch = oklch.split(" ");
|
||||
const lch = splitOklch.map((v, i) => {
|
||||
if (!i && v.includes("%")) {
|
||||
return Number(v.replace("%", "")) / 100;
|
||||
} else {
|
||||
return Number(v);
|
||||
}
|
||||
});
|
||||
const rgb = srgbLinear2rgb(
|
||||
xyz2rgbLinear(
|
||||
oklab2xyz(oklch2oklab(/** @type {[number, number, number]} */ (lch))),
|
||||
),
|
||||
).map((v) => {
|
||||
return Math.max(Math.min(Math.round(v * 255), 255), 0);
|
||||
});
|
||||
return [...rgb, alpha];
|
||||
};
|
||||
}
|
||||
/**
|
||||
* @param {readonly [number, number, number, number, number, number, number, number, number]} A
|
||||
* @param {readonly [number, number, number]} B
|
||||
*/
|
||||
function multiplyMatrices(A, B) {
|
||||
return /** @type {const} */ ([
|
||||
A[0] * B[0] + A[1] * B[1] + A[2] * B[2],
|
||||
A[3] * B[0] + A[4] * B[1] + A[5] * B[2],
|
||||
A[6] * B[0] + A[7] * B[1] + A[8] * B[2],
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param {readonly [number, number, number]} param0 */
|
||||
function oklch2oklab([l, c, h]) {
|
||||
return /** @type {const} */ ([
|
||||
l,
|
||||
isNaN(h) ? 0 : c * Math.cos((h * Math.PI) / 180),
|
||||
isNaN(h) ? 0 : c * Math.sin((h * Math.PI) / 180),
|
||||
]);
|
||||
}
|
||||
|
||||
/** @param {readonly [number, number, number]} rgb */
|
||||
function srgbLinear2rgb(rgb) {
|
||||
return rgb.map((c) =>
|
||||
Math.abs(c) > 0.0031308
|
||||
? (c < 0 ? -1 : 1) * (1.055 * Math.abs(c) ** (1 / 2.4) - 0.055)
|
||||
: 12.92 * c,
|
||||
);
|
||||
}
|
||||
|
||||
/** @param {readonly [number, number, number]} lab */
|
||||
function oklab2xyz(lab) {
|
||||
const LMSg = multiplyMatrices(
|
||||
[1, 0.3963377773761749, 0.2158037573099136, 1, -0.1055613458156586,
|
||||
-0.0638541728258133, 1, -0.0894841775298119, -1.2914855480194092],
|
||||
lab,
|
||||
);
|
||||
const LMS = /** @type {[number, number, number]} */ (LMSg.map((val) => val ** 3));
|
||||
return multiplyMatrices(
|
||||
[1.2268798758459243, -0.5578149944602171, 0.2813910456659647,
|
||||
-0.0405757452148008, 1.112286803280317, -0.0717110580655164,
|
||||
-0.0763729366746601, -0.4214933324022432, 1.5869240198367816],
|
||||
LMS,
|
||||
);
|
||||
}
|
||||
|
||||
/** @param {readonly [number, number, number]} xyz */
|
||||
function xyz2rgbLinear(xyz) {
|
||||
return multiplyMatrices(
|
||||
[3.2409699419045226, -1.537383177570094, -0.4986107602930034,
|
||||
-0.9692436362808796, 1.8759675015077202, 0.04155505740717559,
|
||||
0.05563007969699366, -0.20397695888897652, 1.0569715142428786],
|
||||
xyz,
|
||||
);
|
||||
}
|
||||
|
||||
/** @type {Map<string, [number, number, number, number]>} */
|
||||
const conversionCache = new Map();
|
||||
|
||||
/**
|
||||
* Parse oklch string and return rgba tuple
|
||||
* @param {string} oklch
|
||||
* @returns {[number, number, number, number] | null}
|
||||
*/
|
||||
function parseOklch(oklch) {
|
||||
if (!oklch.startsWith("oklch(")) return null;
|
||||
|
||||
const cached = conversionCache.get(oklch);
|
||||
if (cached) return cached;
|
||||
|
||||
let str = oklch.slice(6, -1); // remove "oklch(" and ")"
|
||||
let alpha = 1;
|
||||
|
||||
const slashIdx = str.indexOf(" / ");
|
||||
if (slashIdx !== -1) {
|
||||
const alphaPart = str.slice(slashIdx + 3);
|
||||
alpha = alphaPart.includes("%")
|
||||
? Number(alphaPart.replace("%", "")) / 100
|
||||
: Number(alphaPart);
|
||||
str = str.slice(0, slashIdx);
|
||||
}
|
||||
|
||||
const parts = str.split(" ");
|
||||
const l = parts[0].includes("%") ? Number(parts[0].replace("%", "")) / 100 : Number(parts[0]);
|
||||
const c = Number(parts[1]);
|
||||
const h = Number(parts[2]);
|
||||
|
||||
const rgb = srgbLinear2rgb(xyz2rgbLinear(oklab2xyz(oklch2oklab([l, c, h]))))
|
||||
.map((v) => Math.max(Math.min(Math.round(v * 255), 255), 0));
|
||||
|
||||
const result = /** @type {[number, number, number, number]} */ ([...rgb, alpha]);
|
||||
conversionCache.set(oklch, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert oklch string to rgba string
|
||||
* @param {string} oklch
|
||||
* @returns {string}
|
||||
*/
|
||||
export function oklchToRgba(oklch) {
|
||||
const result = parseOklch(oklch);
|
||||
if (!result) return oklch;
|
||||
const [r, g, b, a] = result;
|
||||
return a === 1 ? `rgb(${r}, ${g}, ${b})` : `rgba(${r}, ${g}, ${b}, ${a})`;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* @import * as _ from "./modules/leeoniya-ufuzzy/1.0.19/dist/uFuzzy.d.ts"
|
||||
*
|
||||
* @import { IChartApi, ISeriesApi as _ISeriesApi, SeriesDefinition, SingleValueData as _SingleValueData, CandlestickData as _CandlestickData, BaselineData as _BaselineData, HistogramData as _HistogramData, SeriesType as LCSeriesType, IPaneApi, LineSeriesPartialOptions as _LineSeriesPartialOptions, HistogramSeriesPartialOptions as _HistogramSeriesPartialOptions, BaselineSeriesPartialOptions as _BaselineSeriesPartialOptions, CandlestickSeriesPartialOptions as _CandlestickSeriesPartialOptions, WhitespaceData, DeepPartial, ChartOptions, Time, LineData as _LineData, createChart as CreateChart, LineStyle, createSeriesMarkers as CreateSeriesMarkers, SeriesMarker, ISeriesMarkersPluginApi } from './modules/lightweight-charts/5.1.0/dist/typings.js'
|
||||
* @import { IChartApi, ISeriesApi as _ISeriesApi, SeriesDefinition, SingleValueData as _SingleValueData, CandlestickData as _CandlestickData, BaselineData as _BaselineData, HistogramData as _HistogramData, SeriesType as LCSeriesType, IPaneApi, LineSeriesPartialOptions as _LineSeriesPartialOptions, HistogramSeriesPartialOptions as _HistogramSeriesPartialOptions, BaselineSeriesPartialOptions as _BaselineSeriesPartialOptions, CandlestickSeriesPartialOptions as _CandlestickSeriesPartialOptions, WhitespaceData, DeepPartial, ChartOptions, Time, LineData as _LineData, createChart as CreateLCChart, LineStyle, createSeriesMarkers as CreateSeriesMarkers, SeriesMarker, ISeriesMarkersPluginApi } from './modules/lightweight-charts/5.1.0/dist/typings.js'
|
||||
*
|
||||
* @import { Signal, Signals, Accessor } from "./signals.js";
|
||||
*
|
||||
@@ -10,9 +10,9 @@
|
||||
*
|
||||
* @import { Resources, MetricResource } from './resources.js'
|
||||
*
|
||||
* @import { SingleValueData, CandlestickData, Series, AnySeries, ISeries, HistogramData, LineData, BaselineData, LineSeriesPartialOptions, BaselineSeriesPartialOptions, HistogramSeriesPartialOptions, CandlestickSeriesPartialOptions, CreateChartElement, Chart, Legend } from "./chart/index.js"
|
||||
* @import { SingleValueData, CandlestickData, Series, AnySeries, ISeries, HistogramData, LineData, BaselineData, LineSeriesPartialOptions, BaselineSeriesPartialOptions, HistogramSeriesPartialOptions, CandlestickSeriesPartialOptions, Chart, Legend } from "./chart/index.js"
|
||||
*
|
||||
* @import { Color, ColorName, Colors } from "./utils/colors.js"
|
||||
* @import { Color, ColorName, Colors } from "./chart/colors.js"
|
||||
*
|
||||
* @import { WebSockets } from "./utils/ws.js"
|
||||
*
|
||||
@@ -22,7 +22,7 @@
|
||||
*
|
||||
* @import { UnitObject as Unit } from "./utils/units.js"
|
||||
*
|
||||
* @import { ChartableIndexName } from "./panes/chart/index.js";
|
||||
* @import { ChartableIndexName } from "./panes/chart.js";
|
||||
*/
|
||||
|
||||
// import uFuzzy = require("./modules/leeoniya-ufuzzy/1.0.19/dist/uFuzzy.d.ts");
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { createColors } from "./utils/colors.js";
|
||||
import { createColors } from "./chart/colors.js";
|
||||
import { webSockets } from "./utils/ws.js";
|
||||
import * as formatters from "./utils/format.js";
|
||||
import { onFirstIntersection, getElementById, isHidden } from "./utils/dom.js";
|
||||
@@ -8,7 +8,7 @@ import { initOptions } from "./options/full.js";
|
||||
import ufuzzy from "./modules/leeoniya-ufuzzy/1.0.19/dist/uFuzzy.mjs";
|
||||
import * as leanQr from "./modules/lean-qr/2.7.1/index.mjs";
|
||||
import { init as initExplorer } from "./panes/_explorer.js";
|
||||
import { init as initChart } from "./panes/chart/index.js";
|
||||
import { init as initChart } from "./panes/chart.js";
|
||||
import { init as initTable } from "./panes/table.js";
|
||||
import { init as initSimulation } from "./panes/_simulation.js";
|
||||
import { next } from "./utils/timing.js";
|
||||
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
} from "../utils/format.js";
|
||||
import { serdeDate, serdeOptDate, serdeOptNumber } from "../utils/serde.js";
|
||||
import signals from "../signals.js";
|
||||
import { createChartElement } from "../chart/index.js";
|
||||
import { createChart } from "../chart/index.js";
|
||||
import { resources } from "../resources.js";
|
||||
|
||||
/**
|
||||
@@ -684,7 +684,7 @@ export function init({ colors }) {
|
||||
/** @type {() => IndexName} */
|
||||
const index = () => "dateindex";
|
||||
|
||||
createChartElement({
|
||||
createChart({
|
||||
index,
|
||||
parent: resultsElement,
|
||||
signals,
|
||||
@@ -727,7 +727,7 @@ export function init({ colors }) {
|
||||
],
|
||||
});
|
||||
|
||||
createChartElement({
|
||||
createChart({
|
||||
index,
|
||||
parent: resultsElement,
|
||||
signals,
|
||||
@@ -750,7 +750,7 @@ export function init({ colors }) {
|
||||
],
|
||||
});
|
||||
|
||||
createChartElement({
|
||||
createChart({
|
||||
index,
|
||||
parent: resultsElement,
|
||||
signals,
|
||||
@@ -779,7 +779,7 @@ export function init({ colors }) {
|
||||
],
|
||||
});
|
||||
|
||||
createChartElement({
|
||||
createChart({
|
||||
index,
|
||||
parent: resultsElement,
|
||||
signals,
|
||||
@@ -801,7 +801,7 @@ export function init({ colors }) {
|
||||
],
|
||||
});
|
||||
|
||||
createChartElement({
|
||||
createChart({
|
||||
index,
|
||||
parent: resultsElement,
|
||||
signals,
|
||||
|
||||
@@ -1,18 +1,12 @@
|
||||
import {
|
||||
createShadow,
|
||||
createChoiceField,
|
||||
createHeader,
|
||||
} from "../../utils/dom.js";
|
||||
import { chartElement } from "../../utils/elements.js";
|
||||
import { ios, canShare } from "../../utils/env.js";
|
||||
import { serdeChartableIndex } from "../../utils/serde.js";
|
||||
import { Unit } from "../../utils/units.js";
|
||||
import signals from "../../signals.js";
|
||||
import { createChartElement } from "../../chart/index.js";
|
||||
import { createChartState } from "../../chart/state.js";
|
||||
import { webSockets } from "../../utils/ws.js";
|
||||
import { screenshot } from "./screenshot.js";
|
||||
import { debounce } from "../../utils/timing.js";
|
||||
import { createShadow, createChoiceField, createHeader } from "../utils/dom.js";
|
||||
import { chartElement } from "../utils/elements.js";
|
||||
import { serdeChartableIndex } from "../utils/serde.js";
|
||||
import { Unit } from "../utils/units.js";
|
||||
import signals from "../signals.js";
|
||||
import { createChart } from "../chart/index.js";
|
||||
import { createChartState } from "../chart/state.js";
|
||||
import { webSockets } from "../utils/ws.js";
|
||||
import { debounce } from "../utils/timing.js";
|
||||
|
||||
const keyPrefix = "chart";
|
||||
const ONE_BTC_IN_SATS = 100_000_000;
|
||||
@@ -39,15 +33,15 @@ export function init({ colors, option, brk }) {
|
||||
|
||||
const { from, to } = state.range();
|
||||
|
||||
const chart = createChartElement({
|
||||
const chart = createChart({
|
||||
parent: chartElement,
|
||||
signals,
|
||||
colors,
|
||||
id: "charts",
|
||||
brk,
|
||||
index,
|
||||
initialVisibleBarsCount:
|
||||
from !== null && to !== null ? to - from : null,
|
||||
initialVisibleBarsCount: from !== null && to !== null ? to - from : null,
|
||||
captureElement: chartElement,
|
||||
timeScaleSetCallback: (unknownTimeScaleCallback) => {
|
||||
const { from, to } = state.range();
|
||||
if (from !== null && to !== null) {
|
||||
@@ -58,42 +52,11 @@ export function init({ colors, option, brk }) {
|
||||
},
|
||||
});
|
||||
|
||||
if (!(ios && !canShare)) {
|
||||
const domain = window.document.createElement("p");
|
||||
domain.innerText = `${window.location.host}`;
|
||||
domain.id = "domain";
|
||||
|
||||
chart.addFieldsetIfNeeded({
|
||||
id: "capture",
|
||||
paneIndex: 0,
|
||||
position: "ne",
|
||||
createChild() {
|
||||
const button = window.document.createElement("button");
|
||||
button.id = "capture";
|
||||
button.innerText = "capture";
|
||||
button.title = "Capture chart as image";
|
||||
button.addEventListener("click", async () => {
|
||||
chartElement.dataset.screenshot = "true";
|
||||
chartElement.append(domain);
|
||||
try {
|
||||
await screenshot({
|
||||
element: chartElement,
|
||||
name: option().path.join("-"),
|
||||
title: option().title,
|
||||
});
|
||||
} catch {}
|
||||
chartElement.removeChild(domain);
|
||||
chartElement.dataset.screenshot = "false";
|
||||
});
|
||||
return button;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Sync chart → state.range on user pan/zoom
|
||||
// Debounce to avoid rapid URL updates while panning
|
||||
const debouncedSetRange = debounce(
|
||||
(/** @type {{ from: number, to: number }} */ range) => state.setRange(range),
|
||||
(/** @type {{ from: number, to: number }} */ range) =>
|
||||
state.setRange(range),
|
||||
500,
|
||||
);
|
||||
chart.onVisibleLogicalRangeChange((t) => {
|
||||
@@ -110,7 +73,8 @@ export function init({ colors, option, brk }) {
|
||||
storageKey: `${keyPrefix}-price`,
|
||||
urlKey: "price",
|
||||
serialize: (u) => u.id,
|
||||
deserialize: (s) => /** @type {Unit} */ (unitChoices.find((u) => u.id === s) ?? Unit.usd),
|
||||
deserialize: (s) =>
|
||||
/** @type {Unit} */ (unitChoices.find((u) => u.id === s) ?? Unit.usd),
|
||||
});
|
||||
const topUnitField = createChoiceField({
|
||||
defaultValue: Unit.usd,
|
||||
@@ -222,28 +186,33 @@ export function init({ colors, option, brk }) {
|
||||
|
||||
const bottomUnits = Array.from(option.bottom.keys());
|
||||
|
||||
/** @type {{ field: HTMLDivElement, selected: Signal<Unit> } | undefined} */
|
||||
let bottomUnitSelector;
|
||||
/** @type {Signal<Unit> | undefined} */
|
||||
let bottomUnit;
|
||||
|
||||
if (bottomUnits.length) {
|
||||
const selected = signals.createPersistedSignal({
|
||||
// Storage key based on unit group (sorted unit IDs) so each group remembers its selection
|
||||
const unitGroupKey = bottomUnits
|
||||
.map((u) => u.id)
|
||||
.sort()
|
||||
.join("-");
|
||||
bottomUnit = signals.createPersistedSignal({
|
||||
defaultValue: bottomUnits[0],
|
||||
storageKey: `${keyPrefix}-unit`,
|
||||
storageKey: `${keyPrefix}-unit-${unitGroupKey}`,
|
||||
urlKey: "unit",
|
||||
serialize: (u) => u.id,
|
||||
deserialize: (s) => bottomUnits.find((u) => u.id === s) ?? bottomUnits[0],
|
||||
deserialize: (s) =>
|
||||
bottomUnits.find((u) => u.id === s) ?? bottomUnits[0],
|
||||
});
|
||||
const field = createChoiceField({
|
||||
defaultValue: bottomUnits[0],
|
||||
choices: bottomUnits,
|
||||
toKey: (u) => u.id,
|
||||
toLabel: (u) => u.name,
|
||||
selected,
|
||||
selected: bottomUnit,
|
||||
signals,
|
||||
sorted: true,
|
||||
type: "select",
|
||||
});
|
||||
bottomUnitSelector = { field, selected };
|
||||
chart.addFieldsetIfNeeded({
|
||||
id: "charts-unit-1",
|
||||
paneIndex: 1,
|
||||
@@ -259,17 +228,132 @@ export function init({ colors, option, brk }) {
|
||||
chart.legendBottom.removeFrom(0);
|
||||
}
|
||||
|
||||
signals.createScopedEffect(index, (index) => {
|
||||
signals.createScopedEffect(topUnit, (topUnit) => {
|
||||
/**
|
||||
* @param {Object} args
|
||||
* @param {Map<Unit, AnyFetchedSeriesBlueprint[]>} args.blueprints
|
||||
* @param {number} args.paneIndex
|
||||
* @param {Unit} args.unit
|
||||
* @param {IndexName} args.idx
|
||||
* @param {AnySeries[]} args.seriesList
|
||||
* @param {number} args.orderStart
|
||||
* @param {Legend} args.legend
|
||||
*/
|
||||
function createSeriesFromBlueprints({
|
||||
blueprints,
|
||||
paneIndex,
|
||||
unit,
|
||||
idx,
|
||||
seriesList,
|
||||
orderStart,
|
||||
legend,
|
||||
}) {
|
||||
legend.removeFrom(orderStart);
|
||||
seriesList.splice(orderStart).forEach((series) => series.remove());
|
||||
|
||||
blueprints.get(unit)?.forEach((blueprint, order) => {
|
||||
order += orderStart;
|
||||
const options = blueprint.options;
|
||||
const indexes = Object.keys(blueprint.metric.by);
|
||||
|
||||
if (indexes.includes(idx)) {
|
||||
switch (blueprint.type) {
|
||||
case "Baseline": {
|
||||
seriesList.push(
|
||||
chart.addBaselineSeries({
|
||||
metric: blueprint.metric,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options: {
|
||||
...options,
|
||||
topLineColor:
|
||||
blueprint.color?.() ?? blueprint.colors?.[0](),
|
||||
bottomLineColor:
|
||||
blueprint.color?.() ?? blueprint.colors?.[1](),
|
||||
},
|
||||
order,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "Histogram": {
|
||||
seriesList.push(
|
||||
chart.addHistogramSeries({
|
||||
metric: blueprint.metric,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
color: blueprint.color,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options,
|
||||
order,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "Candlestick": {
|
||||
seriesList.push(
|
||||
chart.addCandlestickSeries({
|
||||
metric: blueprint.metric,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
colors: blueprint.colors,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options,
|
||||
order,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "Dots": {
|
||||
seriesList.push(
|
||||
chart.addDotsSeries({
|
||||
metric: blueprint.metric,
|
||||
color: blueprint.color,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options,
|
||||
order,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "Line":
|
||||
case undefined:
|
||||
seriesList.push(
|
||||
chart.addLineSeries({
|
||||
metric: blueprint.metric,
|
||||
color: blueprint.color,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options,
|
||||
order,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Price series + top pane blueprints: combined effect on index + topUnit
|
||||
signals.createScopedEffect(
|
||||
() => ({ idx: index(), unit: topUnit() }),
|
||||
({ idx, unit }) => {
|
||||
// Create price series
|
||||
/** @type {AnySeries | undefined} */
|
||||
let series;
|
||||
|
||||
switch (topUnit) {
|
||||
switch (unit) {
|
||||
case Unit.usd: {
|
||||
series = chart.addCandlestickSeries({
|
||||
metric: brk.metrics.price.usd.ohlc,
|
||||
name: "Price",
|
||||
unit: topUnit,
|
||||
unit,
|
||||
order: 0,
|
||||
});
|
||||
break;
|
||||
@@ -278,19 +362,19 @@ export function init({ colors, option, brk }) {
|
||||
series = chart.addCandlestickSeries({
|
||||
metric: brk.metrics.price.sats.ohlc,
|
||||
name: "Price",
|
||||
unit: topUnit,
|
||||
unit,
|
||||
inverse: true,
|
||||
order: 0,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!series) throw Error("Unreachable");
|
||||
|
||||
seriesListTop[0]?.remove();
|
||||
seriesListTop[0] = series;
|
||||
|
||||
// Live price update effect
|
||||
signals.createEffect(
|
||||
() => ({
|
||||
latest: webSockets.kraken1dCandle.latest(),
|
||||
@@ -298,151 +382,40 @@ export function init({ colors, option, brk }) {
|
||||
}),
|
||||
({ latest, hasData }) => {
|
||||
if (!series || !latest || !hasData) return;
|
||||
printLatest({ series, unit: topUnit, index });
|
||||
printLatest({ series, unit, index: idx });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {Object} args
|
||||
* @param {Map<Unit, AnyFetchedSeriesBlueprint[]>} args.blueprints
|
||||
* @param {number} args.paneIndex
|
||||
* @param {Accessor<Unit>} args.unit
|
||||
* @param {AnySeries[]} args.seriesList
|
||||
* @param {number} args.orderStart
|
||||
* @param {Legend} args.legend
|
||||
*/
|
||||
function processPane({
|
||||
blueprints,
|
||||
paneIndex,
|
||||
unit,
|
||||
seriesList,
|
||||
orderStart,
|
||||
legend,
|
||||
}) {
|
||||
signals.createScopedEffect(unit, (unit) => {
|
||||
legend.removeFrom(orderStart);
|
||||
|
||||
seriesList.splice(orderStart).forEach((series) => {
|
||||
series.remove();
|
||||
});
|
||||
|
||||
blueprints.get(unit)?.forEach((blueprint, order) => {
|
||||
order += orderStart;
|
||||
|
||||
const options = blueprint.options;
|
||||
|
||||
// Tree-first: metric is now an accessor with .by property
|
||||
const indexes = Object.keys(blueprint.metric.by);
|
||||
|
||||
if (indexes.includes(index)) {
|
||||
switch (blueprint.type) {
|
||||
case "Baseline": {
|
||||
seriesList.push(
|
||||
chart.addBaselineSeries({
|
||||
metric: blueprint.metric,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options: {
|
||||
...options,
|
||||
topLineColor:
|
||||
blueprint.color?.() ?? blueprint.colors?.[0](),
|
||||
bottomLineColor:
|
||||
blueprint.color?.() ?? blueprint.colors?.[1](),
|
||||
},
|
||||
order,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "Histogram": {
|
||||
seriesList.push(
|
||||
chart.addHistogramSeries({
|
||||
metric: blueprint.metric,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
color: blueprint.color,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options,
|
||||
order,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "Candlestick": {
|
||||
seriesList.push(
|
||||
chart.addCandlestickSeries({
|
||||
metric: blueprint.metric,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
colors: blueprint.colors,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options,
|
||||
order,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "Dots": {
|
||||
seriesList.push(
|
||||
chart.addDotsSeries({
|
||||
metric: blueprint.metric,
|
||||
color: blueprint.color,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options,
|
||||
order,
|
||||
}),
|
||||
);
|
||||
break;
|
||||
}
|
||||
case "Line":
|
||||
case undefined:
|
||||
seriesList.push(
|
||||
chart.addLineSeries({
|
||||
metric: blueprint.metric,
|
||||
color: blueprint.color,
|
||||
name: blueprint.title,
|
||||
unit,
|
||||
defaultActive: blueprint.defaultActive,
|
||||
paneIndex,
|
||||
options,
|
||||
order,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
// Top pane blueprint series
|
||||
createSeriesFromBlueprints({
|
||||
blueprints: option.top,
|
||||
paneIndex: 0,
|
||||
unit,
|
||||
idx,
|
||||
seriesList: seriesListTop,
|
||||
orderStart: 1,
|
||||
legend: chart.legendTop,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
processPane({
|
||||
blueprints: option.top,
|
||||
paneIndex: 0,
|
||||
unit: topUnit,
|
||||
seriesList: seriesListTop,
|
||||
orderStart: 1,
|
||||
legend: chart.legendTop,
|
||||
});
|
||||
|
||||
if (bottomUnitSelector) {
|
||||
processPane({
|
||||
blueprints: option.bottom,
|
||||
paneIndex: 1,
|
||||
unit: bottomUnitSelector.selected,
|
||||
seriesList: seriesListBottom,
|
||||
orderStart: 0,
|
||||
legend: chart.legendBottom,
|
||||
});
|
||||
}
|
||||
|
||||
});
|
||||
// Bottom pane blueprints: combined effect on index + bottomUnit
|
||||
if (bottomUnit) {
|
||||
signals.createScopedEffect(
|
||||
() => ({ idx: index(), unit: bottomUnit() }),
|
||||
({ idx, unit }) => {
|
||||
createSeriesFromBlueprints({
|
||||
blueprints: option.bottom,
|
||||
paneIndex: 1,
|
||||
unit,
|
||||
idx,
|
||||
seriesList: seriesListBottom,
|
||||
orderStart: 0,
|
||||
legend: chart.legendBottom,
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ function useMetricEndpoint(endpoint) {
|
||||
* @param {number} [to]
|
||||
* @returns {RangeState<T>}
|
||||
*/
|
||||
function range(from, to) {
|
||||
function range(from = -10000, to) {
|
||||
const key = `${from}-${to ?? ""}`;
|
||||
const existing = ranges.get(key);
|
||||
if (existing) return existing;
|
||||
@@ -111,7 +111,7 @@ function useMetricEndpoint(endpoint) {
|
||||
* @param {number} [start=-10000]
|
||||
* @param {number} [end]
|
||||
*/
|
||||
async fetch(start, end) {
|
||||
async fetch(start = -10000, end) {
|
||||
const r = range(start, end);
|
||||
r.loading.set(true);
|
||||
try {
|
||||
|
||||
@@ -22,18 +22,22 @@ export function throttle(callback, wait = 1000) {
|
||||
let timeoutId = null;
|
||||
/** @type {Parameters<F>} */
|
||||
let latestArgs;
|
||||
let hasTrailing = false;
|
||||
|
||||
return (/** @type {Parameters<F>} */ ...args) => {
|
||||
latestArgs = args;
|
||||
|
||||
if (!timeoutId) {
|
||||
// Otherwise it optimizes away timeoutId in Chrome and FF
|
||||
timeoutId = timeoutId;
|
||||
timeoutId = setTimeout(() => {
|
||||
callback(...latestArgs); // Execute with latest args
|
||||
timeoutId = null;
|
||||
}, wait);
|
||||
if (timeoutId) {
|
||||
hasTrailing = true;
|
||||
return;
|
||||
}
|
||||
callback(...latestArgs);
|
||||
timeoutId = setTimeout(() => {
|
||||
timeoutId = null;
|
||||
if (hasTrailing) {
|
||||
hasTrailing = false;
|
||||
callback(...latestArgs);
|
||||
}
|
||||
}, wait);
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user