global: snapshot

This commit is contained in:
nym21
2026-01-19 16:52:17 +01:00
parent c90953adbe
commit 371ff86287
23 changed files with 1043 additions and 908 deletions
Generated
+1
View File
@@ -573,6 +573,7 @@ dependencies = [
"brk_indexer",
"brk_logger",
"brk_types",
"memmap2",
"plotters",
"tracing",
"vecdb",
+1 -2
View File
@@ -252,8 +252,7 @@ impl Vecs {
starting_indexes.dateindex = indexes
.height
.dateindex
.read_once(starting_height.decremented().unwrap())?
.into();
.read_once(starting_height.decremented().unwrap())?;
}
}
+1
View File
@@ -15,6 +15,7 @@ brk_fetcher = { workspace = true }
brk_indexer = { workspace = true }
brk_logger = { workspace = true }
brk_types = { workspace = true }
memmap2 = "0.9"
plotters = "0.3"
tracing = { workspace = true }
vecdb = { workspace = true }
+2
View File
@@ -839,9 +839,11 @@ class BrkError extends Error {
/**
* @template T
* @typedef {Object} MetricData
* @property {number} version - Data version number
* @property {number} total - Total number of data points
* @property {number} start - Start index (inclusive)
* @property {number} end - End index (exclusive)
* @property {string} stamp - Last update timestamp (ISO 8601)
* @property {T[]} data - The metric data
*/
/** @typedef {MetricData<any>} AnyMetricData */
+196 -315
View File
@@ -6,27 +6,19 @@ import {
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";
const createChart = /** @type {CreateChart} */ (_createChart);
import {
createChoiceField,
createLabeledInput,
createSpanName,
} from "../utils/dom.js";
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 } from "../utils/format.js";
import { stringToId, numberToShortUSFormat } from "../utils/format.js";
import { style } from "../utils/elements.js";
import { resources } from "../resources.js";
/**
* @typedef {Object} Valued
* @property {number} value
*
* @typedef {Object} Indexed
* @property {number} index
*
* @typedef {_ISeriesApi<LCSeriesType>} ISeries
* @typedef {_ISeriesApi<'Candlestick'>} CandlestickISeries
* @typedef {_ISeriesApi<'Histogram'>} HistogramISeries
@@ -43,6 +35,8 @@ 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>} hasData
* @property {Signal<string | null>} url
@@ -83,6 +77,7 @@ const lineWidth = /** @type {any} */ (1.5);
* @param {BrkClient} args.brk
* @param {Accessor<ChartableIndex>} args.index
* @param {((unknownTimeScaleCallback: VoidFunction) => void)} [args.timeScaleSetCallback]
* @param {number | null} [args.initialVisibleBarsCount]
* @param {true} [args.fitContent]
* @param {{unit: Unit; blueprints: AnySeriesBlueprint[]}[]} [args.config]
*/
@@ -94,6 +89,7 @@ export function createChartElement({
index,
brk,
timeScaleSetCallback,
initialVisibleBarsCount,
fitContent,
config,
}) {
@@ -131,6 +127,7 @@ export function createChartElement({
},
timeScale: {
borderVisible: false,
enableConflation: true,
...(fitContent
? {
minBarSpacing: 0.001,
@@ -160,13 +157,52 @@ export function createChartElement({
ichart.panes().at(0)?.setStretchFactor(1);
const visibleBarsCount = signals.createSignal(0);
ichart.timeScale().subscribeVisibleLogicalRangeChange((range) => {
if (range) {
visibleBarsCount.set(range.to - range.from);
}
/** @param {{ from: number, to: number }} range */
const setVisibleLogicalRange = (range) => {
// Defer to next frame to ensure chart has rendered
requestAnimationFrame(() => {
ichart.timeScale().setVisibleLogicalRange(range);
});
};
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,
);
/** @type {() => 0 | 1 | 2 | 3} 0: <=200, 1: <=500, 2: <=1000, 3: >1000 */
const visibleBarsCountBucket = signals.createMemo(() => {
const count = visibleBarsCount();
return count > 1000 ? 3 : count > 500 ? 2 : count > 200 ? 1 : 0;
});
const shouldShowLine = signals.createMemo(
() => visibleBarsCountBucket() >= 2,
);
const shouldUpdateMarkers = signals.createMemo(
() => visibleBarsCount() * seriesCount() <= 5000,
);
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),
);
signals.createEffect(
() => ({
defaultColor: colors.default(),
@@ -330,6 +366,7 @@ 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
@@ -343,6 +380,7 @@ export function createChartElement({
* @param {() => void} args.onRemove
*/
function addSeries({
inner,
metric,
name,
unit,
@@ -384,6 +422,8 @@ export function createChartElement({
active,
hasData,
id,
inner,
paneIndex,
url: signals.createSignal(/** @type {string | null} */ (null)),
getOptions,
applyOptions,
@@ -395,11 +435,16 @@ export function createChartElement({
if (_valuesResource) {
activeResources.delete(_valuesResource);
}
seriesList().delete(series);
seriesList.set(seriesList());
},
};
seriesList().add(series);
seriesList.set(seriesList());
if (metric) {
signals.createEffect(index, (index) => {
signals.createScopedEffect(index, (index) => {
// Get timestamp metric from tree based on index type
// timestampMonotonic has height only, timestamp has date-based indexes
/** @type {AnyMetricPattern} */
@@ -425,7 +470,7 @@ export function createChartElement({
return `${base}${valuesResource.path}`;
});
signals.createEffect(active, (active) => {
signals.createScopedEffect(active, (active) => {
if (active) {
timeResource.fetch();
valuesResource.fetch();
@@ -433,19 +478,61 @@ export function createChartElement({
const timeRange = timeResource.range();
const valuesRange = valuesResource.range();
signals.createEffect(
() => ({
_indexes: timeRange.response()?.data,
values: valuesRange.response()?.data,
}),
({ _indexes, values }) => {
if (!_indexes?.length || !values?.length) return;
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 indexes = /** @type {number[]} */ (_indexes);
const length = Math.min(indexes.length, values.length);
let 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
}
// TODO: Don't create new Array if data already present, update instead
/**
* @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 })
);
@@ -454,84 +541,56 @@ export function createChartElement({
let timeOffset = 0;
for (let i = 0; i < length; i++) {
const time = /** @type {Time} */ (indexes[i]);
const time = indexes[i];
const sameTime = prevTime === time;
if (sameTime) {
timeOffset += 1;
}
const v = values[i];
const offsetedI = i - timeOffset;
if (v === null) {
data[offsetedI] = {
time,
value: NaN,
};
} else if (typeof v === "number") {
data[offsetedI] = {
time,
value: v,
};
} else {
// if (sameTime) {
// console.log(data[offsetedI]);
// }
if (!Array.isArray(v) || v.length !== 4)
throw new Error(`Expected OHLC tuple, got: ${v}`);
let [open, high, low, close] = v;
data[offsetedI] = {
time,
// @ts-ignore
open: sameTime ? data[offsetedI].open : open,
high: sameTime
? // @ts-ignore
Math.max(data[offsetedI].high, high)
: high,
low: sameTime
? // @ts-ignore
Math.min(data[offsetedI].low, low)
: low,
close,
};
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;
if (!hasData()) {
setData(data);
hasData.set(true);
lastTime =
/** @type {number} */ (data.at(-1)?.time) ?? -Infinity;
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"
) {
ichart.timeScale().setVisibleLogicalRange({
from: -1,
to: data.length,
});
}
});
} else {
for (let i = 0; i < data.length; i++) {
const time = /** @type {number} */ (data[i].time);
if (time >= lastTime) {
update(data[i]);
lastTime = time;
}
}
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);
}
@@ -541,6 +600,7 @@ export function createChartElement({
signals.createEffect(data, (data) => {
setData(data);
hasData.set(true);
if (shouldUpdateMarkers()) markers.scheduleUpdate();
if (fitContent) {
ichart.timeScale().fitContent();
@@ -566,12 +626,23 @@ export function createChartElement({
}
const chart = {
inner: ichart,
legendTop,
legendBottom,
addFieldsetIfNeeded,
setVisibleLogicalRange,
/**
* @param {(range: { from: number, to: number } | null) => void} callback
* @param {number} [wait=500]
*/
onVisibleLogicalRangeChange(callback, wait = 500) {
ichart
.timeScale()
.subscribeVisibleLogicalRangeChange(throttle(callback, wait));
},
/**
* @param {Object} args
* @param {string} args.name
@@ -601,6 +672,7 @@ 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} */ (
@@ -612,7 +684,7 @@ export function createChartElement({
wickUpColor: upColor(),
wickDownColor: downColor(),
borderVisible: false,
visible: defaultActive !== false,
visible: false,
...options,
},
paneIndex,
@@ -633,9 +705,8 @@ export function createChartElement({
)
);
let showLine = false;
return addSeries({
const series = addSeries({
inner: () => (showLine ? lineISeries : candlestickISeries),
colors: [upColor, downColor],
name,
order,
@@ -649,14 +720,22 @@ export function createChartElement({
candlestickISeries.setSeriesOrder(order);
lineISeries.setSeriesOrder(order);
signals.createEffect(
() => ({ count: visibleBarsCount(), active: active() }),
({ count, active }) => {
showLine = count > 500;
() => ({
shouldShow: shouldShowLine(),
active: active(),
barsCount: visibleBarsCount(),
}),
({ shouldShow, active, barsCount }) => {
if (barsCount === Infinity) return;
const wasLine = showLine;
showLine = shouldShow;
candlestickISeries.applyOptions({ visible: active && !showLine });
lineISeries.applyOptions({
visible: active && showLine,
priceLineVisible: active && showLine,
});
if (wasLine !== showLine && shouldUpdateMarkers())
markers.scheduleUpdate();
},
);
},
@@ -681,6 +760,7 @@ export function createChartElement({
ichart.removeSeries(lineISeries);
},
});
return series;
},
/**
* @param {Object} args
@@ -723,7 +803,8 @@ export function createChartElement({
)
);
return addSeries({
const series = addSeries({
inner: () => iseries,
colors: isDualColor ? [positiveColor, negativeColor] : [positiveColor],
name,
order,
@@ -760,6 +841,7 @@ export function createChartElement({
applyOptions: (options) => iseries.applyOptions(options),
onRemove: () => ichart.removeSeries(iseries),
});
return series;
},
/**
* @param {Object} args
@@ -801,7 +883,8 @@ export function createChartElement({
)
);
return addSeries({
const series = addSeries({
inner: () => iseries,
colors: [color],
name,
order,
@@ -824,6 +907,7 @@ export function createChartElement({
applyOptions: (options) => iseries.applyOptions(options),
onRemove: () => ichart.removeSeries(iseries),
});
return series;
},
/**
* @param {Object} args
@@ -867,7 +951,8 @@ export function createChartElement({
)
);
return addSeries({
const series = addSeries({
inner: () => iseries,
colors: [color],
name,
order,
@@ -882,8 +967,8 @@ export function createChartElement({
signals.createEffect(active, (active) =>
iseries.applyOptions({ visible: active }),
);
signals.createEffect(visibleBarsCount, (count) => {
const radius = count > 1000 ? 1 : count > 200 ? 1.5 : 2;
signals.createEffect(visibleBarsCountBucket, (bucket) => {
const radius = bucket === 3 ? 1 : bucket >= 1 ? 1.5 : 2;
iseries.applyOptions({ pointMarkersRadius: radius });
});
},
@@ -894,6 +979,7 @@ export function createChartElement({
applyOptions: (options) => iseries.applyOptions(options),
onRemove: () => ichart.removeSeries(iseries),
});
return series;
},
/**
* @param {Object} args
@@ -942,7 +1028,8 @@ export function createChartElement({
)
);
return addSeries({
const series = addSeries({
inner: () => iseries,
colors: [
() => options?.topLineColor ?? colors.green(),
() => options?.bottomLineColor ?? colors.red(),
@@ -968,6 +1055,7 @@ export function createChartElement({
applyOptions: (options) => iseries.applyOptions(options),
onRemove: () => ichart.removeSeries(iseries),
});
return series;
},
};
@@ -1028,213 +1116,6 @@ export function createChartElement({
return chart;
}
/**
* @param {Signals} signals
*/
function createLegend(signals) {
const element = window.document.createElement("legend");
const hovered = signals.createSignal(/** @type {AnySeries | null} */ (null));
/** @type {HTMLElement[]} */
const legends = [];
return {
element,
/**
* @param {Object} args
* @param {AnySeries} args.series
* @param {string} args.name
* @param {number} args.order
* @param {Color[]} args.colors
*/
addOrReplace({ series, name, colors, order }) {
const div = window.document.createElement("div");
const prev = legends[order];
if (prev) {
prev.replaceWith(div);
} else {
const elementAtOrder = Array.from(element.children).at(order);
if (elementAtOrder) {
elementAtOrder.before(div);
} else {
element.append(div);
}
}
legends[order] = div;
const { input, label } = createLabeledInput({
inputId: stringToId(`legend-${series.id}`),
inputName: stringToId(`selected-${series.id}`),
inputValue: "value",
title: "Click to toggle",
inputChecked: series.active(),
onClick: () => {
series.active.set(input.checked);
},
type: "checkbox",
});
const spanMain = window.document.createElement("span");
spanMain.classList.add("main");
label.append(spanMain);
const spanName = createSpanName(name);
spanMain.append(spanName);
div.append(label);
label.addEventListener("mouseover", () => {
const h = hovered();
if (!h || h !== series) {
hovered.set(series);
}
});
label.addEventListener("mouseleave", () => {
hovered.set(null);
});
function shouldHighlight() {
const h = hovered();
return !h || h === series;
}
/**
* @param {string} color
*/
function tameColor(color) {
return `${color.slice(0, -1)} / 50%)`;
}
const spanColors = window.document.createElement("span");
spanColors.classList.add("colors");
spanMain.prepend(spanColors);
colors.forEach((color) => {
const spanColor = window.document.createElement("span");
spanColors.append(spanColor);
signals.createEffect(
() => ({
color: color(),
shouldHighlight: shouldHighlight(),
}),
({ color, shouldHighlight }) => {
if (shouldHighlight) {
spanColor.style.backgroundColor = color;
} else {
spanColor.style.backgroundColor = tameColor(color);
}
},
);
});
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) => {
if (url) {
anchor.href = url;
anchor.target = "_blank";
anchor.rel = "noopener noreferrer";
anchor.title = "Click to view data";
div.append(anchor);
}
});
},
/**
* @param {number} start
*/
removeFrom(start) {
// disposeFrom(start);
legends.splice(start).forEach((child) => child.remove());
},
};
}
/**
* @param {number} value
* @param {0 | 2} [digits]
*/
function numberToShortUSFormat(value, digits) {
const absoluteValue = Math.abs(value);
if (isNaN(value)) {
return "";
} else if (absoluteValue < 10) {
return numberToUSFormat(value, Math.min(3, digits || 10));
} else if (absoluteValue < 1_000) {
return numberToUSFormat(value, Math.min(2, digits || 10));
} else if (absoluteValue < 10_000) {
return numberToUSFormat(value, Math.min(1, digits || 10));
} else if (absoluteValue < 1_000_000) {
return numberToUSFormat(value, 0);
} else if (absoluteValue >= 1_000_000_000_000_000_000_000) {
return "Inf.";
}
const log = Math.floor(Math.log10(absoluteValue) - 6);
const suffices = ["M", "B", "T", "P", "E", "Z"];
const letterIndex = Math.floor(log / 3);
const letter = suffices[letterIndex];
const modulused = log % 3;
if (modulused === 0) {
return `${numberToUSFormat(
value / (1_000_000 * 1_000 ** letterIndex),
3,
)}${letter}`;
} else if (modulused === 1) {
return `${numberToUSFormat(
value / (1_000_000 * 1_000 ** letterIndex),
2,
)}${letter}`;
} else {
return `${numberToUSFormat(
value / (1_000_000 * 1_000 ** letterIndex),
1,
)}${letter}`;
}
}
/**
* @param {number} value
* @param {number} [digits]
* @param {Intl.NumberFormatOptions} [options]
*/
function numberToUSFormat(value, digits, options) {
return value.toLocaleString("en-us", {
...options,
minimumFractionDigits: digits,
maximumFractionDigits: digits,
});
}
/**
* @typedef {typeof createChartElement} CreateChartElement
* @typedef {ReturnType<createChartElement>} Chart
+141
View File
@@ -0,0 +1,141 @@
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
*/
export function createLegend(signals) {
const element = window.document.createElement("legend");
const hovered = signals.createSignal(/** @type {AnySeries | null} */ (null));
/** @type {HTMLElement[]} */
const legends = [];
return {
element,
/**
* @param {Object} args
* @param {AnySeries} args.series
* @param {string} args.name
* @param {number} args.order
* @param {Color[]} args.colors
*/
addOrReplace({ series, name, colors, order }) {
const div = window.document.createElement("div");
const prev = legends[order];
if (prev) {
prev.replaceWith(div);
} else {
const elementAtOrder = Array.from(element.children).at(order);
if (elementAtOrder) {
elementAtOrder.before(div);
} else {
element.append(div);
}
}
legends[order] = div;
const { input, label } = createLabeledInput({
inputId: stringToId(`legend-${series.id}`),
inputName: stringToId(`selected-${series.id}`),
inputValue: "value",
title: "Click to toggle",
inputChecked: series.active(),
onClick: () => {
series.active.set(input.checked);
},
type: "checkbox",
});
const spanMain = window.document.createElement("span");
spanMain.classList.add("main");
label.append(spanMain);
const spanName = createSpanName(name);
spanMain.append(spanName);
div.append(label);
label.addEventListener("mouseover", () => {
const h = hovered();
if (!h || h !== series) {
hovered.set(series);
}
});
label.addEventListener("mouseleave", () => {
hovered.set(null);
});
const shouldHighlight = () => !hovered() || hovered() === series;
const spanColors = window.document.createElement("span");
spanColors.classList.add("colors");
spanMain.prepend(spanColors);
colors.forEach((color) => {
const spanColor = window.document.createElement("span");
spanColors.append(spanColor);
signals.createEffect(
() => ({
color: color(),
shouldHighlight: shouldHighlight(),
}),
({ color, shouldHighlight }) => {
if (shouldHighlight) {
spanColor.style.backgroundColor = color;
} else {
spanColor.style.backgroundColor = tameColor(color);
}
},
);
});
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) => {
if (url) {
anchor.href = url;
anchor.target = "_blank";
anchor.rel = "noopener noreferrer";
anchor.title = "Click to view data";
div.append(anchor);
}
});
},
/**
* @param {number} start
*/
removeFrom(start) {
legends.splice(start).forEach((child) => child.remove());
},
};
}
+143
View File
@@ -0,0 +1,143 @@
import { createSeriesMarkers } from "../modules/lightweight-charts/5.1.0/dist/lightweight-charts.standalone.production.mjs";
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 {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>} */
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: ISeries, maxV: number, maxT: Time, maxS: ISeries }>} */
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;
const iseries = series.inner();
let pane = byPane.get(paneIndex);
if (!pane) {
pane = {
minV: Infinity,
minT: /** @type {Time} */ (0),
minS: iseries,
maxV: -Infinity,
maxT: /** @type {Time} */ (0),
maxS: iseries,
};
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 = iseries;
}
if (h && h > pane.maxV) {
pane.maxV = h;
pane.maxT = pt.time;
pane.maxS = iseries;
}
}
}
// Set new markers
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) {
getOrCreatePlugin(minS).setMarkers([minM, maxM]);
} else {
getOrCreatePlugin(minS).setMarkers([minM]);
getOrCreatePlugin(maxS).setMarkers([maxM]);
}
}
// Clear stale
for (const s of prevMarkerSeries) {
if (!used.has(s)) getOrCreatePlugin(s).setMarkers([]);
}
prevMarkerSeries.clear();
for (const s of used) prevMarkerSeries.add(s);
}
function clear() {
for (const s of prevMarkerSeries) getOrCreatePlugin(s).setMarkers([]);
prevMarkerSeries.clear();
}
return {
update,
scheduleUpdate: throttle(update, 100),
clear,
};
}
+96
View File
@@ -0,0 +1,96 @@
import {
readParam,
readNumberParam,
writeParam,
} from "../utils/url.js";
/**
* @typedef {{ from: number | null, to: number | null }} Range
*/
const INDEX_KEY = "chart-index";
const RANGES_KEY = "chart-ranges";
/**
* @param {Signals} signals
*/
export function createChartState(signals) {
/** @type {Record<string, Range>} */
let ranges = {};
try {
const stored = localStorage.getItem(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 {}
}
// 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
*/
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);
},
};
}
+6 -2
View File
@@ -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 } 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 CreateChart, LineStyle, createSeriesMarkers as CreateSeriesMarkers, SeriesMarker, ISeriesMarkersPluginApi } from './modules/lightweight-charts/5.1.0/dist/typings.js'
*
* @import { Signal, Signals, Accessor } from "./signals.js";
*
@@ -10,7 +10,7 @@
*
* @import { Resources, MetricResource } from './resources.js'
*
* @import { Valued, 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, CreateChartElement, Chart, Legend } from "./chart/index.js"
*
* @import { Color, ColorName, Colors } from "./utils/colors.js"
*
@@ -30,6 +30,10 @@
/**
* @typedef {[number, number, number, number]} OHLCTuple
*
* Lightweight Charts markers
* @typedef {ISeriesMarkersPluginApi<Time>} SeriesMarkersPlugin
* @typedef {SeriesMarker<Time>} TimeSeriesMarker
*
* Brk type aliases
* @typedef {Brk.MetricsTree_Distribution_UtxoCohorts} UtxoCohortTree
* @typedef {Brk.MetricsTree_Distribution_AddressCohorts} AddressCohortTree
+3 -2
View File
@@ -115,7 +115,8 @@ function initFrameSelectors() {
initFrameSelectors();
signals.createRoot(() => {
const brk = new BrkClient("/");
const brk = new BrkClient("https://next.bitview.space");
// const brk = new BrkClient("/");
const owner = signals.getOwner();
console.log(`VERSION = ${brk.VERSION}`);
@@ -210,7 +211,7 @@ signals.createRoot(() => {
let firstTimeLoadingSimulation = true;
let firstTimeLoadingExplorer = true;
signals.createEffect(options.selected, (option) => {
signals.createScopedEffect(options.selected, (option) => {
/** @type {HTMLElement} */
let element;
+2 -15
View File
@@ -1,6 +1,7 @@
/** Chain section builder - typed tree-based patterns */
import { Unit } from "../utils/units.js";
import { satsBtcUsd } from "./shared.js";
/**
* Create Chain section
@@ -239,21 +240,7 @@ export function createChainSection(ctx) {
name: "Volume",
title: "Transaction Volume",
bottom: [
line({
metric: transactions.volume.sentSum.sats,
name: "Sent",
unit: Unit.sats,
}),
line({
metric: transactions.volume.sentSum.bitcoin,
name: "Sent",
unit: Unit.btc,
}),
line({
metric: transactions.volume.sentSum.dollars,
name: "Sent",
unit: Unit.usd,
}),
...satsBtcUsd(ctx, transactions.volume.sentSum, "Sent"),
line({
metric: transactions.volume.annualizedVolume.sats,
name: "annualized",
+19 -121
View File
@@ -1,6 +1,7 @@
/** Shared cohort chart section builders */
import { Unit } from "../../utils/units.js";
import { satsBtcUsd } from "../shared.js";
/**
* Create supply section for a single cohort
@@ -13,24 +14,7 @@ export function createSingleSupplySeries(ctx, cohort) {
const { tree } = cohort;
return [
line({
metric: tree.supply.total.sats,
name: "Supply",
color: colors.default,
unit: Unit.sats,
}),
line({
metric: tree.supply.total.bitcoin,
name: "Supply",
color: colors.default,
unit: Unit.btc,
}),
line({
metric: tree.supply.total.dollars,
name: "Supply",
color: colors.default,
unit: Unit.usd,
}),
...satsBtcUsd(ctx, tree.supply.total, "Supply", colors.default),
...("supplyRelToCirculatingSupply" in tree.relative
? [
line({
@@ -41,63 +25,12 @@ export function createSingleSupplySeries(ctx, cohort) {
}),
]
: []),
line({
metric: tree.unrealized.supplyInProfit.sats,
name: "In Profit",
color: colors.green,
unit: Unit.sats,
}),
line({
metric: tree.unrealized.supplyInProfit.bitcoin,
name: "In Profit",
color: colors.green,
unit: Unit.btc,
}),
line({
metric: tree.unrealized.supplyInProfit.dollars,
name: "In Profit",
color: colors.green,
unit: Unit.usd,
}),
line({
metric: tree.unrealized.supplyInLoss.sats,
name: "In Loss",
color: colors.red,
unit: Unit.sats,
}),
line({
metric: tree.unrealized.supplyInLoss.bitcoin,
name: "In Loss",
color: colors.red,
unit: Unit.btc,
}),
line({
metric: tree.unrealized.supplyInLoss.dollars,
name: "In Loss",
color: colors.red,
unit: Unit.usd,
}),
line({
metric: tree.supply.halved.sats,
name: "half",
color: colors.gray,
unit: Unit.sats,
...satsBtcUsd(ctx, tree.unrealized.supplyInProfit, "In Profit", colors.green),
...satsBtcUsd(ctx, tree.unrealized.supplyInLoss, "In Loss", colors.red),
...satsBtcUsd(ctx, tree.supply.halved, "half", colors.gray).map((s) => ({
...s,
options: { lineStyle: 4 },
}),
line({
metric: tree.supply.halved.bitcoin,
name: "half",
color: colors.gray,
unit: Unit.btc,
options: { lineStyle: 4 },
}),
line({
metric: tree.supply.halved.dollars,
name: "half",
color: colors.gray,
unit: Unit.usd,
options: { lineStyle: 4 },
}),
})),
...("supplyInProfitRelToCirculatingSupply" in tree.relative
? [
line({
@@ -147,17 +80,16 @@ export function createGroupedSupplyTotalSeries(ctx, list) {
const constant100 = brk.metrics.constants.constant100;
return list.flatMap(({ color, name, tree }) => [
line({ metric: tree.supply.total.sats, name, color, unit: Unit.sats }),
line({ metric: tree.supply.total.bitcoin, name, color, unit: Unit.btc }),
line({ metric: tree.supply.total.dollars, name, color, unit: Unit.usd }),
"supplyRelToCirculatingSupply" in tree.relative
? line({
metric: tree.relative.supplyRelToCirculatingSupply,
name,
color,
unit: Unit.pctSupply,
})
: line({ metric: constant100, name, color, unit: Unit.pctSupply }),
...satsBtcUsd(ctx, tree.supply.total, name, color),
line({
metric:
"supplyRelToCirculatingSupply" in tree.relative
? tree.relative.supplyRelToCirculatingSupply
: constant100,
name,
color,
unit: Unit.pctSupply,
}),
]);
}
@@ -171,24 +103,7 @@ export function createGroupedSupplyInProfitSeries(ctx, list) {
const { line } = ctx;
return list.flatMap(({ color, name, tree }) => [
line({
metric: tree.unrealized.supplyInProfit.sats,
name,
color,
unit: Unit.sats,
}),
line({
metric: tree.unrealized.supplyInProfit.bitcoin,
name,
color,
unit: Unit.btc,
}),
line({
metric: tree.unrealized.supplyInProfit.dollars,
name,
color,
unit: Unit.usd,
}),
...satsBtcUsd(ctx, tree.unrealized.supplyInProfit, name, color),
...("supplyInProfitRelToCirculatingSupply" in tree.relative
? [
line({
@@ -212,24 +127,7 @@ export function createGroupedSupplyInLossSeries(ctx, list) {
const { line } = ctx;
return list.flatMap(({ color, name, tree }) => [
line({
metric: tree.unrealized.supplyInLoss.sats,
name,
color,
unit: Unit.sats,
}),
line({
metric: tree.unrealized.supplyInLoss.bitcoin,
name,
color,
unit: Unit.btc,
}),
line({
metric: tree.unrealized.supplyInLoss.dollars,
name,
color,
unit: Unit.usd,
}),
...satsBtcUsd(ctx, tree.unrealized.supplyInLoss, name, color),
...("supplyInLossRelToCirculatingSupply" in tree.relative
? [
line({
+20 -92
View File
@@ -1,6 +1,14 @@
/** Cointime section builder - typed tree-based patterns */
import { Unit } from "../utils/units.js";
import {
satsBtcUsd,
priceLines,
percentileUsdMap,
percentileMap,
sdPatterns,
sdBands,
} from "./shared.js";
/**
* Create price with ratio options for cointime prices
@@ -19,50 +27,9 @@ function createCointimePriceWithRatioOptions(
) {
const { line, colors, createPriceLine } = ctx;
// Percentile USD mappings
const percentileUsdMap = [
{ name: "pct99", prop: ratio.ratioPct99Usd, color: colors.rose },
{ name: "pct98", prop: ratio.ratioPct98Usd, color: colors.pink },
{ name: "pct95", prop: ratio.ratioPct95Usd, color: colors.fuchsia },
{ name: "pct5", prop: ratio.ratioPct5Usd, color: colors.cyan },
{ name: "pct2", prop: ratio.ratioPct2Usd, color: colors.sky },
{ name: "pct1", prop: ratio.ratioPct1Usd, color: colors.blue },
];
// Percentile ratio mappings
const percentileMap = [
{ name: "pct99", prop: ratio.ratioPct99, color: colors.rose },
{ name: "pct98", prop: ratio.ratioPct98, color: colors.pink },
{ name: "pct95", prop: ratio.ratioPct95, color: colors.fuchsia },
{ name: "pct5", prop: ratio.ratioPct5, color: colors.cyan },
{ name: "pct2", prop: ratio.ratioPct2, color: colors.sky },
{ name: "pct1", prop: ratio.ratioPct1, color: colors.blue },
];
// SD patterns by window
const sdPatterns = [
{ nameAddon: "all", titleAddon: "", sd: ratio.ratioSd },
{ nameAddon: "4y", titleAddon: "4y", sd: ratio.ratio4ySd },
{ nameAddon: "2y", titleAddon: "2y", sd: ratio.ratio2ySd },
{ nameAddon: "1y", titleAddon: "1y", sd: ratio.ratio1ySd },
];
/** @param {Ratio1ySdPattern} sd */
const getSdBands = (sd) => [
{ name: "0σ", prop: sd._0sdUsd, color: colors.lime },
{ name: "+0.5σ", prop: sd.p05sdUsd, color: colors.yellow },
{ name: "+1σ", prop: sd.p1sdUsd, color: colors.amber },
{ name: "+1.5σ", prop: sd.p15sdUsd, color: colors.orange },
{ name: "+2σ", prop: sd.p2sdUsd, color: colors.red },
{ name: "+2.5σ", prop: sd.p25sdUsd, color: colors.rose },
{ name: "+3σ", prop: sd.p3sd, color: colors.pink },
{ name: "0.5σ", prop: sd.m05sdUsd, color: colors.teal },
{ name: "1σ", prop: sd.m1sdUsd, color: colors.cyan },
{ name: "1.5σ", prop: sd.m15sdUsd, color: colors.sky },
{ name: "2σ", prop: sd.m2sdUsd, color: colors.blue },
{ name: "2.5σ", prop: sd.m25sdUsd, color: colors.indigo },
{ name: "3σ", prop: sd.m3sd, color: colors.violet },
];
const pctUsdMap = percentileUsdMap(colors, ratio);
const pctMap = percentileMap(colors, ratio);
const sdPats = sdPatterns(ratio);
return [
{
@@ -75,7 +42,7 @@ function createCointimePriceWithRatioOptions(
title: `${title} Ratio`,
top: [
line({ metric: price, name: legend, color, unit: Unit.usd }),
...percentileUsdMap.map(({ name: pctName, prop, color: pctColor }) =>
...pctUsdMap.map(({ name: pctName, prop, color: pctColor }) =>
line({
metric: prop,
name: pctName,
@@ -124,7 +91,7 @@ function createCointimePriceWithRatioOptions(
color: colors.rose,
unit: Unit.ratio,
}),
...percentileMap.map(({ name: pctName, prop, color: pctColor }) =>
...pctMap.map(({ name: pctName, prop, color: pctColor }) =>
line({
metric: prop,
name: pctName,
@@ -200,22 +167,14 @@ function createCointimePriceWithRatioOptions(
color: colors.yellow,
unit: Unit.sd,
}),
createPriceLine({ unit: Unit.sd, number: 4 }),
createPriceLine({ unit: Unit.sd, number: 3 }),
createPriceLine({ unit: Unit.sd, number: 2 }),
createPriceLine({ unit: Unit.sd, number: 1 }),
createPriceLine({ unit: Unit.sd, number: 0 }),
createPriceLine({ unit: Unit.sd, number: -1 }),
createPriceLine({ unit: Unit.sd, number: -2 }),
createPriceLine({ unit: Unit.sd, number: -3 }),
createPriceLine({ unit: Unit.sd, number: -4 }),
...priceLines(ctx, Unit.sd, [0, 1, -1, 2, -2, 3, -3, 4, -4]),
],
},
// Individual Z-Score charts
...sdPatterns.map(({ nameAddon, titleAddon, sd }) => ({
...sdPats.map(({ nameAddon, titleAddon, sd }) => ({
name: nameAddon,
title: `${title} ${titleAddon} Z-Score`,
top: getSdBands(sd).map(({ name: bandName, prop, color: bandColor }) =>
top: sdBands(colors, sd).map(({ name: bandName, prop, color: bandColor }) =>
line({
metric: prop,
name: bandName,
@@ -225,13 +184,7 @@ function createCointimePriceWithRatioOptions(
),
bottom: [
line({ metric: sd.zscore, name: "Z-Score", color, unit: Unit.sd }),
createPriceLine({ unit: Unit.sd, number: 3 }),
createPriceLine({ unit: Unit.sd, number: 2 }),
createPriceLine({ unit: Unit.sd, number: 1 }),
createPriceLine({ unit: Unit.sd, number: 0 }),
createPriceLine({ unit: Unit.sd, number: -1 }),
createPriceLine({ unit: Unit.sd, number: -2 }),
createPriceLine({ unit: Unit.sd, number: -3 }),
...priceLines(ctx, Unit.sd, [0, 1, -1, 2, -2, 3, -3]),
],
})),
],
@@ -395,34 +348,9 @@ export function createCointimeSection(ctx) {
name: "Supply",
title: "Cointime Supply",
bottom: [
// All supply (different pattern structure)
line({
metric: all.supply.total.sats,
name: "All",
color: colors.orange,
unit: Unit.sats,
}),
line({
metric: all.supply.total.bitcoin,
name: "All",
color: colors.orange,
unit: Unit.btc,
}),
line({
metric: all.supply.total.dollars,
name: "All",
color: colors.orange,
unit: Unit.usd,
}),
// Cointime supplies (ActiveSupplyPattern)
.../** @type {const} */ ([
[cointimeSupply.vaultedSupply, "Vaulted", colors.lime],
[cointimeSupply.activeSupply, "Active", colors.rose],
]).flatMap(([supplyItem, name, color]) => [
line({ metric: supplyItem.sats, name, color, unit: Unit.sats }),
line({ metric: supplyItem.bitcoin, name, color, unit: Unit.btc }),
line({ metric: supplyItem.dollars, name, color, unit: Unit.usd }),
]),
...satsBtcUsd(ctx, all.supply.total, "All", colors.orange),
...satsBtcUsd(ctx, cointimeSupply.vaultedSupply, "Vaulted", colors.lime),
...satsBtcUsd(ctx, cointimeSupply.activeSupply, "Active", colors.rose),
],
},
+140 -142
View File
@@ -2,7 +2,6 @@ import { createPartialOptions } from "./partial.js";
import {
createButtonElement,
createAnchorElement,
insertElementAtIndex,
} from "../utils/dom.js";
import { pushHistory, resetParams } from "../utils/url.js";
import { readStored, writeToStorage } from "../utils/storage.js";
@@ -43,6 +42,21 @@ export function initOptions({ colors, signals, brk, qrcode }) {
const parent = signals.createSignal(/** @type {HTMLElement | null} */ (null));
/** @type {Map<string, HTMLLIElement>} */
const liByPath = new Map();
/**
* @param {string[]} nodePath
*/
function isOnSelectedPath(nodePath) {
const selectedPath = selected()?.path;
return (
selectedPath &&
nodePath.length <= selectedPath.length &&
nodePath.every((v, i) => v === selectedPath[i])
);
}
/**
* @param {AnyFetchedSeriesBlueprint[]} [arr]
*/
@@ -120,137 +134,55 @@ export function initOptions({ colors, signals, brk, qrcode }) {
/** @type {Option | undefined} */
let savedOption;
// ============================================
// Phase 1: Process partial tree (non-reactive)
// Transforms options, computes counts, populates list
// ============================================
/**
* @typedef {{ type: "group"; name: string; serName: string; path: string[]; count: number; children: ProcessedNode[] }} ProcessedGroup
* @typedef {{ type: "option"; option: Option; path: string[] }} ProcessedOption
* @typedef {ProcessedGroup | ProcessedOption} ProcessedNode
*/
/**
* @param {PartialOptionsTree} partialTree
* @param {Accessor<HTMLElement | null>} parent
* @param {string[] | undefined} parentPath
* @returns {Accessor<number>}
* @param {string[]} parentPath
* @returns {ProcessedNode[]}
*/
function recursiveProcessPartialTree(
partialTree,
parent,
parentPath = [],
depth = 0,
) {
/** @type {Accessor<number>[]} */
const listForSum = [];
const ul = signals.createMemo(
// @ts_ignore
(_previous) => {
const previous = /** @type {HTMLUListElement | null} */ (_previous);
previous?.remove();
const _parent = parent();
if (_parent) {
if ("open" in _parent && !_parent.open) {
throw "Set accesor to null instead";
}
const ul = window.document.createElement("ul");
_parent.append(ul);
return ul;
} else {
return null;
}
},
null,
);
partialTree.forEach((anyPartial, partialIndex) => {
const renderLi = signals.createSignal(true);
const li = signals.createMemo((_previous) => {
const previous = _previous;
previous?.remove();
const _ul = ul();
if (renderLi() && _ul) {
const li = window.document.createElement("li");
insertElementAtIndex(_ul, li, partialIndex);
return li;
} else {
return null;
}
}, /** @type {HTMLLIElement | null} */ (null));
function processPartialTree(partialTree, parentPath = []) {
/** @type {ProcessedNode[]} */
const nodes = [];
for (const anyPartial of partialTree) {
if ("tree" in anyPartial) {
/** @type {Omit<OptionsGroup, keyof PartialOptionsGroup>} */
const groupAddons = {};
Object.assign(anyPartial, groupAddons);
const passedDetails = signals.createSignal(
/** @type {HTMLDivElement | HTMLDetailsElement | null} */ (null),
);
const serName = stringToId(anyPartial.name);
const path = [...parentPath, serName];
const childOptionsCount = recursiveProcessPartialTree(
anyPartial.tree,
passedDetails,
path,
depth + 1,
const children = processPartialTree(anyPartial.tree, path);
// Compute count from children
const count = children.reduce(
(sum, child) => sum + (child.type === "group" ? child.count : 1),
0,
);
listForSum.push(childOptionsCount);
// Skip groups with no children
if (count === 0) continue;
signals.createEffect(li, (li) => {
if (!li) {
passedDetails.set(null);
return;
}
signals.createEffect(selected, (selected) => {
if (
path.length <= selected.path.length &&
path.every((v, i) => selected.path.at(i) === v)
) {
li.dataset.highlight = "";
} else {
delete li.dataset.highlight;
}
});
const details = window.document.createElement("details");
details.dataset.name = serName;
li.appendChild(details);
const summary = window.document.createElement("summary");
details.append(summary);
summary.append(anyPartial.name);
const supCount = window.document.createElement("sup");
summary.append(supCount);
signals.createEffect(childOptionsCount, (childOptionsCount) => {
supCount.innerHTML = childOptionsCount.toLocaleString("en-us");
});
details.addEventListener("toggle", () => {
const open = details.open;
if (open) {
passedDetails.set(details);
} else {
passedDetails.set(null);
}
});
nodes.push({
type: "group",
name: anyPartial.name,
serName,
path,
count,
children,
});
function createRenderLiEffect() {
signals.createEffect(childOptionsCount, (count) => {
renderLi.set(!!count);
});
}
createRenderLiEffect();
} else {
const option = /** @type {Option} */ (anyPartial);
const name = option.name;
const path = [...parentPath, stringToId(option.name)];
// Transform partial to full option
if ("kind" in anyPartial && anyPartial.kind === "explorer") {
Object.assign(
option,
@@ -310,6 +242,7 @@ export function initOptions({ colors, signals, brk, qrcode }) {
list.push(option);
// Check if this matches URL or saved path
if (urlPath) {
const sameAsURLPath =
urlPath.length === path.length &&
@@ -326,38 +259,103 @@ export function initOptions({ colors, signals, brk, qrcode }) {
}
}
signals.createEffect(li, (li) => {
if (!li) {
return;
}
signals.createEffect(selected, (selected) => {
if (selected === option) {
li.dataset.highlight = "";
} else {
delete li.dataset.highlight;
}
});
const element = createOptionElement({
option,
qrcode,
});
li.append(element);
nodes.push({
type: "option",
option,
path,
});
listForSum.push(() => 1);
}
});
}
return signals.createMemo(() =>
listForSum.reduce((acc, s) => acc + s(), 0),
);
return nodes;
}
recursiveProcessPartialTree(partialOptions, parent);
const processedTree = processPartialTree(partialOptions);
logUnused();
// ============================================
// Phase 2: Build DOM lazily (imperative)
// Uses native toggle events for lazy loading
// ============================================
/**
* @param {ProcessedNode[]} nodes
* @param {HTMLElement} parentEl
*/
function buildTreeDOM(nodes, parentEl) {
const ul = window.document.createElement("ul");
parentEl.append(ul);
for (const node of nodes) {
const li = window.document.createElement("li");
ul.append(li);
const pathKey = node.path.join("/");
liByPath.set(pathKey, li);
if (isOnSelectedPath(node.path)) {
li.dataset.highlight = "";
}
if (node.type === "group") {
const details = window.document.createElement("details");
details.dataset.name = node.serName;
li.appendChild(details);
const summary = window.document.createElement("summary");
details.append(summary);
summary.append(node.name);
const supCount = window.document.createElement("sup");
supCount.innerHTML = node.count.toLocaleString("en-us");
summary.append(supCount);
let built = false;
details.addEventListener("toggle", () => {
if (details.open && !built) {
built = true;
buildTreeDOM(node.children, details);
}
});
} else {
const element = createOptionElement({
option: node.option,
qrcode,
});
li.append(element);
}
}
}
// Single effect to kick off DOM building when parent is set
signals.createEffect(
() => parent(),
(_parent) => {
if (!_parent) return;
buildTreeDOM(processedTree, _parent);
},
);
// Single effect for highlighting on selection change
signals.createEffect(
() => selected(),
(selected) => {
if (!selected) return;
// Clear all existing highlights
liByPath.forEach((li) => {
delete li.dataset.highlight;
});
// Highlight selected option and parent groups
for (let i = 1; i <= selected.path.length; i++) {
const pathKey = selected.path.slice(0, i).join("/");
const li = liByPath.get(pathKey);
if (li) li.dataset.highlight = "";
}
},
);
if (!selected()) {
const option =
savedOption || list.find((option) => option.kind === "chart");
+15 -52
View File
@@ -1,6 +1,13 @@
/** Moving averages section */
import { Unit } from "../../utils/units.js";
import {
priceLines,
percentileUsdMap,
percentileMap,
sdPatterns,
sdBands,
} from "../shared.js";
import { periodIdToName } from "./utils.js";
/**
@@ -51,47 +58,9 @@ export function createPriceWithRatioOptions(
const { line, colors, createPriceLine } = ctx;
const priceMetric = ratio.price;
const percentileUsdMap = [
{ name: "pct99", prop: ratio.ratioPct99Usd, color: colors.rose },
{ name: "pct98", prop: ratio.ratioPct98Usd, color: colors.pink },
{ name: "pct95", prop: ratio.ratioPct95Usd, color: colors.fuchsia },
{ name: "pct5", prop: ratio.ratioPct5Usd, color: colors.cyan },
{ name: "pct2", prop: ratio.ratioPct2Usd, color: colors.sky },
{ name: "pct1", prop: ratio.ratioPct1Usd, color: colors.blue },
];
const percentileMap = [
{ name: "pct99", prop: ratio.ratioPct99, color: colors.rose },
{ name: "pct98", prop: ratio.ratioPct98, color: colors.pink },
{ name: "pct95", prop: ratio.ratioPct95, color: colors.fuchsia },
{ name: "pct5", prop: ratio.ratioPct5, color: colors.cyan },
{ name: "pct2", prop: ratio.ratioPct2, color: colors.sky },
{ name: "pct1", prop: ratio.ratioPct1, color: colors.blue },
];
const sdPatterns = [
{ nameAddon: "all", titleAddon: "", sd: ratio.ratioSd },
{ nameAddon: "4y", titleAddon: "4y", sd: ratio.ratio4ySd },
{ nameAddon: "2y", titleAddon: "2y", sd: ratio.ratio2ySd },
{ nameAddon: "1y", titleAddon: "1y", sd: ratio.ratio1ySd },
];
/** @param {Ratio1ySdPattern} sd */
const getSdBands = (sd) => [
{ name: "0σ", prop: sd._0sdUsd, color: colors.lime },
{ name: "+0.5σ", prop: sd.p05sdUsd, color: colors.yellow },
{ name: "+1σ", prop: sd.p1sdUsd, color: colors.amber },
{ name: "+1.5σ", prop: sd.p15sdUsd, color: colors.orange },
{ name: "+2σ", prop: sd.p2sdUsd, color: colors.red },
{ name: "+2.5σ", prop: sd.p25sdUsd, color: colors.rose },
{ name: "+3σ", prop: sd.p3sd, color: colors.pink },
{ name: "0.5σ", prop: sd.m05sdUsd, color: colors.teal },
{ name: "1σ", prop: sd.m1sdUsd, color: colors.cyan },
{ name: "1.5σ", prop: sd.m15sdUsd, color: colors.sky },
{ name: "2σ", prop: sd.m2sdUsd, color: colors.blue },
{ name: "2.5σ", prop: sd.m25sdUsd, color: colors.indigo },
{ name: "3σ", prop: sd.m3sd, color: colors.violet },
];
const pctUsdMap = percentileUsdMap(colors, ratio);
const pctMap = percentileMap(colors, ratio);
const sdPats = sdPatterns(ratio);
return [
{
@@ -104,7 +73,7 @@ export function createPriceWithRatioOptions(
title: `${title} Ratio`,
top: [
line({ metric: priceMetric, name: legend, color, unit: Unit.usd }),
...percentileUsdMap.map(({ name: pctName, prop, color: pctColor }) =>
...pctUsdMap.map(({ name: pctName, prop, color: pctColor }) =>
line({
metric: prop,
name: pctName,
@@ -153,7 +122,7 @@ export function createPriceWithRatioOptions(
color: colors.rose,
unit: Unit.ratio,
}),
...percentileMap.map(({ name: pctName, prop, color: pctColor }) =>
...pctMap.map(({ name: pctName, prop, color: pctColor }) =>
line({
metric: prop,
name: pctName,
@@ -168,10 +137,10 @@ export function createPriceWithRatioOptions(
},
{
name: "ZScores",
tree: sdPatterns.map(({ nameAddon, titleAddon, sd }) => ({
tree: sdPats.map(({ nameAddon, titleAddon, sd }) => ({
name: nameAddon,
title: `${title} ${titleAddon} Z-Score`,
top: getSdBands(sd).map(({ name: bandName, prop, color: bandColor }) =>
top: sdBands(colors, sd).map(({ name: bandName, prop, color: bandColor }) =>
line({
metric: prop,
name: bandName,
@@ -181,13 +150,7 @@ export function createPriceWithRatioOptions(
),
bottom: [
line({ metric: sd.zscore, name: "Z-Score", color, unit: Unit.sd }),
createPriceLine({ unit: Unit.sd, number: 3 }),
createPriceLine({ unit: Unit.sd, number: 2 }),
createPriceLine({ unit: Unit.sd, number: 1 }),
createPriceLine({ unit: Unit.sd, number: 0 }),
createPriceLine({ unit: Unit.sd, number: -1 }),
createPriceLine({ unit: Unit.sd, number: -2 }),
createPriceLine({ unit: Unit.sd, number: -3 }),
...priceLines(ctx, Unit.sd, [0, 1, -1, 2, -2, 3, -3]),
],
})),
},
+6 -79
View File
@@ -1,6 +1,7 @@
/** Investing section (DCA) */
import { Unit } from "../../utils/units.js";
import { satsBtcUsd } from "../shared.js";
import { periodIdToName } from "./utils.js";
/**
@@ -113,42 +114,8 @@ export function createInvestingSection(ctx, { dca, lookback, returns }) {
name: "Stack",
title: `${name} DCA vs Lump Sum Stack ($100/day)`,
bottom: [
line({
metric: dcaStack.sats,
name: "DCA",
color: colors.green,
unit: Unit.sats,
}),
line({
metric: dcaStack.bitcoin,
name: "DCA",
color: colors.green,
unit: Unit.btc,
}),
line({
metric: dcaStack.dollars,
name: "DCA",
color: colors.green,
unit: Unit.usd,
}),
line({
metric: lumpSumStack.sats,
name: "Lump sum",
color: colors.orange,
unit: Unit.sats,
}),
line({
metric: lumpSumStack.bitcoin,
name: "Lump sum",
color: colors.orange,
unit: Unit.btc,
}),
line({
metric: lumpSumStack.dollars,
name: "Lump sum",
color: colors.orange,
unit: Unit.usd,
}),
...satsBtcUsd(ctx, dcaStack, "DCA", colors.green),
...satsBtcUsd(ctx, lumpSumStack, "Lump sum", colors.orange),
],
},
],
@@ -196,29 +163,8 @@ export function createInvestingSection(ctx, { dca, lookback, returns }) {
name: "Stack",
title: "DCA Stack by Year ($100/day)",
bottom: dcaClasses.flatMap(
({ year, color, defaultActive, stack }) => [
line({
metric: stack.sats,
name: `${year}`,
color,
defaultActive,
unit: Unit.sats,
}),
line({
metric: stack.bitcoin,
name: `${year}`,
color,
defaultActive,
unit: Unit.btc,
}),
line({
metric: stack.dollars,
name: `${year}`,
color,
defaultActive,
unit: Unit.usd,
}),
],
({ year, color, defaultActive, stack }) =>
satsBtcUsd(ctx, stack, `${year}`, color, { defaultActive }),
),
},
],
@@ -254,26 +200,7 @@ export function createInvestingSection(ctx, { dca, lookback, returns }) {
{
name: "Stack",
title: `DCA Class ${year} Stack ($100/day)`,
bottom: [
line({
metric: stack.sats,
name: "Stack",
color,
unit: Unit.sats,
}),
line({
metric: stack.bitcoin,
name: "Stack",
color,
unit: Unit.btc,
}),
line({
metric: stack.dollars,
name: "Stack",
color,
unit: Unit.usd,
}),
],
bottom: satsBtcUsd(ctx, stack, "Stack", color),
},
],
})),
+99
View File
@@ -0,0 +1,99 @@
/** Shared helpers for options */
import { Unit } from "../utils/units.js";
/**
* Create sats/btc/usd line series from a pattern with .sats/.bitcoin/.dollars
* @param {PartialContext} ctx
* @param {{ sats: AnyMetricPattern, bitcoin: AnyMetricPattern, dollars: AnyMetricPattern }} pattern
* @param {string} name
* @param {Color} [color]
* @param {{ defaultActive?: boolean }} [options]
* @returns {FetchedLineSeriesBlueprint[]}
*/
export function satsBtcUsd(ctx, pattern, name, color, options) {
const { defaultActive } = options || {};
return [
ctx.line({ metric: pattern.sats, name, color, unit: Unit.sats, defaultActive }),
ctx.line({ metric: pattern.bitcoin, name, color, unit: Unit.btc, defaultActive }),
ctx.line({ metric: pattern.dollars, name, color, unit: Unit.usd, defaultActive }),
];
}
/**
* Create multiple price lines with the same unit
* @param {PartialContext} ctx
* @param {Unit} unit
* @param {number[]} numbers
*/
export function priceLines(ctx, unit, numbers) {
return numbers.map((n) => ctx.createPriceLine({ unit, number: n }));
}
/**
* Build percentile USD mappings from a ratio pattern
* @param {Colors} colors
* @param {ActivePriceRatioPattern} ratio
*/
export function percentileUsdMap(colors, ratio) {
return /** @type {const} */ ([
{ name: "pct99", prop: ratio.ratioPct99Usd, color: colors.rose },
{ name: "pct98", prop: ratio.ratioPct98Usd, color: colors.pink },
{ name: "pct95", prop: ratio.ratioPct95Usd, color: colors.fuchsia },
{ name: "pct5", prop: ratio.ratioPct5Usd, color: colors.cyan },
{ name: "pct2", prop: ratio.ratioPct2Usd, color: colors.sky },
{ name: "pct1", prop: ratio.ratioPct1Usd, color: colors.blue },
]);
}
/**
* Build percentile ratio mappings from a ratio pattern
* @param {Colors} colors
* @param {ActivePriceRatioPattern} ratio
*/
export function percentileMap(colors, ratio) {
return /** @type {const} */ ([
{ name: "pct99", prop: ratio.ratioPct99, color: colors.rose },
{ name: "pct98", prop: ratio.ratioPct98, color: colors.pink },
{ name: "pct95", prop: ratio.ratioPct95, color: colors.fuchsia },
{ name: "pct5", prop: ratio.ratioPct5, color: colors.cyan },
{ name: "pct2", prop: ratio.ratioPct2, color: colors.sky },
{ name: "pct1", prop: ratio.ratioPct1, color: colors.blue },
]);
}
/**
* Build SD patterns from a ratio pattern
* @param {ActivePriceRatioPattern} ratio
*/
export function sdPatterns(ratio) {
return /** @type {const} */ ([
{ nameAddon: "all", titleAddon: "", sd: ratio.ratioSd },
{ nameAddon: "4y", titleAddon: "4y", sd: ratio.ratio4ySd },
{ nameAddon: "2y", titleAddon: "2y", sd: ratio.ratio2ySd },
{ nameAddon: "1y", titleAddon: "1y", sd: ratio.ratio1ySd },
]);
}
/**
* Build SD band mappings from an SD pattern
* @param {Colors} colors
* @param {Ratio1ySdPattern} sd
*/
export function sdBands(colors, sd) {
return /** @type {const} */ ([
{ name: "0σ", prop: sd._0sdUsd, color: colors.lime },
{ name: "+0.5σ", prop: sd.p05sdUsd, color: colors.yellow },
{ name: "+1σ", prop: sd.p1sdUsd, color: colors.amber },
{ name: "+1.5σ", prop: sd.p15sdUsd, color: colors.orange },
{ name: "+2σ", prop: sd.p2sdUsd, color: colors.red },
{ name: "+2.5σ", prop: sd.p25sdUsd, color: colors.rose },
{ name: "+3σ", prop: sd.p3sd, color: colors.pink },
{ name: "0.5σ", prop: sd.m05sdUsd, color: colors.teal },
{ name: "1σ", prop: sd.m1sdUsd, color: colors.cyan },
{ name: "1.5σ", prop: sd.m15sdUsd, color: colors.sky },
{ name: "2σ", prop: sd.m2sdUsd, color: colors.blue },
{ name: "2.5σ", prop: sd.m25sdUsd, color: colors.indigo },
{ name: "3σ", prop: sd.m3sd, color: colors.violet },
]);
}
+48 -61
View File
@@ -5,11 +5,11 @@ import {
} from "../../utils/dom.js";
import { chartElement } from "../../utils/elements.js";
import { ios, canShare } from "../../utils/env.js";
import { serdeChartableIndex, serdeOptNumber } from "../../utils/serde.js";
import { throttle } from "../../utils/timing.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";
@@ -33,30 +33,10 @@ export function init({ colors, option, brk }) {
const { headerElement, headingElement } = createHeader();
chartElement.append(headerElement);
const { index, fieldset } = createIndexSelector(option);
const state = createChartState(signals);
const { fieldset, index } = createIndexSelector(option, state);
const TIMERANGE_LS_KEY = signals.createMemo(
() => `chart-timerange-${index()}`,
);
let firstRun = true;
const from = signals.createSignal(/** @type {number | null} */ (null), {
save: {
...serdeOptNumber,
keyPrefix: TIMERANGE_LS_KEY,
key: "from",
serializeParam: firstRun,
},
});
const to = signals.createSignal(/** @type {number | null} */ (null), {
save: {
...serdeOptNumber,
keyPrefix: TIMERANGE_LS_KEY,
key: "to",
serializeParam: firstRun,
},
});
const { from, to } = state.range();
const chart = createChartElement({
parent: chartElement,
@@ -65,17 +45,12 @@ export function init({ colors, option, brk }) {
id: "charts",
brk,
index,
initialVisibleBarsCount:
from !== null && to !== null ? to - from : null,
timeScaleSetCallback: (unknownTimeScaleCallback) => {
// TODO: Although it mostly works in practice, need to make it more robust, there is no guarantee that this runs in order and wait for `from` and `to` to update when `index` and thus `TIMERANGE_LS_KEY` is updated
// Need to have the right values before the update
const from_ = from();
const to_ = to();
if (from_ !== null && to_ !== null) {
chart.inner.timeScale().setVisibleLogicalRange({
from: from_,
to: to_,
});
const { from, to } = state.range();
if (from !== null && to !== null) {
chart.setVisibleLogicalRange({ from, to });
} else {
unknownTimeScaleCallback();
}
@@ -114,13 +89,10 @@ export function init({ colors, option, brk }) {
});
}
chart.inner.timeScale().subscribeVisibleLogicalRangeChange(
throttle((t) => {
if (!t) return;
from.set(t.from);
to.set(t.to);
}, 250),
);
chart.onVisibleLogicalRangeChange((t) => {
if (!t) return;
state.setRange({ from: t.from, to: t.to });
});
chartElement.append(fieldset);
@@ -230,7 +202,7 @@ export function init({ colors, option, brk }) {
}
}
signals.createEffect(option, (option) => {
signals.createScopedEffect(option, (option) => {
headingElement.innerHTML = option.title;
const bottomUnits = Array.from(option.bottom.keys());
@@ -267,8 +239,8 @@ export function init({ colors, option, brk }) {
chart.legendBottom.removeFrom(0);
}
signals.createEffect(index, (index) => {
signals.createEffect(topUnit, (topUnit) => {
signals.createScopedEffect(index, (index) => {
signals.createScopedEffect(topUnit, (topUnit) => {
/** @type {AnySeries | undefined} */
let series;
@@ -328,7 +300,7 @@ export function init({ colors, option, brk }) {
orderStart,
legend,
}) {
signals.createEffect(unit, (unit) => {
signals.createScopedEffect(unit, (unit) => {
legend.removeFrom(orderStart);
seriesList.splice(orderStart).forEach((series) => {
@@ -450,15 +422,15 @@ export function init({ colors, option, brk }) {
});
}
firstRun = false;
});
});
}
/**
* @param {Accessor<ChartOption>} option
* @param {ReturnType<typeof createChartState>} state
*/
function createIndexSelector(option) {
function createIndexSelector(option, state) {
const choices_ = /** @satisfies {ChartableIndexName[]} */ ([
"timestamp",
"date",
@@ -497,17 +469,7 @@ function createIndexSelector(option) {
);
});
/** @type {ChartableIndexName} */
const defaultIndex = "date";
const { field, selected } = createChoiceField({
defaultValue: defaultIndex,
keyPrefix,
key: "index",
choices,
id: "index",
signals,
});
// Create UI that syncs with state.index
const fieldset = window.document.createElement("fieldset");
fieldset.id = "interval";
@@ -515,11 +477,36 @@ function createIndexSelector(option) {
screenshotSpan.innerText = "interval:";
fieldset.append(screenshotSpan);
fieldset.append(field);
const select = window.document.createElement("select");
select.id = "index";
fieldset.append(select);
fieldset.dataset.size = "sm";
// Populate and update options when choices change
signals.createEffect(choices, (choices) => {
const currentValue = state.index();
select.innerHTML = "";
choices.forEach((choice) => {
const option = window.document.createElement("option");
option.value = choice;
option.textContent = choice;
option.selected = choice === currentValue;
select.append(option);
});
});
// Sync select value with state
signals.createEffect(state.index, (value) => {
select.value = value;
});
select.addEventListener("change", () => {
state.index.set(/** @type {ChartableIndexName} */ (select.value));
});
// Convert short name to internal name
const index = signals.createMemo(() =>
serdeChartableIndex.deserialize(selected()),
serdeChartableIndex.deserialize(state.index()),
);
return { fieldset, index };
+3 -3
View File
@@ -74,7 +74,7 @@ export function init({ colors }) {
let stateValue = /** @type {string | null} */ (null);
signals.createEffect(
signals.createScopedEffect(
() => {
const value = signal();
return value ? String(value) : "";
@@ -137,7 +137,7 @@ export function init({ colors }) {
let stateValue = /** @type {string | null} */ (null);
signals.createEffect(
signals.createScopedEffect(
() => {
const dateSignal = signal();
return dateSignal ? serdeDate.serialize(dateSignal) : "";
@@ -838,7 +838,7 @@ export function init({ colors }) {
const closes = /** @type {number[]} */ (_closes);
signals.runWithOwner(owner, () => {
signals.createEffect(
signals.createScopedEffect(
() => ({
initialDollarAmount: settings.dollars.initial.amount() || 0,
topUpAmount: settings.dollars.topUp.amount() || 0,
+33 -21
View File
@@ -23,13 +23,14 @@ import {
runWithOwner,
onCleanup,
} from "./modules/solidjs-signals/0.6.3/dist/prod.js";
import { debounce } from "./utils/timing.js";
// let effectCount = 0;
let effectCount = 0;
const signals = {
createSolidSignal: /** @type {typeof CreateSignal} */ (createSignal),
createSolidEffect: /** @type {typeof CreateEffect} */ (createEffect),
createEffect: /** @type {typeof CreateEffect} */ (
createEffect: /** @type {typeof CreateEffect} */ (createEffect),
createScopedEffect: /** @type {typeof CreateEffect} */ (
// @ts-ignore
(compute, effect) => {
let dispose = /** @type {VoidFunction | null} */ (null);
@@ -42,13 +43,13 @@ const signals = {
if (dispose) {
dispose();
dispose = null;
// console.log("effectCount = ", --effectCount);
console.log("effectCount = ", --effectCount);
}
}
// @ts-ignore
createEffect(compute, (v, oldV) => {
// console.log("effectCount = ", ++effectCount);
console.log("effectCount = ", ++effectCount);
cleanup();
signals.createRoot((_dispose) => {
dispose = _dispose;
@@ -143,10 +144,9 @@ const signals = {
});
let firstRun2 = true;
this.createEffect(get, (value) => {
if (!save) return;
if (!firstRun2) {
const debouncedSave = debounce(
/** @param {T} value */ (value) => {
try {
if (
value !== undefined &&
@@ -157,26 +157,38 @@ const signals = {
save.serialize(value) !== save.serialize(initialValue))
) {
localStorage.setItem(storageKey(), save.serialize(value));
writeParam(paramKey, save.serialize(value));
} else {
localStorage.removeItem(storageKey());
removeParam(paramKey);
}
} catch (_) {}
}
},
250,
);
if (
value !== undefined &&
value !== null &&
(initialValue === undefined ||
initialValue === null ||
save.saveDefaultValue ||
save.serialize(value) !== save.serialize(initialValue))
) {
writeParam(paramKey, save.serialize(value));
this.createEffect(get, (value) => {
if (!save) return;
if (firstRun2) {
// First run: sync URL params immediately
if (
value !== undefined &&
value !== null &&
(initialValue === undefined ||
initialValue === null ||
save.saveDefaultValue ||
save.serialize(value) !== save.serialize(initialValue))
) {
writeParam(paramKey, save.serialize(value));
} else {
removeParam(paramKey);
}
firstRun2 = false;
} else {
removeParam(paramKey);
// Subsequent runs: debounce
debouncedSave(value);
}
firstRun2 = false;
});
}
+1 -1
View File
@@ -291,7 +291,7 @@ export function createChoiceField({
field.append(remainingSmall);
}
signals.createEffect(choices, (choices) => {
signals.createScopedEffect(choices, (choices) => {
const s = selected();
const sKey = toKey(s);
const keys = choices.map(toKey);
+47
View File
@@ -24,6 +24,53 @@ export const numberToPercentage = new Intl.NumberFormat("en-US", {
maximumFractionDigits: 2,
});
/**
* @param {number} value
* @param {0 | 2} [digits]
*/
export function numberToShortUSFormat(value, digits) {
const absoluteValue = Math.abs(value);
if (isNaN(value)) {
return "";
} else if (absoluteValue < 10) {
return numberToUSNumber(value, Math.min(3, digits || 10));
} else if (absoluteValue < 1_000) {
return numberToUSNumber(value, Math.min(2, digits || 10));
} else if (absoluteValue < 10_000) {
return numberToUSNumber(value, Math.min(1, digits || 10));
} else if (absoluteValue < 1_000_000) {
return numberToUSNumber(value, 0);
} else if (absoluteValue >= 1_000_000_000_000_000_000_000) {
return "Inf.";
}
const log = Math.floor(Math.log10(absoluteValue) - 6);
const suffices = ["M", "B", "T", "P", "E", "Z"];
const letterIndex = Math.floor(log / 3);
const letter = suffices[letterIndex];
const modulused = log % 3;
if (modulused === 0) {
return `${numberToUSNumber(
value / (1_000_000 * 1_000 ** letterIndex),
3,
)}${letter}`;
} else if (modulused === 1) {
return `${numberToUSNumber(
value / (1_000_000 * 1_000 ** letterIndex),
2,
)}${letter}`;
} else {
return `${numberToUSNumber(
value / (1_000_000 * 1_000 ** letterIndex),
1,
)}${letter}`;
}
}
/**
* @param {string} s
*/
+20
View File
@@ -36,3 +36,23 @@ export function throttle(callback, wait = 1000) {
}
};
}
/**
* @template {(...args: any[]) => any} F
* @param {F} callback
* @param {number} [wait]
*/
export function debounce(callback, wait = 1000) {
/** @type {number | null} */
let timeoutId = null;
return (/** @type {Parameters<F>} */ ...args) => {
if (timeoutId) {
clearTimeout(timeoutId);
}
timeoutId = setTimeout(() => {
callback(...args);
timeoutId = null;
}, wait);
};
}