mirror of
https://github.com/bitcoinresearchkit/brk.git
synced 2026-04-28 00:29:58 -07:00
global: MASSIVE snapshot
This commit is contained in:
20
websites/bitview/scripts/utils/array.js
Normal file
20
websites/bitview/scripts/utils/array.js
Normal file
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* @param {number} start
|
||||
* @param {number} end
|
||||
*/
|
||||
export function range(start, end) {
|
||||
const range = [];
|
||||
while (start <= end) {
|
||||
range.push(start);
|
||||
start += 1;
|
||||
}
|
||||
return range;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template T
|
||||
* @param {T[]} array
|
||||
*/
|
||||
export function randomFromArray(array) {
|
||||
return array[Math.floor(Math.random() * array.length)];
|
||||
}
|
||||
116
websites/bitview/scripts/utils/colors.js
Normal file
116
websites/bitview/scripts/utils/colors.js
Normal file
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
* @param {Accessor<boolean>} dark
|
||||
*/
|
||||
export function createColors(dark) {
|
||||
const globalComputedStyle = getComputedStyle(window.document.documentElement);
|
||||
/**
|
||||
* @param {string} color
|
||||
*/
|
||||
function getColor(color) {
|
||||
return globalComputedStyle.getPropertyValue(`--${color}`);
|
||||
}
|
||||
function red() {
|
||||
return getColor("red");
|
||||
}
|
||||
function orange() {
|
||||
return getColor("orange");
|
||||
}
|
||||
function amber() {
|
||||
return getColor("amber");
|
||||
}
|
||||
function yellow() {
|
||||
return getColor("yellow");
|
||||
}
|
||||
function avocado() {
|
||||
return getColor("avocado");
|
||||
}
|
||||
function lime() {
|
||||
return getColor("lime");
|
||||
}
|
||||
function green() {
|
||||
return getColor("green");
|
||||
}
|
||||
function emerald() {
|
||||
return getColor("emerald");
|
||||
}
|
||||
function teal() {
|
||||
return getColor("teal");
|
||||
}
|
||||
function cyan() {
|
||||
return getColor("cyan");
|
||||
}
|
||||
function sky() {
|
||||
return getColor("sky");
|
||||
}
|
||||
function blue() {
|
||||
return getColor("blue");
|
||||
}
|
||||
function indigo() {
|
||||
return getColor("indigo");
|
||||
}
|
||||
function violet() {
|
||||
return getColor("violet");
|
||||
}
|
||||
function purple() {
|
||||
return getColor("purple");
|
||||
}
|
||||
function fuchsia() {
|
||||
return getColor("fuchsia");
|
||||
}
|
||||
function pink() {
|
||||
return getColor("pink");
|
||||
}
|
||||
function rose() {
|
||||
return getColor("rose");
|
||||
}
|
||||
function gray() {
|
||||
return getColor("gray");
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} property
|
||||
*/
|
||||
function getLightDarkValue(property) {
|
||||
const value = globalComputedStyle.getPropertyValue(property);
|
||||
const [light, _dark] = value.slice(11, -1).split(", ");
|
||||
return dark() ? _dark : light;
|
||||
}
|
||||
|
||||
function textColor() {
|
||||
return getLightDarkValue("--color");
|
||||
}
|
||||
function borderColor() {
|
||||
return getLightDarkValue("--border-color");
|
||||
}
|
||||
|
||||
return {
|
||||
default: textColor,
|
||||
gray,
|
||||
border: borderColor,
|
||||
|
||||
red,
|
||||
orange,
|
||||
amber,
|
||||
yellow,
|
||||
avocado,
|
||||
lime,
|
||||
green,
|
||||
emerald,
|
||||
teal,
|
||||
cyan,
|
||||
sky,
|
||||
blue,
|
||||
indigo,
|
||||
violet,
|
||||
purple,
|
||||
fuchsia,
|
||||
pink,
|
||||
rose,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {ReturnType<typeof createColors>} Colors
|
||||
* @typedef {Colors["orange"]} Color
|
||||
* @typedef {keyof Colors} ColorName
|
||||
*/
|
||||
58
websites/bitview/scripts/utils/date.js
Normal file
58
websites/bitview/scripts/utils/date.js
Normal file
@@ -0,0 +1,58 @@
|
||||
const ONE_DAY_IN_MS = 1000 * 60 * 60 * 24;
|
||||
|
||||
export function todayUTC() {
|
||||
const today = new Date();
|
||||
return new Date(
|
||||
Date.UTC(
|
||||
today.getUTCFullYear(),
|
||||
today.getUTCMonth(),
|
||||
today.getUTCDate(),
|
||||
0,
|
||||
0,
|
||||
0,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Date} date
|
||||
*/
|
||||
export function dateToDateIndex(date) {
|
||||
if (
|
||||
date.getUTCFullYear() === 2009 &&
|
||||
date.getUTCMonth() === 0 &&
|
||||
date.getUTCDate() === 3
|
||||
)
|
||||
return 0;
|
||||
return differenceBetweenDates(date, new Date("2009-01-09"));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Date} start
|
||||
* @param {Date} end
|
||||
*/
|
||||
export function createDateRange(start, end) {
|
||||
const dates = /** @type {Date[]} */ ([]);
|
||||
let currentDate = new Date(start);
|
||||
while (currentDate <= end) {
|
||||
dates.push(new Date(currentDate));
|
||||
currentDate.setUTCDate(currentDate.getUTCDate() + 1);
|
||||
}
|
||||
return dates;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Date} date1
|
||||
* @param {Date} date2
|
||||
*/
|
||||
export function differenceBetweenDates(date1, date2) {
|
||||
return Math.abs(date1.valueOf() - date2.valueOf()) / ONE_DAY_IN_MS;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Date} date1
|
||||
* @param {Date} date2
|
||||
*/
|
||||
export function roundedDifferenceBetweenDates(date1, date2) {
|
||||
return Math.round(differenceBetweenDates(date1, date2));
|
||||
}
|
||||
446
websites/bitview/scripts/utils/dom.js
Normal file
446
websites/bitview/scripts/utils/dom.js
Normal file
@@ -0,0 +1,446 @@
|
||||
import { serdeString } from "./serde";
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @returns {HTMLElement}
|
||||
*/
|
||||
export function getElementById(id) {
|
||||
const element = window.document.getElementById(id);
|
||||
if (!element) throw `Element with id = "${id}" should exist`;
|
||||
return element;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLElement} element
|
||||
*/
|
||||
export function isHidden(element) {
|
||||
return element.tagName !== "BODY" && !element.offsetParent;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {HTMLElement} element
|
||||
* @param {VoidFunction} callback
|
||||
*/
|
||||
export function onFirstIntersection(element, callback) {
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
if (entries[i].isIntersecting) {
|
||||
callback();
|
||||
observer.disconnect();
|
||||
}
|
||||
}
|
||||
});
|
||||
observer.observe(element);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} name
|
||||
*/
|
||||
export function createSpanName(name) {
|
||||
const spanName = window.document.createElement("span");
|
||||
spanName.classList.add("name");
|
||||
const [first, second, third] = name.split(" - ");
|
||||
spanName.innerHTML = first;
|
||||
|
||||
if (second) {
|
||||
const smallRest = window.document.createElement("small");
|
||||
smallRest.innerHTML = ` — ${second}`;
|
||||
spanName.append(smallRest);
|
||||
|
||||
if (third) {
|
||||
throw "Shouldn't have more than one dash";
|
||||
}
|
||||
}
|
||||
|
||||
return spanName;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} arg
|
||||
* @param {string} arg.href
|
||||
* @param {string} arg.title
|
||||
* @param {string} [arg.text]
|
||||
* @param {boolean} [arg.blank]
|
||||
* @param {VoidFunction} [arg.onClick]
|
||||
* @param {boolean} [arg.preventDefault]
|
||||
*/
|
||||
export function createAnchorElement({
|
||||
text,
|
||||
href,
|
||||
blank,
|
||||
onClick,
|
||||
title,
|
||||
preventDefault,
|
||||
}) {
|
||||
const anchor = window.document.createElement("a");
|
||||
anchor.href = href;
|
||||
anchor.title = title.toUpperCase();
|
||||
|
||||
if (text) {
|
||||
anchor.innerText = text;
|
||||
}
|
||||
|
||||
if (blank) {
|
||||
anchor.target = "_blank";
|
||||
anchor.rel = "noopener noreferrer";
|
||||
}
|
||||
|
||||
if (onClick || preventDefault) {
|
||||
if (onClick) {
|
||||
anchor.addEventListener("click", (event) => {
|
||||
event.preventDefault();
|
||||
onClick();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return anchor;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} arg
|
||||
* @param {string | HTMLElement} arg.inside
|
||||
* @param {string} arg.title
|
||||
* @param {(event: MouseEvent) => void} arg.onClick
|
||||
*/
|
||||
export function createButtonElement({ inside: text, onClick, title }) {
|
||||
const button = window.document.createElement("button");
|
||||
|
||||
button.append(text);
|
||||
|
||||
button.title = title.toUpperCase();
|
||||
|
||||
button.addEventListener("click", onClick);
|
||||
|
||||
return button;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} args
|
||||
* @param {string} args.inputName
|
||||
* @param {string} args.inputId
|
||||
* @param {string} args.inputValue
|
||||
* @param {boolean} [args.inputChecked=false]
|
||||
* @param {string} [args.title]
|
||||
* @param {'radio' | 'checkbox'} args.type
|
||||
* @param {(event: MouseEvent) => void} [args.onClick]
|
||||
*/
|
||||
export function createLabeledInput({
|
||||
inputId,
|
||||
inputName,
|
||||
inputValue,
|
||||
inputChecked = false,
|
||||
title,
|
||||
onClick,
|
||||
type,
|
||||
}) {
|
||||
const label = window.document.createElement("label");
|
||||
|
||||
inputId = inputId.toLowerCase();
|
||||
|
||||
const input = window.document.createElement("input");
|
||||
if (type === "radio") {
|
||||
input.type = "radio";
|
||||
input.name = inputName;
|
||||
} else {
|
||||
input.type = "checkbox";
|
||||
}
|
||||
input.id = inputId;
|
||||
input.value = inputValue;
|
||||
input.checked = inputChecked;
|
||||
label.append(input);
|
||||
|
||||
label.id = `${inputId}-label`;
|
||||
if (title) {
|
||||
label.title = title;
|
||||
}
|
||||
label.htmlFor = inputId;
|
||||
|
||||
if (onClick) {
|
||||
label.addEventListener("click", onClick);
|
||||
}
|
||||
|
||||
return {
|
||||
label,
|
||||
input,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {HTMLElement} parent
|
||||
* @param {HTMLElement} child
|
||||
* @param {number} index
|
||||
*/
|
||||
export function insertElementAtIndex(parent, child, index) {
|
||||
if (!index) index = 0;
|
||||
if (index >= parent.children.length) {
|
||||
parent.appendChild(child);
|
||||
} else {
|
||||
parent.insertBefore(child, parent.children[index]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {boolean} [targetBlank]
|
||||
*/
|
||||
export function open(url, targetBlank) {
|
||||
console.log(`open: ${url}`);
|
||||
const a = window.document.createElement("a");
|
||||
window.document.body.append(a);
|
||||
a.href = url;
|
||||
|
||||
if (targetBlank) {
|
||||
a.target = "_blank";
|
||||
a.rel = "noopener noreferrer";
|
||||
}
|
||||
|
||||
a.click();
|
||||
a.remove();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} href
|
||||
*/
|
||||
export function importStyle(href) {
|
||||
const link = document.createElement("link");
|
||||
link.href = href;
|
||||
link.type = "text/css";
|
||||
link.rel = "stylesheet";
|
||||
link.media = "screen,print";
|
||||
const head = window.document.getElementsByTagName("head")[0];
|
||||
head.appendChild(link);
|
||||
return link;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template {Readonly<string[]>} T
|
||||
* @param {Object} args
|
||||
* @param {T[number]} args.defaultValue
|
||||
* @param {string} [args.id]
|
||||
* @param {T | Accessor<T>} args.choices
|
||||
* @param {string} [args.keyPrefix]
|
||||
* @param {string} args.key
|
||||
* @param {boolean} [args.sorted]
|
||||
* @param {Signals} args.signals
|
||||
*/
|
||||
export function createHorizontalChoiceField({
|
||||
id,
|
||||
choices: unsortedChoices,
|
||||
defaultValue,
|
||||
keyPrefix,
|
||||
key,
|
||||
signals,
|
||||
sorted,
|
||||
}) {
|
||||
const choices = signals.createMemo(() => {
|
||||
/** @type {T} */
|
||||
let c;
|
||||
if (typeof unsortedChoices === "function") {
|
||||
c = unsortedChoices();
|
||||
} else {
|
||||
c = unsortedChoices;
|
||||
}
|
||||
|
||||
return sorted
|
||||
? /** @type {T} */ (
|
||||
/** @type {any} */ (c.toSorted((a, b) => a.localeCompare(b)))
|
||||
)
|
||||
: c;
|
||||
});
|
||||
|
||||
/** @type {Signal<T[number]>} */
|
||||
const selected = signals.createSignal(defaultValue, {
|
||||
save: {
|
||||
...serdeString,
|
||||
keyPrefix: keyPrefix ?? "",
|
||||
key,
|
||||
saveDefaultValue: true,
|
||||
},
|
||||
});
|
||||
|
||||
const field = window.document.createElement("div");
|
||||
field.classList.add("field");
|
||||
|
||||
const div = window.document.createElement("div");
|
||||
field.append(div);
|
||||
|
||||
signals.createEffect(choices, (choices) => {
|
||||
const s = selected();
|
||||
if (!choices.includes(s)) {
|
||||
if (choices.includes(defaultValue)) {
|
||||
selected.set(() => defaultValue);
|
||||
} else if (choices.length) {
|
||||
selected.set(() => choices[0]);
|
||||
}
|
||||
}
|
||||
|
||||
div.innerHTML = "";
|
||||
|
||||
choices.forEach((choice) => {
|
||||
const inputValue = choice;
|
||||
const { label } = createLabeledInput({
|
||||
inputId: `${id ?? key}-${choice.toLowerCase()}`,
|
||||
inputName: id ?? key,
|
||||
inputValue,
|
||||
inputChecked: inputValue === selected(),
|
||||
// title: choice,
|
||||
type: "radio",
|
||||
});
|
||||
|
||||
const text = window.document.createTextNode(choice);
|
||||
label.append(text);
|
||||
div.append(label);
|
||||
});
|
||||
});
|
||||
|
||||
field.addEventListener("change", (event) => {
|
||||
// @ts-ignore
|
||||
const value = event.target.value;
|
||||
selected.set(value);
|
||||
});
|
||||
|
||||
return { field, selected };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} [title]
|
||||
* @param {1 | 2 | 3} [level]
|
||||
*/
|
||||
export function createHeader(title = "", level = 1) {
|
||||
const headerElement = window.document.createElement("header");
|
||||
|
||||
const headingElement = window.document.createElement(`h${level}`);
|
||||
headingElement.innerHTML = title;
|
||||
headerElement.append(headingElement);
|
||||
headingElement.style.display = "block";
|
||||
|
||||
return {
|
||||
headerElement,
|
||||
headingElement,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @template {string} Name
|
||||
* @template {string} Value
|
||||
* @template {Value | {name: Name; value: Value}} T
|
||||
* @param {T} arg
|
||||
*/
|
||||
export function createOption(arg) {
|
||||
const option = window.document.createElement("option");
|
||||
if (typeof arg === "object") {
|
||||
option.value = arg.value;
|
||||
option.innerText = arg.name;
|
||||
} else {
|
||||
option.value = arg;
|
||||
option.innerText = arg;
|
||||
}
|
||||
return option;
|
||||
}
|
||||
|
||||
/**
|
||||
* @template {string} Name
|
||||
* @template {string} Value
|
||||
* @template {Value | {name: Name; value: Value}} T
|
||||
* @param {Object} args
|
||||
* @param {string} [args.id]
|
||||
* @param {boolean} [args.deep]
|
||||
* @param {readonly ((T) | {name: string; list: T[]})[]} args.list
|
||||
* @param {Signal<T>} args.signal
|
||||
*/
|
||||
export function createSelect({ id, list, signal, deep = false }) {
|
||||
const select = window.document.createElement("select");
|
||||
|
||||
if (id) {
|
||||
select.name = id;
|
||||
select.id = id;
|
||||
}
|
||||
|
||||
/** @type {Record<string, VoidFunction>} */
|
||||
const setters = {};
|
||||
|
||||
list.forEach((anyOption, index) => {
|
||||
if (typeof anyOption === "object" && "list" in anyOption) {
|
||||
const { name, list } = anyOption;
|
||||
const optGroup = window.document.createElement("optgroup");
|
||||
optGroup.label = name;
|
||||
select.append(optGroup);
|
||||
list.forEach((option) => {
|
||||
optGroup.append(createOption(option));
|
||||
const key = /** @type {string} */ (
|
||||
typeof option === "object" ? option.value : option
|
||||
);
|
||||
setters[key] = () => signal.set(() => option);
|
||||
});
|
||||
} else {
|
||||
select.append(createOption(anyOption));
|
||||
const key = /** @type {string} */ (
|
||||
typeof anyOption === "object" ? anyOption.value : anyOption
|
||||
);
|
||||
setters[key] = () => signal.set(() => anyOption);
|
||||
}
|
||||
if (deep && index !== list.length - 1) {
|
||||
select.append(window.document.createElement("hr"));
|
||||
}
|
||||
});
|
||||
|
||||
select.addEventListener("change", () => {
|
||||
const callback = setters[select.value];
|
||||
// @ts-ignore
|
||||
if (callback) {
|
||||
callback();
|
||||
}
|
||||
});
|
||||
|
||||
const initialSignal = signal();
|
||||
const initialValue =
|
||||
typeof initialSignal === "object" ? initialSignal.value : initialSignal;
|
||||
select.value = String(initialValue);
|
||||
|
||||
return { select, signal };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} args
|
||||
* @param {string} args.title
|
||||
* @param {string} args.description
|
||||
* @param {HTMLElement} args.input
|
||||
*/
|
||||
export function createFieldElement({ title, description, input }) {
|
||||
const div = window.document.createElement("div");
|
||||
|
||||
const label = window.document.createElement("label");
|
||||
div.append(label);
|
||||
|
||||
const titleElement = window.document.createElement("span");
|
||||
titleElement.innerHTML = title;
|
||||
label.append(titleElement);
|
||||
|
||||
const descriptionElement = window.document.createElement("small");
|
||||
descriptionElement.innerHTML = description;
|
||||
label.append(descriptionElement);
|
||||
|
||||
div.append(input);
|
||||
|
||||
const forId = input.id || input.firstElementChild?.id;
|
||||
|
||||
if (!forId) {
|
||||
console.log(input);
|
||||
throw `Input should've an ID`;
|
||||
}
|
||||
|
||||
label.htmlFor = forId;
|
||||
|
||||
return div;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {'left' | 'bottom' | 'top' | 'right'} position
|
||||
*/
|
||||
export function createShadow(position) {
|
||||
const div = window.document.createElement("div");
|
||||
div.classList.add(`shadow-${position}`);
|
||||
return div;
|
||||
}
|
||||
24
websites/bitview/scripts/utils/elements.js
Normal file
24
websites/bitview/scripts/utils/elements.js
Normal file
@@ -0,0 +1,24 @@
|
||||
import { getElementById } from "./dom";
|
||||
|
||||
export const style = getComputedStyle(window.document.documentElement);
|
||||
|
||||
export const headElement = window.document.getElementsByTagName("head")[0];
|
||||
export const bodyElement = window.document.body;
|
||||
|
||||
export const mainElement = getElementById("main");
|
||||
export const asideElement = getElementById("aside");
|
||||
export const searchElement = getElementById("search");
|
||||
export const navElement = getElementById("nav");
|
||||
export const chartElement = getElementById("chart");
|
||||
export const tableElement = getElementById("table");
|
||||
export const explorerElement = getElementById("explorer");
|
||||
export const simulationElement = getElementById("simulation");
|
||||
|
||||
export const asideLabelElement = getElementById("aside-selector-label");
|
||||
export const navLabelElement = getElementById(`nav-selector-label`);
|
||||
export const searchLabelElement = getElementById(`search-selector-label`);
|
||||
export const searchInput = /** @type {HTMLInputElement} */ (
|
||||
getElementById("search-input")
|
||||
);
|
||||
export const searchResultsElement = getElementById("search-results");
|
||||
export const frameSelectorsElement = getElementById("frame-selectors");
|
||||
12
websites/bitview/scripts/utils/env.js
Normal file
12
websites/bitview/scripts/utils/env.js
Normal file
@@ -0,0 +1,12 @@
|
||||
export const localhost = window.location.hostname === "localhost";
|
||||
export const standalone =
|
||||
"standalone" in window.navigator && !!window.navigator.standalone;
|
||||
export const userAgent = navigator.userAgent.toLowerCase();
|
||||
export const isChrome = userAgent.includes("chrome");
|
||||
export const safari = userAgent.includes("safari");
|
||||
export const safariOnly = safari && !isChrome;
|
||||
export const macOS = userAgent.includes("mac os");
|
||||
export const iphone = userAgent.includes("iphone");
|
||||
export const ipad = userAgent.includes("ipad");
|
||||
export const ios = iphone || ipad;
|
||||
export const canShare = "canShare" in navigator;
|
||||
38
websites/bitview/scripts/utils/format.js
Normal file
38
websites/bitview/scripts/utils/format.js
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* @param {number} value
|
||||
* @param {number} [digits]
|
||||
* @param {Intl.NumberFormatOptions} [options]
|
||||
*/
|
||||
export function numberToUSNumber(value, digits, options) {
|
||||
return value.toLocaleString("en-us", {
|
||||
...options,
|
||||
minimumFractionDigits: digits,
|
||||
maximumFractionDigits: digits,
|
||||
});
|
||||
}
|
||||
|
||||
export const numberToDollars = new Intl.NumberFormat("en-US", {
|
||||
style: "currency",
|
||||
currency: "USD",
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
|
||||
export const numberToPercentage = new Intl.NumberFormat("en-US", {
|
||||
style: "percent",
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
|
||||
/**
|
||||
* @param {string} s
|
||||
*/
|
||||
export function stringToId(s) {
|
||||
return (
|
||||
s
|
||||
// .replace(/\W/g, " ")
|
||||
.trim()
|
||||
.replace(/ +/g, "-")
|
||||
.toLowerCase()
|
||||
);
|
||||
}
|
||||
535
websites/bitview/scripts/utils/serde.js
Normal file
535
websites/bitview/scripts/utils/serde.js
Normal file
@@ -0,0 +1,535 @@
|
||||
const localhost = window.location.hostname === "localhost";
|
||||
console.log({ localhost });
|
||||
|
||||
export const serdeString = {
|
||||
/**
|
||||
* @param {string} v
|
||||
*/
|
||||
serialize(v) {
|
||||
return v;
|
||||
},
|
||||
/**
|
||||
* @param {string} v
|
||||
*/
|
||||
deserialize(v) {
|
||||
return v;
|
||||
},
|
||||
};
|
||||
|
||||
export const serdeMetrics = {
|
||||
/**
|
||||
* @param {Metric[]} v
|
||||
*/
|
||||
serialize(v) {
|
||||
return v.join(",");
|
||||
},
|
||||
/**
|
||||
* @param {string} v
|
||||
*/
|
||||
deserialize(v) {
|
||||
return /** @type {Metric[]} */ (v.split(","));
|
||||
},
|
||||
};
|
||||
|
||||
export const serdeNumber = {
|
||||
/**
|
||||
* @param {number} v
|
||||
*/
|
||||
serialize(v) {
|
||||
return String(v);
|
||||
},
|
||||
/**
|
||||
* @param {string} v
|
||||
*/
|
||||
deserialize(v) {
|
||||
return Number(v);
|
||||
},
|
||||
};
|
||||
|
||||
export const serdeOptNumber = {
|
||||
/**
|
||||
* @param {number | null} v
|
||||
*/
|
||||
serialize(v) {
|
||||
return v !== null ? String(v) : "";
|
||||
},
|
||||
/**
|
||||
* @param {string} v
|
||||
*/
|
||||
deserialize(v) {
|
||||
return v ? Number(v) : null;
|
||||
},
|
||||
};
|
||||
|
||||
export const serdeDate = {
|
||||
/**
|
||||
* @param {Date} date
|
||||
*/
|
||||
serialize(date) {
|
||||
return date.toString();
|
||||
},
|
||||
/**
|
||||
* @param {string} v
|
||||
*/
|
||||
deserialize(v) {
|
||||
return new Date(v);
|
||||
},
|
||||
};
|
||||
|
||||
export const serdeOptDate = {
|
||||
/**
|
||||
* @param {Date | null} date
|
||||
*/
|
||||
serialize(date) {
|
||||
return date !== null ? date.toString() : "";
|
||||
},
|
||||
/**
|
||||
* @param {string} v
|
||||
*/
|
||||
deserialize(v) {
|
||||
return new Date(v);
|
||||
},
|
||||
};
|
||||
|
||||
export const serdeBool = {
|
||||
/**
|
||||
* @param {boolean} v
|
||||
*/
|
||||
serialize(v) {
|
||||
return String(v);
|
||||
},
|
||||
/**
|
||||
* @param {string} v
|
||||
*/
|
||||
deserialize(v) {
|
||||
if (v === "true" || v === "1") {
|
||||
return true;
|
||||
} else if (v === "false" || v === "0") {
|
||||
return false;
|
||||
} else {
|
||||
throw "deser bool err";
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export const serdeChartableIndex = {
|
||||
/**
|
||||
* @param {IndexName} v
|
||||
* @returns {ChartableIndexName | null}
|
||||
*/
|
||||
serialize(v) {
|
||||
switch (v) {
|
||||
case "dateindex":
|
||||
return "date";
|
||||
case "decadeindex":
|
||||
return "decade";
|
||||
case "difficultyepoch":
|
||||
return "epoch";
|
||||
case "height":
|
||||
return "timestamp";
|
||||
case "monthindex":
|
||||
return "month";
|
||||
case "quarterindex":
|
||||
return "quarter";
|
||||
case "semesterindex":
|
||||
return "semester";
|
||||
case "weekindex":
|
||||
return "week";
|
||||
case "yearindex":
|
||||
return "year";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
},
|
||||
/**
|
||||
* @param {ChartableIndexName} v
|
||||
* @returns {IndexName}
|
||||
*/
|
||||
deserialize(v) {
|
||||
switch (v) {
|
||||
case "timestamp":
|
||||
return "height";
|
||||
case "date":
|
||||
return "dateindex";
|
||||
case "week":
|
||||
return "weekindex";
|
||||
case "epoch":
|
||||
return "difficultyepoch";
|
||||
case "month":
|
||||
return "monthindex";
|
||||
case "quarter":
|
||||
return "quarterindex";
|
||||
case "semester":
|
||||
return "semesterindex";
|
||||
case "year":
|
||||
return "yearindex";
|
||||
case "decade":
|
||||
return "decadeindex";
|
||||
default:
|
||||
throw Error("todo");
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {"" |
|
||||
* "%all" |
|
||||
* "%cmcap" |
|
||||
* "%cp+l" |
|
||||
* "%mcap" |
|
||||
* "%pnl" |
|
||||
* "%rcap" |
|
||||
* "%self" |
|
||||
* "/sec" |
|
||||
* "address data" |
|
||||
* "block" |
|
||||
* "blocks" |
|
||||
* "bool" |
|
||||
* "btc" |
|
||||
* "bytes" |
|
||||
* "cents" |
|
||||
* "coinblocks" |
|
||||
* "coindays" |
|
||||
* "constant" |
|
||||
* "count" |
|
||||
* "date" |
|
||||
* "days" |
|
||||
* "difficulty" |
|
||||
* "epoch" |
|
||||
* "gigabytes" |
|
||||
* "h/s" |
|
||||
* "hash" |
|
||||
* "height" |
|
||||
* "id" |
|
||||
* "index" |
|
||||
* "len" |
|
||||
* "locktime" |
|
||||
* "percentage" |
|
||||
* "position" |
|
||||
* "ratio" |
|
||||
* "sat/vb" |
|
||||
* "satblocks" |
|
||||
* "satdays" |
|
||||
* "sats" |
|
||||
* "sats/(ph/s)/day" |
|
||||
* "sats/(th/s)/day" |
|
||||
* "sd" |
|
||||
* "secs" |
|
||||
* "timestamp" |
|
||||
* "tx" |
|
||||
* "type" |
|
||||
* "usd" |
|
||||
* "usd/(ph/s)/day" |
|
||||
* "usd/(th/s)/day" |
|
||||
* "vb" |
|
||||
* "version" |
|
||||
* "wu" |
|
||||
* "years" |
|
||||
* "" } Unit
|
||||
*/
|
||||
|
||||
export const serdeUnit = {
|
||||
/**
|
||||
* @param {string} v
|
||||
*/
|
||||
deserialize(v) {
|
||||
/** @type {Unit | undefined} */
|
||||
let unit;
|
||||
|
||||
/**
|
||||
* @param {Unit} u
|
||||
*/
|
||||
function setUnit(u) {
|
||||
if (unit)
|
||||
throw Error(
|
||||
`Can't assign "${u}" to unit, "${unit}" is already assigned to "${v}"`,
|
||||
);
|
||||
unit = u;
|
||||
}
|
||||
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v.includes("in_sats") ||
|
||||
v.endsWith("_sats") ||
|
||||
(v.endsWith("supply") &&
|
||||
!(v.endsWith("circulating_supply") || v.endsWith("_own_supply"))) ||
|
||||
v === "sent" ||
|
||||
v === "annualized_volume" ||
|
||||
v.endsWith("supply_half") ||
|
||||
v.endsWith("supply_in_profit") ||
|
||||
v.endsWith("supply_in_loss") ||
|
||||
v.endsWith("stack") ||
|
||||
(v.endsWith("value") && !v.includes("realized")) ||
|
||||
((v.includes("coinbase") ||
|
||||
v.includes("fee") ||
|
||||
v.includes("subsidy") ||
|
||||
v.includes("rewards")) &&
|
||||
!(
|
||||
v.startsWith("is_") ||
|
||||
v.includes("_btc") ||
|
||||
v.includes("_usd") ||
|
||||
v.includes("fee_rate") ||
|
||||
v.endsWith("dominance")
|
||||
)))
|
||||
) {
|
||||
setUnit("sats");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
!v.endsWith("velocity") &&
|
||||
((v.includes("_btc") &&
|
||||
!(v.includes("0k_btc") || v.includes("1k_btc"))) ||
|
||||
v.endsWith("_btc"))
|
||||
) {
|
||||
setUnit("btc");
|
||||
}
|
||||
if ((!unit || localhost) && v === "chain") {
|
||||
setUnit("block");
|
||||
}
|
||||
if ((!unit || localhost) && v.startsWith("blocks_before")) {
|
||||
setUnit("blocks");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v === "emptyaddressdata" || v === "loadedaddressdata")
|
||||
) {
|
||||
setUnit("address data");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v === "price_high" ||
|
||||
v === "price_ohlc" ||
|
||||
v === "price_low" ||
|
||||
v === "price_close" ||
|
||||
v === "price_open" ||
|
||||
v === "price_ath" ||
|
||||
v === "market_cap" ||
|
||||
v.startsWith("price_true_range") ||
|
||||
(v.includes("_usd") && !v.endsWith("velocity")) ||
|
||||
v.includes("cointime_value") ||
|
||||
v.endsWith("_ago") ||
|
||||
v.endsWith("price_paid") ||
|
||||
v.endsWith("_price") ||
|
||||
(v.startsWith("price") && (v.endsWith("min") || v.endsWith("max"))) ||
|
||||
(v.endsWith("_cap") && !v.includes("rel_to")) ||
|
||||
v.endsWith("value_created") ||
|
||||
v.endsWith("value_destroyed") ||
|
||||
((v.includes("realized") || v.includes("true_market_mean")) &&
|
||||
!v.includes("unrealized") &&
|
||||
!v.includes("ratio") &&
|
||||
!v.includes("rel_to")) ||
|
||||
(v.includes("unrealized") && !v.includes("rel_to")) ||
|
||||
((v.endsWith("sma") || v.includes("sma_x") || v.endsWith("ema")) &&
|
||||
!v.includes("ratio") &&
|
||||
!v.includes("sopr") &&
|
||||
!v.includes("hash_rate")) ||
|
||||
v === "ath")
|
||||
) {
|
||||
setUnit("usd");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("cents")) {
|
||||
setUnit("cents");
|
||||
}
|
||||
if (
|
||||
((!unit || localhost) &&
|
||||
(v.endsWith("ratio") ||
|
||||
(v.includes("ratio") &&
|
||||
(v.endsWith("sma") || v.endsWith("ema") || v.endsWith("zscore"))) ||
|
||||
v.includes("sopr") ||
|
||||
v.endsWith("_5sd") ||
|
||||
v.endsWith("1sd") ||
|
||||
v.endsWith("2sd") ||
|
||||
v.endsWith("3sd") ||
|
||||
v.endsWith("pct1") ||
|
||||
v.endsWith("pct2") ||
|
||||
v.endsWith("pct5") ||
|
||||
v.endsWith("pct95") ||
|
||||
v.endsWith("pct98") ||
|
||||
v.endsWith("pct99"))) ||
|
||||
v.includes("liveliness") ||
|
||||
v.includes("vaultedness") ||
|
||||
v == "puell_multiple" ||
|
||||
v.endsWith("velocity")
|
||||
) {
|
||||
setUnit("ratio");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v === "price_drawdown" ||
|
||||
v === "difficulty_adjustment" ||
|
||||
v.endsWith("inflation_rate") ||
|
||||
v.endsWith("_oscillator") ||
|
||||
v.endsWith("_dominance") ||
|
||||
v.endsWith("_returns") ||
|
||||
v.endsWith("_rebound") ||
|
||||
v.endsWith("_volatility") ||
|
||||
v.endsWith("_cagr"))
|
||||
) {
|
||||
setUnit("percentage");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v.endsWith("count") ||
|
||||
v.includes("_count_") ||
|
||||
v.startsWith("block_count") ||
|
||||
v.includes("blocks_mined") ||
|
||||
(v.includes("tx_v") && !v.includes("vsize")))
|
||||
) {
|
||||
setUnit("count");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v.startsWith("hash_rate") || v.endsWith("as_hash"))
|
||||
) {
|
||||
setUnit("h/s");
|
||||
}
|
||||
if ((!unit || localhost) && v === "pool") {
|
||||
setUnit("id");
|
||||
}
|
||||
if ((!unit || localhost) && v.includes("fee_rate")) {
|
||||
setUnit("sat/vb");
|
||||
}
|
||||
if ((!unit || localhost) && v.startsWith("is_")) {
|
||||
setUnit("bool");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("type")) {
|
||||
setUnit("type");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v === "interval" || v.startsWith("block_interval"))
|
||||
) {
|
||||
setUnit("secs");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("_per_sec")) {
|
||||
setUnit("/sec");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("locktime")) {
|
||||
setUnit("locktime");
|
||||
}
|
||||
|
||||
if ((!unit || localhost) && v.endsWith("version")) {
|
||||
setUnit("version");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v === "txid" ||
|
||||
(v.endsWith("bytes") && !v.endsWith("vbytes")) ||
|
||||
v.endsWith("base_size") ||
|
||||
v.endsWith("total_size") ||
|
||||
v.includes("block_size"))
|
||||
) {
|
||||
setUnit("bytes");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("_sd")) {
|
||||
setUnit("sd");
|
||||
}
|
||||
if ((!unit || localhost) && (v.includes("vsize") || v.includes("vbytes"))) {
|
||||
setUnit("vb");
|
||||
}
|
||||
if ((!unit || localhost) && v.includes("weight")) {
|
||||
setUnit("wu");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("index")) {
|
||||
setUnit("index");
|
||||
}
|
||||
if ((!unit || localhost) && (v === "date" || v === "date_fixed")) {
|
||||
setUnit("date");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v === "timestamp" || v === "timestamp_fixed")
|
||||
) {
|
||||
setUnit("timestamp");
|
||||
}
|
||||
if ((!unit || localhost) && v.includes("coinblocks")) {
|
||||
setUnit("coinblocks");
|
||||
}
|
||||
if ((!unit || localhost) && v.includes("coindays")) {
|
||||
setUnit("coindays");
|
||||
}
|
||||
if ((!unit || localhost) && v.includes("satblocks")) {
|
||||
setUnit("satblocks");
|
||||
}
|
||||
if ((!unit || localhost) && v.includes("satdays")) {
|
||||
setUnit("satdays");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("height")) {
|
||||
setUnit("height");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("rel_to_market_cap")) {
|
||||
setUnit("%mcap");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("rel_to_own_market_cap")) {
|
||||
setUnit("%cmcap");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("rel_to_own_total_unrealized_pnl")) {
|
||||
setUnit("%cp+l");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("rel_to_realized_cap")) {
|
||||
setUnit("%rcap");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("rel_to_circulating_supply")) {
|
||||
setUnit("%all");
|
||||
}
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v.includes("rel_to_realized_profit") ||
|
||||
v.includes("rel_to_realized_loss"))
|
||||
) {
|
||||
setUnit("%pnl");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("rel_to_own_supply")) {
|
||||
setUnit("%self");
|
||||
}
|
||||
if ((!unit || localhost) && v.endsWith("epoch")) {
|
||||
setUnit("epoch");
|
||||
}
|
||||
if ((!unit || localhost) && v === "difficulty") {
|
||||
setUnit("difficulty");
|
||||
}
|
||||
if ((!unit || localhost) && v === "blockhash") {
|
||||
setUnit("hash");
|
||||
}
|
||||
if ((!unit || localhost) && v.startsWith("hash_price_phs")) {
|
||||
setUnit("usd/(ph/s)/day");
|
||||
}
|
||||
if ((!unit || localhost) && v.startsWith("hash_price_ths")) {
|
||||
setUnit("usd/(th/s)/day");
|
||||
}
|
||||
if ((!unit || localhost) && v.startsWith("hash_value_phs")) {
|
||||
setUnit("sats/(ph/s)/day");
|
||||
}
|
||||
if ((!unit || localhost) && v.startsWith("hash_value_ths")) {
|
||||
setUnit("sats/(th/s)/day");
|
||||
}
|
||||
|
||||
if (
|
||||
(!unit || localhost) &&
|
||||
(v.includes("days_between") ||
|
||||
v.includes("days_since") ||
|
||||
v.startsWith("days_before"))
|
||||
) {
|
||||
setUnit("days");
|
||||
}
|
||||
if ((!unit || localhost) && v.includes("years_between")) {
|
||||
setUnit("years");
|
||||
}
|
||||
if ((!unit || localhost) && v == "len") {
|
||||
setUnit("len");
|
||||
}
|
||||
if ((!unit || localhost) && v == "position") {
|
||||
setUnit("position");
|
||||
}
|
||||
if ((!unit || localhost) && v.startsWith("constant")) {
|
||||
setUnit("constant");
|
||||
}
|
||||
|
||||
if (!unit) {
|
||||
console.log();
|
||||
throw Error(`Unit not set for "${v}"`);
|
||||
}
|
||||
|
||||
return /** @type {Unit} */ (unit);
|
||||
},
|
||||
};
|
||||
51
websites/bitview/scripts/utils/storage.js
Normal file
51
websites/bitview/scripts/utils/storage.js
Normal file
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* @param {string} key
|
||||
*/
|
||||
export function readStoredNumber(key) {
|
||||
const saved = readStored(key);
|
||||
if (saved) {
|
||||
return Number(saved);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
*/
|
||||
export function readStoredBool(key) {
|
||||
const saved = readStored(key);
|
||||
if (saved) {
|
||||
return saved === "true" || saved === "1";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
*/
|
||||
export function readStored(key) {
|
||||
try {
|
||||
return localStorage.getItem(key);
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
* @param {string | boolean | null | undefined} value
|
||||
*/
|
||||
export function writeToStorage(key, value) {
|
||||
try {
|
||||
value !== undefined && value !== null
|
||||
? localStorage.setItem(key, String(value))
|
||||
: localStorage.removeItem(key);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
*/
|
||||
export function removeStored(key) {
|
||||
writeToStorage(key, undefined);
|
||||
}
|
||||
38
websites/bitview/scripts/utils/timing.js
Normal file
38
websites/bitview/scripts/utils/timing.js
Normal file
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* @param {number} ms
|
||||
*/
|
||||
export function sleep(ms) {
|
||||
return new Promise((resolve) => {
|
||||
setTimeout(resolve, ms);
|
||||
});
|
||||
}
|
||||
|
||||
export function next() {
|
||||
return sleep(0);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @template {(...args: any[]) => any} F
|
||||
* @param {F} callback
|
||||
* @param {number} [wait]
|
||||
*/
|
||||
export function throttle(callback, wait = 1000) {
|
||||
/** @type {number | null} */
|
||||
let timeoutId = null;
|
||||
/** @type {Parameters<F>} */
|
||||
let latestArgs;
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
}
|
||||
107
websites/bitview/scripts/utils/url.js
Normal file
107
websites/bitview/scripts/utils/url.js
Normal file
@@ -0,0 +1,107 @@
|
||||
/**
|
||||
* @param {string | string[]} [pathname]
|
||||
*/
|
||||
function processPathname(pathname) {
|
||||
pathname ||= window.location.pathname;
|
||||
return Array.isArray(pathname) ? pathname.join("/") : pathname;
|
||||
}
|
||||
|
||||
const chartParamsWhitelist = ["from", "to"];
|
||||
|
||||
/**
|
||||
* @param {string | string[]} pathname
|
||||
*/
|
||||
export function pushHistory(pathname) {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
pathname = processPathname(pathname);
|
||||
try {
|
||||
const url = `/${pathname}?${urlParams.toString()}`;
|
||||
console.log(`push history: ${url}`);
|
||||
window.history.pushState(null, "", url);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} args
|
||||
* @param {URLSearchParams} [args.urlParams]
|
||||
* @param {string | string[]} [args.pathname]
|
||||
*/
|
||||
export function replaceHistory({ urlParams, pathname }) {
|
||||
urlParams ||= new URLSearchParams(window.location.search);
|
||||
pathname = processPathname(pathname);
|
||||
try {
|
||||
const url = `/${pathname}?${urlParams.toString()}`;
|
||||
console.log(`replace history: ${url}`);
|
||||
window.history.replaceState(null, "", url);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Option} option
|
||||
*/
|
||||
export function resetParams(option) {
|
||||
const urlParams = new URLSearchParams();
|
||||
if (option.kind === "chart") {
|
||||
[...new URLSearchParams(window.location.search).entries()]
|
||||
.filter(([key, _]) => chartParamsWhitelist.includes(key))
|
||||
.forEach(([key, value]) => {
|
||||
urlParams.set(key, value);
|
||||
});
|
||||
}
|
||||
replaceHistory({ urlParams, pathname: option.path.join("/") });
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
* @param {string | boolean | null | undefined} value
|
||||
*/
|
||||
export function writeParam(key, value) {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
|
||||
if (value !== null && value !== undefined) {
|
||||
urlParams.set(key, String(value));
|
||||
} else {
|
||||
urlParams.delete(key);
|
||||
}
|
||||
|
||||
replaceHistory({ urlParams });
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
*/
|
||||
export function removeParam(key) {
|
||||
writeParam(key, undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
*/
|
||||
export function readBoolParam(key) {
|
||||
const param = readParam(key);
|
||||
if (param) {
|
||||
return param === "true" || param === "1";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} key
|
||||
*/
|
||||
export function readNumberParam(key) {
|
||||
const param = readParam(key);
|
||||
if (param) {
|
||||
return Number(param);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} key
|
||||
* @returns {string | null}
|
||||
*/
|
||||
export function readParam(key) {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
return params.get(key);
|
||||
}
|
||||
128
websites/bitview/scripts/utils/ws.js
Normal file
128
websites/bitview/scripts/utils/ws.js
Normal file
@@ -0,0 +1,128 @@
|
||||
/**
|
||||
* @param {Signals} signals
|
||||
*/
|
||||
export function createWebSockets(signals) {
|
||||
/**
|
||||
* @template T
|
||||
* @param {(callback: (value: T) => void) => WebSocket} creator
|
||||
*/
|
||||
function createWebsocket(creator) {
|
||||
let ws = /** @type {WebSocket | null} */ (null);
|
||||
|
||||
const live = signals.createSignal(false);
|
||||
const latest = signals.createSignal(/** @type {T | null} */ (null));
|
||||
|
||||
function reinitWebSocket() {
|
||||
if (!ws || ws.readyState === ws.CLOSED) {
|
||||
console.log("ws: reinit");
|
||||
resource.open();
|
||||
}
|
||||
}
|
||||
|
||||
function reinitWebSocketIfDocumentNotHidden() {
|
||||
!window.document.hidden && reinitWebSocket();
|
||||
}
|
||||
|
||||
const resource = {
|
||||
live,
|
||||
latest,
|
||||
open() {
|
||||
ws = creator((value) => latest.set(() => value));
|
||||
|
||||
ws.addEventListener("open", () => {
|
||||
console.log("ws: open");
|
||||
live.set(true);
|
||||
});
|
||||
|
||||
ws.addEventListener("close", () => {
|
||||
console.log("ws: close");
|
||||
live.set(false);
|
||||
});
|
||||
|
||||
window.document.addEventListener(
|
||||
"visibilitychange",
|
||||
reinitWebSocketIfDocumentNotHidden,
|
||||
);
|
||||
|
||||
window.document.addEventListener("online", reinitWebSocket);
|
||||
},
|
||||
close() {
|
||||
ws?.close();
|
||||
window.document.removeEventListener(
|
||||
"visibilitychange",
|
||||
reinitWebSocketIfDocumentNotHidden,
|
||||
);
|
||||
window.document.removeEventListener("online", reinitWebSocket);
|
||||
live.set(false);
|
||||
ws = null;
|
||||
},
|
||||
};
|
||||
|
||||
return resource;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {(candle: CandlestickData) => void} callback
|
||||
*/
|
||||
function krakenCandleWebSocketCreator(callback) {
|
||||
const ws = new WebSocket("wss://ws.kraken.com/v2");
|
||||
|
||||
ws.addEventListener("open", () => {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
method: "subscribe",
|
||||
params: {
|
||||
channel: "ohlc",
|
||||
symbol: ["BTC/USD"],
|
||||
interval: 1440,
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
ws.addEventListener("message", (message) => {
|
||||
const result = JSON.parse(message.data);
|
||||
|
||||
if (result.channel !== "ohlc") return;
|
||||
|
||||
const { interval_begin, open, high, low, close } = result.data.at(-1);
|
||||
|
||||
/** @type {CandlestickData} */
|
||||
const candle = {
|
||||
// index: -1,
|
||||
time: new Date(interval_begin).valueOf() / 1000,
|
||||
open: Number(open),
|
||||
high: Number(high),
|
||||
low: Number(low),
|
||||
close: Number(close),
|
||||
};
|
||||
|
||||
candle && callback({ ...candle });
|
||||
});
|
||||
|
||||
return ws;
|
||||
}
|
||||
|
||||
/** @type {ReturnType<typeof createWebsocket<CandlestickData>>} */
|
||||
const kraken1dCandle = createWebsocket((callback) =>
|
||||
krakenCandleWebSocketCreator(callback),
|
||||
);
|
||||
|
||||
kraken1dCandle.open();
|
||||
|
||||
signals.createEffect(kraken1dCandle.latest, (latest) => {
|
||||
if (latest) {
|
||||
const close = latest.close;
|
||||
console.log("close:", close);
|
||||
|
||||
window.document.title = `${latest.close.toLocaleString("en-us")} | ${
|
||||
window.location.host
|
||||
}`;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
kraken1dCandle,
|
||||
};
|
||||
}
|
||||
/** @typedef {ReturnType<typeof createWebSockets>} WebSockets */
|
||||
Reference in New Issue
Block a user