general: snapshot

This commit is contained in:
nym21
2025-02-19 21:43:18 +01:00
parent 2cb4d65f3d
commit 5e39510f21
150 changed files with 188 additions and 972 deletions

View File

@@ -0,0 +1,57 @@
Fontshare EULA
---—---------------------------------—------------------------------
Free Font - End User License Agreement (FF EULA)
---—---------------------------------—------------------------------
Notice to User
Indian Type Foundry designs, produces and distributes font software as digital fonts to end users worldwide. In addition to commercial fonts that are available for a fee, ITF also offers several fonts which can be used free of charge. The free fonts are distributed through a dedicated platform called www.fontshare.com (“Fontshare”) to end users worldwide. These free fonts are subject to this legally binding EULA between the Indian Type Foundry (“Indian Type Foundry” or “Licensor”) and you (“Licensee”). 
You acknowledge that the Font Software and designs embodied therein are protected by the copyright, other intellectual property rights and industrial property rights and by international treaties. They are and remain at all times the intellectual property of the Indian Type Foundry.
In addition to direct download, Fontshare also offers these free fonts via Fonthsare API using a code. In this case, the Font Software is delivered directly from the servers used by Indian Type Foundry to the Licensee's website, without the Licensee having to download the Font Software.
By downloading, accessing the API, installing, storing, copying or using one of any Font Software, you agree to the following terms. 
Definitions
“Font Software” refers to the set of computer files or programs released under this license that instructs your computer to display and/or print each letters, characters, typographic designs, ornament and so forth. Font Software includes all bitmap and vector representations of fonts and typographic representations and embellishments created by or derived from the Font Software. 
“Original Version” refers to the Font Software as distributed by the Indian Type Foundry as the copyright holder. 
“Derivative Work” refers to the pictorial representation of the font created by the Font Software, including typographic characters such as letters, numerals, ornaments, symbols, or punctuation and special characters.
01. Grant of License
You are hereby granted a non-exclusive, non-assignable, non-transferrable, terminable license to access, download and use the Font Software for your personal or commercial use for an unlimited period of time for free of charge. 
You may use the font Software in any media (including Print, Web, Mobile, Digital, Apps, ePub, Broadcasting and OEM) at any scale, at any location worldwide. 
You may use the Font Software to create logos and other graphic elements, images on any surface, vector files or other scalable drawings and static images. 
You may use the Font Software on any number of devices (computer, tablet, phone). The number of output devices (Printers) is not restricted. 
You may make only such reasonable number of back-up copies suitable to your permitted use. 
You may but are not required to identify Indian Type Foundry Fonts in your work credits. 
02. Limitations of usage
You may not modify, edit, adapt, translate, reverse engineer, decompile or disassemble, alter or otherwise copy the Font Software or the designs embodied therein in whole or in part, without the prior written consent of the Licensor. 
The Fonts may not - beyond the permitted copies and the uses defined herein - be distributed, duplicated, loaned, resold or licensed in any way, whether by lending, donating or give otherwise to a person or entity. This includes the distribution of the Fonts by e-mail, on USB sticks, CD-ROMs, or other media, uploading them in a public server or making the fonts available on peer-to-peer networks. A passing on to external designers or service providers (design agencies, repro studios, printers, etc.) is also not permitted. 
You are not allowed to transmit the Font Software over the Internet in font serving or for font replacement by means of technologies such as but not limited to EOT, Cufon, sIFR or similar technologies that may be developed in the future without the prior written consent of the Licensor. 
03. Embedding
You may embed the Font Software in PDF and other digital documents provided that is done in a secured, read-only mode. It must be ensured beyond doubt that the recipient cannot use the Font Software to edit or to create new documents. The design data (PDFs) created in this way and under these created design data (PDFs) may be distributed in any number. 
The extraction of the Font Software in whole or in part is prohibited. 
04. Third party use, Commercial print service provider
You may include the Font Software in a non-editable electronic document solely for printing and display purposes and provide that electronic document to the commercial print service provider for the purpose of printing. If the print service needs to install the fonts, they too need to download the Font Software from the Licensor's website.
05. Derivative Work
You are allowed to make derivative works as far as you use them for your personal or commercial use. However, you cannot modify, make changes or reverse engineer the original font software provided to you. Any derivative works are the exclusive property of the Licensor and shall be subject to the terms and conditions of this EULA. Derivative works may not be sub-licensed, sold, leased, rented, loaned, or given away without the express written permission of the Licensor. 
06. Warranty and Liability
BECAUSE THIS SOFTWARE IS LICENSED FREE OF CHARGE, INDIAN TYPE FOUNDRY MAKES NO WARRANTIES, EXPRESS OR IMPLIED AS TO THE MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR OTHERWISE. THE FONT SOFTWARE WAS NOT MANUFACTURED FOR USE IN MANUFACTURING CONTROL DEVICES OR NAVIGATION DEVICES OR IN CIRCUMSTANCES THAT COULD RESULT IN ENVIRONMENTAL DAMAGE OR PERSONAL INJURY. WITHOUT LIMITING THE FOREGOING, INDIAN TYPE FOUNDRY SHALL IN NO EVENT BE LIABLE TO THE LICENSED USER OR ANY OTHER THIRD PARTY FOR ANY DIRECT, CONSEQUENTIAL OR INCIDENTAL DAMAGES, INCLUDING DAMAGES FROM LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS INFORMATION NOR FOR LOST PROFITS OR SAVINGS ARISING OUT OF THE USE OR INABILITY TO USE THE PRODUCT EVEN IF NOTIFIED IN ADVANCE, UNDER NO CIRCUMSTANCES SHALL INDIAN TYPE FOUNDRYS LIABILITY EXCEED THE REPLACEMENT COST OF THE SOFTWARE. 
IF LICENSEE CHOOSES TO ACCESS THE FONT SOFTWARE THROUGH A CODE (API), IT MAY HAVE A DIRECT IMPACT ON LICENSEE'S WEBSITE OR APPLICATIONS. INDIAN TYPE FOUNDRY IS NOT RESPONSIBLE OR LIABLE FOR ANY INTERRUPTION, MALFUNCTION, DOWNTIME OR OTHER FAILURE OF THE WEBSITE OR ITS API.
07. Updates, Maintenance and Support Services
Licensor will not provide you with any support services for the Software under this Agreement.
08. Termination 
Any breach of the terms of this agreement shall be a cause for termination, provided that such breach is notified in writing to the Licensee by the Licensor and the Licensee failed to rectify the breach within 30 days of the receipt of such notification. 
In the event of termination and without limitation of any remedies under law or equity, you must delete the Font Software and all copies thereof. Proof of this must be provided upon request of the Licensor.  
We reserve the right to claim damages for the violation of the conditions. 
09. Final Provisions
If individual provisions of this agreement are or become invalid, the validity of the remaining provisions shall remain unaffected. Invalid provisions shall be replaced by mutual agreement by such provisions that are suitable to achieve the desired economic purpose, taking into account the interests of both parties. The same shall apply mutatis mutandis to the filling of any gaps which may arise in this agreement.
This contract is subject to laws of the Republic of India. Place of performance and exclusive place of jurisdiction for all disputes between the parties arising out of or in connection with this contract is, as far as legally permissible, Ahmedabad, India.
- 
Last Updated on 22 March 2021
Copyright 2021 Indian Type Foundry. All rights reserved. 

Binary file not shown.

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 146 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 59 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 78 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 240 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 279 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 288 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 250 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 408 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 286 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 243 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 281 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 288 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 145 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 157 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 175 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 407 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 60 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 79 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 96 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.9 KiB

View File

@@ -0,0 +1,44 @@
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/png" sizes="196x196" href="/assets/pwa/2024-11-20_09-41-25/favicon-196.png">
<link rel="apple-touch-icon" href="/assets/pwa/2024-11-20_09-41-25/apple-icon-180.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2048-2732.jpg" media="(device-width: 1024px) and (device-height: 1366px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2732-2048.jpg" media="(device-width: 1024px) and (device-height: 1366px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1668-2388.jpg" media="(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2388-1668.jpg" media="(device-width: 834px) and (device-height: 1194px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1536-2048.jpg" media="(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2048-1536.jpg" media="(device-width: 768px) and (device-height: 1024px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1488-2266.jpg" media="(device-width: 744px) and (device-height: 1133px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2266-1488.jpg" media="(device-width: 744px) and (device-height: 1133px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1640-2360.jpg" media="(device-width: 820px) and (device-height: 1180px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2360-1640.jpg" media="(device-width: 820px) and (device-height: 1180px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1668-2224.jpg" media="(device-width: 834px) and (device-height: 1112px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2224-1668.jpg" media="(device-width: 834px) and (device-height: 1112px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1620-2160.jpg" media="(device-width: 810px) and (device-height: 1080px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2160-1620.jpg" media="(device-width: 810px) and (device-height: 1080px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1290-2796.jpg" media="(device-width: 430px) and (device-height: 932px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2796-1290.jpg" media="(device-width: 430px) and (device-height: 932px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1179-2556.jpg" media="(device-width: 393px) and (device-height: 852px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2556-1179.jpg" media="(device-width: 393px) and (device-height: 852px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1284-2778.jpg" media="(device-width: 428px) and (device-height: 926px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2778-1284.jpg" media="(device-width: 428px) and (device-height: 926px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1170-2532.jpg" media="(device-width: 390px) and (device-height: 844px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2532-1170.jpg" media="(device-width: 390px) and (device-height: 844px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1125-2436.jpg" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2436-1125.jpg" media="(device-width: 375px) and (device-height: 812px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1242-2688.jpg" media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2688-1242.jpg" media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-828-1792.jpg" media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1792-828.jpg" media="(device-width: 414px) and (device-height: 896px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1242-2208.jpg" media="(device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio: 3) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-2208-1242.jpg" media="(device-width: 414px) and (device-height: 736px) and (-webkit-device-pixel-ratio: 3) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-750-1334.jpg" media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1334-750.jpg" media="(device-width: 375px) and (device-height: 667px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-640-1136.jpg" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2) and (orientation: portrait)">
<link rel="apple-touch-startup-image" href="/assets/pwa/2024-11-20_09-41-25/apple-splash-1136-640.jpg" media="(device-width: 320px) and (device-height: 568px) and (-webkit-device-pixel-ratio: 2) and (orientation: landscape)">
</head>
<body>
</body>
</html>

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -0,0 +1,5 @@
<!doctype html>
<html lang="en">
<head></head>
<body></body>
</html>

View File

@@ -0,0 +1,33 @@
#!/usr/bin/env bash
DATE=$(date -u '+%Y-%m-%d_%H-%M-%S')
OUTPUT="/assets/pwa/${DATE}"
mkdir ".${OUTPUT}"
cp "./assets/pwa/index.html" ".${OUTPUT}/"
pwa-asset-generator "../assets/dove-orange.svg" ".${OUTPUT}" \
--index ".${OUTPUT}/index.html" \
--manifest "./manifest.webmanifest" \
--favicon \
--padding "0%" \
--path-override "${OUTPUT}" \
--quality "100" \
--opaque "false"
pwa-asset-generator "../assets/dove-white.svg" ".${OUTPUT}" \
--index ".${OUTPUT}/index.html" \
--manifest "./manifest.webmanifest" \
--icon-only \
--background "#f26610" \
--padding "10%" \
--path-override "${OUTPUT}" \
--quality "100"
pwa-asset-generator "../assets/logo-stamp-orange.svg" ".${OUTPUT}" \
--index ".${OUTPUT}/index.html" \
--splash-only \
--background "#f26610" \
--padding "min(30vh, 30vw)" \
--path-override "${OUTPUT}" \
--quality "100"

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,9 @@
{
"compilerOptions": {
"checkJs": true,
"strict": true,
"target": "ESNext",
"module": "ESNext"
},
"exclude": ["assets", "packages", "ignore"]
}

View File

@@ -0,0 +1,43 @@
{
"name": "kibō",
"short_name": "kibō",
"description": "A better, FOSS, Bitcoin-only, self-hostable Glassnode",
"categories": [
"bitcoin",
"on-chain",
"data"
],
"start_url": "/",
"scope": "/",
"display": "standalone",
"handle_links": "preferred",
"theme_color": "#f26610",
"background_color": "#f26610",
"lang": "en",
"icons": [
{
"src": "/assets/pwa/2024-11-20_09-41-25/manifest-icon-192.maskable.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
},
{
"src": "/assets/pwa/2024-11-20_09-41-25/manifest-icon-192.maskable.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/assets/pwa/2024-11-20_09-41-25/manifest-icon-512.maskable.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/assets/pwa/2024-11-20_09-41-25/manifest-icon-512.maskable.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
]
}

View File

@@ -0,0 +1,46 @@
(async () => {
const theme = await (
await fetch(
"https://raw.githubusercontent.com/tailwindlabs/tailwindcss/refs/heads/next/packages/tailwindcss/theme.css",
)
).text();
console.log(
[
"red",
"orange",
"amber",
"yellow",
"lime",
"green",
"emerald",
"teal",
"cyan",
"sky",
"blue",
"indigo",
"violet",
"purple",
"fuchsia",
"pink",
"rose",
]
.map((color) => {
const [a, b] = [500, 600].map((shade) => {
const regExp = new RegExp(
`(?<=${`${color}-${shade}: oklch\(`})(.*?)(?=\\s*${`\);`})`,
"g",
);
let res = regExp.exec(theme)?.[2];
if (!res) throw "err";
res = res.replace("(", "");
res = res.replace(")", "");
// return res
return res.split(" ").map((s) => Number(s));
});
const mult = 10_000;
return `--${color}: oklch(${[0, 1, 2].map((i) => Math.round(((a[i] + b[i]) / 2) * mult) / mult).join(" ")})`;
})
.join(";\n"),
);
})();

View File

@@ -0,0 +1,3 @@
URL + Version:
https://unpkg.com/browse/lean-qr@latest/

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,241 @@
declare module "lean-qr" {
interface ImageDataLike {
readonly data: Uint8ClampedArray;
}
interface Context2DLike<DataT extends ImageDataLike> {
createImageData(width: number, height: number): DataT;
putImageData(data: DataT, x: number, y: number): void;
}
interface CanvasLike<DataT extends ImageDataLike> {
width: number;
height: number;
getContext(type: "2d"): Context2DLike<DataT> | null;
}
export type RGBA = readonly [number, number, number, number?];
export interface Bitmap1D {
push(value: number, bits: number): void;
}
export interface StringOptions {
on?: string;
off?: string;
lf?: string;
padX?: number;
padY?: number;
}
export interface ImageDataOptions {
on?: RGBA;
off?: RGBA;
padX?: number;
padY?: number;
}
export interface Bitmap2D {
readonly size: number;
get(x: number, y: number): boolean;
toString(options?: Readonly<StringOptions>): string;
toImageData<DataT extends ImageDataLike>(
context: Context2DLike<DataT>,
options?: Readonly<ImageDataOptions>,
): DataT;
toDataURL(
options?: Readonly<
ImageDataOptions & {
type?: `image/${string}`;
scale?: number;
}
>,
): string;
toCanvas(
canvas: CanvasLike<ImageDataLike>,
options?: Readonly<ImageDataOptions>,
): void;
}
export type Mask = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
export type Mode = (data: Bitmap1D, version: number) => void;
export interface ModeFactory {
(value: string): Mode;
test(string: string): boolean;
est(value: string, version: number): number;
eci?: number;
}
interface ModeAutoOptions {
modes?: ReadonlyArray<ModeFactory>;
}
export const mode: Readonly<{
auto(value: string, options?: Readonly<ModeAutoOptions>): Mode;
multi(...modes: ReadonlyArray<Mode>): Mode;
eci(id: number): Mode;
numeric: ModeFactory;
alphaNumeric: ModeFactory;
bytes(data: Uint8Array | ReadonlyArray<number>): Mode;
ascii: ModeFactory;
iso8859_1: ModeFactory;
shift_jis: ModeFactory;
utf8: ModeFactory;
}>;
type Correction = number & { readonly _: unique symbol };
export const correction: Readonly<{
min: Correction;
L: Correction;
M: Correction;
Q: Correction;
H: Correction;
max: Correction;
}>;
export interface GenerateOptions extends ModeAutoOptions {
minCorrectionLevel?: Correction;
maxCorrectionLevel?: Correction;
minVersion?: number;
maxVersion?: number;
mask?: null | Mask;
trailer?: number;
}
export type GenerateFn = (
data: Mode | string,
options?: Readonly<GenerateOptions>,
) => Bitmap2D;
interface Generate extends GenerateFn {
with(...modes: ReadonlyArray<ModeFactory>): GenerateFn;
}
export const generate: Generate;
}
declare module "lean-qr/extras/svg" {
import type { Bitmap2D } from "lean-qr";
export interface SVGOptions {
on?: string;
off?: string;
padX?: number;
padY?: number;
width?: number | null;
height?: number | null;
scale?: number;
}
export const toSvgPath: (code: Bitmap2D) => string;
export const toSvg: (
code: Bitmap2D,
target: Document | SVGElement,
options?: Readonly<SVGOptions>,
) => SVGElement;
export const toSvgSource: (
code: Bitmap2D,
options?: Readonly<SVGOptions & { xmlDeclaration?: boolean }>,
) => string;
export type toSvgDataURLFn = (
code: Bitmap2D,
options?: Readonly<SVGOptions>,
) => string;
export const toSvgDataURL: toSvgDataURLFn;
}
declare module "lean-qr/extras/node_export" {
import type { RGBA, Bitmap2D } from "lean-qr";
export interface PNGOptions {
on?: RGBA;
off?: RGBA;
padX?: number;
padY?: number;
scale?: number;
}
export const toPngBuffer: (
code: Bitmap2D,
options?: Readonly<PNGOptions>,
) => Uint8Array;
export const toPngDataURL: (
code: Bitmap2D,
options?: Readonly<PNGOptions>,
) => string;
}
declare module "lean-qr/extras/react" {
import type { ImageDataOptions, GenerateOptions, GenerateFn } from "lean-qr";
import type { SVGOptions, toSvgDataURLFn } from "lean-qr/extras/svg";
export interface AsyncFramework<T> {
createElement: (
type: "canvas",
props: {
ref: any;
style: { imageRendering: "pixelated" };
className: string;
},
) => T;
useRef<T>(initialValue: T | null): { readonly current: T | null };
useEffect(fn: () => void | (() => void), deps: unknown[]): void;
}
interface QRComponentProps {
content: string;
className?: string;
}
export interface AsyncQRComponentProps
extends ImageDataOptions,
GenerateOptions,
QRComponentProps {}
export type AsyncQRComponent<T> = (
props: Readonly<AsyncQRComponentProps>,
) => T;
export const makeAsyncComponent: <T>(
framework: Readonly<AsyncFramework<T>>,
generate: GenerateFn,
defaultProps?: Readonly<Partial<AsyncQRComponentProps>>,
) => AsyncQRComponent<T>;
export interface SyncFramework<T> {
createElement: (
type: "img",
props: {
src: string;
style: { imageRendering: "pixelated" };
className: string;
},
) => T;
useMemo<T>(fn: () => T, deps: unknown[]): T;
}
export interface SyncQRComponentProps
extends SVGOptions,
GenerateOptions,
QRComponentProps {}
export type SyncQRComponent<T> = (props: Readonly<SyncQRComponentProps>) => T;
export const makeSyncComponent: <T>(
framework: Readonly<SyncFramework<T>>,
generate: GenerateFn,
toSvgDataURL: toSvgDataURLFn,
defaultProps?: Readonly<Partial<SyncQRComponentProps>>,
) => SyncQRComponent<T>;
}
declare module "lean-qr/extras/errors" {
export const readError: (error: unknown) => string;
}

View File

@@ -0,0 +1,2 @@
TradingView Lightweight Charts™
Copyright (с) 2023 TradingView, Inc. https://www.tradingview.com/

View File

@@ -0,0 +1,3 @@
URL + Version:
https://unpkg.com/browse/lightweight-charts@latest/

View File

@@ -0,0 +1,124 @@
import { Signal } from "../solid-signals/types";
import { Accessor } from "../solid-signals/2024-11-02/types/signals";
import {
DeepPartial,
BaselineStyleOptions,
CandlestickStyleOptions,
LineStyleOptions,
SeriesOptionsCommon,
Time,
CandlestickData,
ISeriesApi,
BaselineData,
} from "./v4.2.2/types";
import { Color, Valued, ValuedCandlestickData } from "../../scripts/types/self";
interface BaseSeriesBlueprint {
title: string;
defaultActive?: boolean;
}
interface BaselineSeriesBlueprint extends BaseSeriesBlueprint {
type: "Baseline";
color?: Color;
options?: DeepPartial<BaselineStyleOptions & SeriesOptionsCommon>;
data?: Accessor<BaselineData<Time>[]>;
}
interface CandlestickSeriesBlueprint extends BaseSeriesBlueprint {
type: "Candlestick";
color?: Color;
options?: DeepPartial<CandlestickStyleOptions & SeriesOptionsCommon>;
data?: Accessor<(CandlestickData<Time> & Valued)[]>;
}
interface LineSeriesBlueprint extends BaseSeriesBlueprint {
type?: "Line";
color: Color;
options?: DeepPartial<LineStyleOptions & SeriesOptionsCommon>;
data?: Accessor<LineData<Time>[]>;
}
type AnySpecificSeriesBlueprint =
| BaselineSeriesBlueprint
| CandlestickSeriesBlueprint
| LineSeriesBlueprint;
type SeriesType = NonNullable<AnySpecificSeriesBlueprint["type"]>;
type PriceSeriesType = "Candlestick" | "Line";
type RemoveSeriesBlueprintFluff<Blueprint extends AnySpecificSeriesBlueprint> =
Omit<Blueprint, "type" | "title">;
type SplitSeriesBlueprint = {
datasetPath: AnyDatasetPath;
main?: boolean;
} & AnySpecificSeriesBlueprint;
type SingleSeriesBlueprint = AnySpecificSeriesBlueprint;
interface CreateBaseSeriesParameters extends BaseSeriesBlueprint {
id: string;
disabled?: Accessor<boolean>;
color?: Color;
}
interface BaseSeries {
id: string;
title: string;
color: Color | Color[];
active: Signal<boolean>;
visible: Accessor<boolean>;
disabled: Accessor<boolean>;
}
interface SingleSeries extends BaseSeries {
iseries: ISeriesApi<any>;
dataset: Accessor<(SingleValueData | ValuedCandlestickData)[] | null>;
}
interface SplitSeries extends BaseSeries {
chunks: Array<Accessor<ISeriesApi<SeriesType> | undefined>>;
dataset: ResourceDataset<TimeScale, number>;
}
type AnySeries = SingleSeries | SplitSeries;
interface CreateSingleSeriesParameters {
blueprint: SingleSeriesBlueprint;
id: string;
}
interface CreateSplitSeriesParameters<S extends TimeScale> {
dataset: ResourceDataset<S>;
blueprint: SplitSeriesBlueprint;
id: string;
index: number;
disabled?: Accessor<boolean>;
}
type ChartPane = IChartApi & {
whitespace: ISeriesApi<"Line">;
hidden: () => boolean;
setHidden: (b: boolean) => void;
setInitialVisibleTimeRange: VoidFunction;
createSingleSeries: (a: CreateSingleSeriesParameters) => SingleSeries;
createSplitSeries: <S extends TimeScale>(
a: CreateSplitSeriesParameters<S>,
) => SplitSeries[];
anySeries: AnySeries[];
singleSeries: SingleSeries[];
splitSeries: SplitSeries[];
remove: VoidFunction;
};
interface CreatePaneParameters {
unit: Unit;
paneIndex?: number;
options?: DeepPartial<ChartOptions>;
config?: SingleSeriesBlueprint[];
}
interface Marker {
weight: number;
time: Time;
value: number;
seriesChunk: ISeriesApi<any>;
}
interface HoveredLegend {
label: HTMLLabelElement;
series: AnySeries;
}

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,790 @@
// src/core/error.ts
var NotReadyError = class extends Error {
};
var NoOwnerError = class extends Error {
constructor() {
super(
""
);
}
};
var ContextNotFoundError = class extends Error {
constructor() {
super(
""
);
}
};
// src/utils.ts
function isUndefined(value) {
return typeof value === "undefined";
}
// src/core/constants.ts
var STATE_CLEAN = 0;
var STATE_CHECK = 1;
var STATE_DIRTY = 2;
var STATE_DISPOSED = 3;
// src/core/owner.ts
var currentOwner = null;
var defaultContext = {};
function getOwner() {
return currentOwner;
}
function setOwner(owner) {
const out = currentOwner;
currentOwner = owner;
return out;
}
var Owner = class {
// We flatten the owner tree into a linked list so that we don't need a pointer to .firstChild
// However, the children are actually added in reverse creation order
// See comment at the top of the file for an example of the _nextSibling traversal
l = null;
g = null;
j = null;
a = STATE_CLEAN;
e = null;
h = defaultContext;
f = null;
constructor(signal = false) {
if (currentOwner && !signal)
currentOwner.append(this);
}
append(child) {
child.l = this;
child.j = this;
if (this.g)
this.g.j = child;
child.g = this.g;
this.g = child;
if (child.h !== this.h) {
child.h = { ...this.h, ...child.h };
}
if (this.f) {
child.f = !child.f ? this.f : [...child.f, ...this.f];
}
}
dispose(self = true) {
if (this.a === STATE_DISPOSED)
return;
let head = self ? this.j || this.l : this, current = this.g, next = null;
while (current && current.l === this) {
current.dispose(true);
current.n();
next = current.g;
current.g = null;
current = next;
}
if (self)
this.n();
if (current)
current.j = !self ? this : this.j;
if (head)
head.g = current;
}
n() {
if (this.j)
this.j.g = null;
this.l = null;
this.j = null;
this.h = defaultContext;
this.f = null;
this.a = STATE_DISPOSED;
this.emptyDisposal();
}
emptyDisposal() {
if (!this.e)
return;
if (Array.isArray(this.e)) {
for (let i = 0; i < this.e.length; i++) {
const callable = this.e[i];
callable.call(callable);
}
} else {
this.e.call(this.e);
}
this.e = null;
}
handleError(error) {
if (!this.f)
throw error;
let i = 0, len = this.f.length;
for (i = 0; i < len; i++) {
try {
this.f[i](error);
break;
} catch (e) {
error = e;
}
}
if (i === len)
throw error;
}
};
function createContext(defaultValue, description) {
return { id: Symbol(description), defaultValue };
}
function getContext(context, owner = currentOwner) {
if (!owner) {
throw new NoOwnerError();
}
const value = hasContext(context, owner) ? owner.h[context.id] : context.defaultValue;
if (isUndefined(value)) {
throw new ContextNotFoundError();
}
return value;
}
function setContext(context, value, owner = currentOwner) {
if (!owner) {
throw new NoOwnerError();
}
owner.h = {
...owner.h,
[context.id]: isUndefined(value) ? context.defaultValue : value
};
}
function hasContext(context, owner = currentOwner) {
return !isUndefined(owner?.h[context.id]);
}
function onCleanup(disposable) {
if (!currentOwner)
return;
const node = currentOwner;
if (!node.e) {
node.e = disposable;
} else if (Array.isArray(node.e)) {
node.e.push(disposable);
} else {
node.e = [node.e, disposable];
}
}
// src/core/flags.ts
var ERROR_OFFSET = 0;
var ERROR_BIT = 1 << ERROR_OFFSET;
var LOADING_OFFSET = 1;
var LOADING_BIT = 1 << LOADING_OFFSET;
var DEFAULT_FLAGS = ERROR_BIT;
// src/core/scheduler.ts
var scheduled = false;
var runningScheduled = false;
var Computations = [];
var RenderEffects = [];
var Effects = [];
function flushSync() {
if (!runningScheduled)
runScheduled();
}
function flushQueue() {
if (scheduled)
return;
scheduled = true;
queueMicrotask(runScheduled);
}
function runTop(node) {
const ancestors = [];
for (let current = node; current !== null; current = current.l) {
if (current.a !== STATE_CLEAN) {
ancestors.push(current);
}
}
for (let i = ancestors.length - 1; i >= 0; i--) {
if (ancestors[i].a !== STATE_DISPOSED)
ancestors[i].m();
}
}
function runScheduled() {
if (!Effects.length && !RenderEffects.length && !Computations.length) {
scheduled = false;
return;
}
runningScheduled = true;
try {
runPureQueue(Computations);
runPureQueue(RenderEffects);
runPureQueue(Effects);
} finally {
const renderEffects = RenderEffects;
const effects = Effects;
Computations = [];
Effects = [];
RenderEffects = [];
scheduled = false;
runningScheduled = false;
incrementClock();
runEffectQueue(renderEffects);
runEffectQueue(effects);
}
}
function runPureQueue(queue) {
for (let i = 0; i < queue.length; i++) {
if (queue[i].a !== STATE_CLEAN)
runTop(queue[i]);
}
}
function runEffectQueue(queue) {
for (let i = 0; i < queue.length; i++) {
if (queue[i].q && queue[i].a !== STATE_DISPOSED) {
queue[i].r(queue[i].d, queue[i].o);
queue[i].q = false;
queue[i].o = queue[i].d;
}
}
}
// src/core/core.ts
var currentObserver = null;
var currentMask = DEFAULT_FLAGS;
var newSources = null;
var newSourcesIndex = 0;
var newFlags = 0;
var clock = 0;
var syncResolve = false;
var updateCheck = null;
function getObserver() {
return currentObserver;
}
function incrementClock() {
clock++;
}
var UNCHANGED = Symbol(0);
var Computation2 = class extends Owner {
b = null;
c = null;
d;
s;
// Used in __DEV__ mode, hopefully removed in production
B;
// Using false is an optimization as an alternative to _equals: () => false
// which could enable more efficient DIRTY notification
t = isEqual;
x;
/** Whether the computation is an error or has ancestors that are unresolved */
i = 0;
/** Which flags raised by sources are handled, vs. being passed through. */
p = DEFAULT_FLAGS;
u = null;
v = null;
w = -1;
constructor(initialValue, compute2, options) {
super(compute2 === null);
this.s = compute2;
this.a = compute2 ? STATE_DIRTY : STATE_CLEAN;
this.d = initialValue;
if (options?.equals !== void 0)
this.t = options.equals;
if (options?.unobserved)
this.x = options?.unobserved;
}
y() {
if (this.s)
this.m();
if (!this.b || this.b.length)
track(this);
newFlags |= this.i & ~currentMask;
if (this.i & ERROR_BIT) {
throw this.d;
} else {
return this.d;
}
}
/**
* Return the current value of this computation
* Automatically re-executes the surrounding computation when the value changes
*/
read() {
return this.y();
}
/**
* Return the current value of this computation
* Automatically re-executes the surrounding computation when the value changes
*
* If the computation has any unresolved ancestors, this function waits for the value to resolve
* before continuing
*/
wait() {
if (!syncResolve && this.loading()) {
throw new NotReadyError();
}
return this.y();
}
/**
* Return true if the computation is the value is dependent on an unresolved promise
* Triggers re-execution of the computation when the loading state changes
*
* This is useful especially when effects want to re-execute when a computation's
* loading state changes
*/
loading() {
if (this.v === null) {
this.v = loadingState(this);
}
return this.v.read();
}
/**
* Return true if the computation is the computation threw an error
* Triggers re-execution of the computation when the error state changes
*/
error() {
if (this.u === null) {
this.u = errorState(this);
}
return this.u.read();
}
/** Update the computation with a new value. */
write(value, flags = 0, raw = false) {
const newValue = !raw && typeof value === "function" ? value(this.d) : value;
const valueChanged = newValue !== UNCHANGED && (!!(flags & ERROR_BIT) || this.t === false || !this.t(this.d, newValue));
if (valueChanged)
this.d = newValue;
const changedFlagsMask = this.i ^ flags, changedFlags = changedFlagsMask & flags;
this.i = flags;
this.w = clock + 1;
if (this.c) {
for (let i = 0; i < this.c.length; i++) {
if (valueChanged) {
this.c[i].k(STATE_DIRTY);
} else if (changedFlagsMask) {
this.c[i].z(changedFlagsMask, changedFlags);
}
}
}
return this.d;
}
/**
* Set the current node's state, and recursively mark all of this node's observers as STATE_CHECK
*/
k(state) {
if (this.a >= state)
return;
this.a = state;
if (this.c) {
for (let i = 0; i < this.c.length; i++) {
this.c[i].k(STATE_CHECK);
}
}
}
/**
* Notify the computation that one of its sources has changed flags.
*
* @param mask A bitmask for which flag(s) were changed.
* @param newFlags The source's new flags, masked to just the changed ones.
*/
z(mask, newFlags2) {
if (this.a >= STATE_DIRTY)
return;
if (mask & this.p) {
this.k(STATE_DIRTY);
return;
}
if (this.a >= STATE_CHECK)
return;
const prevFlags = this.i & mask;
const deltaFlags = prevFlags ^ newFlags2;
if (newFlags2 === prevFlags) ; else if (deltaFlags & prevFlags & mask) {
this.k(STATE_CHECK);
} else {
this.i ^= deltaFlags;
if (this.c) {
for (let i = 0; i < this.c.length; i++) {
this.c[i].z(mask, newFlags2);
}
}
}
}
A(error) {
this.write(error, this.i | ERROR_BIT);
}
/**
* This is the core part of the reactivity system, which makes sure that the values are updated
* before they are read. We've also adapted it to return the loading state of the computation,
* so that we can propagate that to the computation's observers.
*
* This function will ensure that the value and states we read from the computation are up to date
*/
m() {
if (this.a === STATE_DISPOSED) {
throw new Error("Tried to read a disposed computation");
}
if (this.a === STATE_CLEAN) {
return;
}
let observerFlags = 0;
if (this.a === STATE_CHECK) {
for (let i = 0; i < this.b.length; i++) {
this.b[i].m();
observerFlags |= this.b[i].i;
if (this.a === STATE_DIRTY) {
break;
}
}
}
if (this.a === STATE_DIRTY) {
update(this);
} else {
this.write(UNCHANGED, observerFlags);
this.a = STATE_CLEAN;
}
}
/**
* Remove ourselves from the owner graph and the computation graph
*/
n() {
if (this.a === STATE_DISPOSED)
return;
if (this.b)
removeSourceObservers(this, 0);
super.n();
}
};
function loadingState(node) {
const prevOwner = setOwner(node.l);
const options = void 0;
const computation = new Computation2(
void 0,
() => {
track(node);
node.m();
return !!(node.i & LOADING_BIT);
},
options
);
computation.p = ERROR_BIT | LOADING_BIT;
setOwner(prevOwner);
return computation;
}
function errorState(node) {
const prevOwner = setOwner(node.l);
const options = void 0;
const computation = new Computation2(
void 0,
() => {
track(node);
node.m();
return !!(node.i & ERROR_BIT);
},
options
);
computation.p = ERROR_BIT;
setOwner(prevOwner);
return computation;
}
function track(computation) {
if (currentObserver) {
if (!newSources && currentObserver.b && currentObserver.b[newSourcesIndex] === computation) {
newSourcesIndex++;
} else if (!newSources)
newSources = [computation];
else if (computation !== newSources[newSources.length - 1]) {
newSources.push(computation);
}
if (updateCheck) {
updateCheck.d = computation.w > currentObserver.w;
}
}
}
function update(node) {
const prevSources = newSources, prevSourcesIndex = newSourcesIndex, prevFlags = newFlags;
newSources = null;
newSourcesIndex = 0;
newFlags = 0;
try {
node.dispose(false);
node.emptyDisposal();
const result = compute(node, node.s, node);
node.write(result, newFlags, true);
} catch (error) {
if (error instanceof NotReadyError) {
node.write(UNCHANGED, newFlags | LOADING_BIT);
} else {
node.A(error);
}
} finally {
if (newSources) {
if (node.b)
removeSourceObservers(node, newSourcesIndex);
if (node.b && newSourcesIndex > 0) {
node.b.length = newSourcesIndex + newSources.length;
for (let i = 0; i < newSources.length; i++) {
node.b[newSourcesIndex + i] = newSources[i];
}
} else {
node.b = newSources;
}
let source;
for (let i = newSourcesIndex; i < node.b.length; i++) {
source = node.b[i];
if (!source.c)
source.c = [node];
else
source.c.push(node);
}
} else if (node.b && newSourcesIndex < node.b.length) {
removeSourceObservers(node, newSourcesIndex);
node.b.length = newSourcesIndex;
}
newSources = prevSources;
newSourcesIndex = prevSourcesIndex;
newFlags = prevFlags;
node.a = STATE_CLEAN;
}
}
function removeSourceObservers(node, index) {
let source;
let swap;
for (let i = index; i < node.b.length; i++) {
source = node.b[i];
if (source.c) {
swap = source.c.indexOf(node);
source.c[swap] = source.c[source.c.length - 1];
source.c.pop();
if (!source.c.length)
source.x?.();
}
}
}
function isEqual(a, b) {
return a === b;
}
function untrack(fn) {
if (currentObserver === null)
return fn();
return compute(getOwner(), fn, null);
}
function hasUpdated(fn) {
const current = updateCheck;
updateCheck = { d: false };
try {
fn();
return updateCheck.d;
} finally {
updateCheck = current;
}
}
function isPending(fn) {
try {
fn();
return false;
} catch (e) {
return e instanceof NotReadyError;
}
}
function latest(fn) {
const prevFlags = newFlags;
syncResolve = true;
try {
return fn();
} catch {
} finally {
newFlags = prevFlags;
syncResolve = false;
}
}
function compute(owner, compute2, observer) {
const prevOwner = setOwner(owner), prevObserver = currentObserver, prevMask = currentMask;
currentObserver = observer;
currentMask = observer?.p ?? DEFAULT_FLAGS;
try {
return compute2(observer ? observer.d : void 0);
} finally {
setOwner(prevOwner);
currentObserver = prevObserver;
currentMask = prevMask;
}
}
var EagerComputation = class extends Computation2 {
constructor(initialValue, compute2, options) {
super(initialValue, compute2, options);
this.m();
Computations.push(this);
}
k(state) {
if (this.a >= state)
return;
if (this.a === STATE_CLEAN) {
Computations.push(this);
flushQueue();
}
super.k(state);
}
};
// src/core/effect.ts
var BaseEffect = class extends Computation2 {
r;
q = false;
o;
constructor(initialValue, compute2, effect, options) {
super(initialValue, compute2, options);
this.r = effect;
this.o = initialValue;
}
write(value) {
if (value === UNCHANGED)
return this.d;
this.d = value;
this.q = true;
return value;
}
A(error) {
this.handleError(error);
}
n() {
this.r = void 0;
this.o = void 0;
super.n();
}
};
var Effect = class extends BaseEffect {
constructor(initialValue, compute2, effect, options) {
super(initialValue, compute2, effect, options);
Effects.push(this);
flushQueue();
}
k(state) {
if (this.a >= state)
return;
if (this.a === STATE_CLEAN) {
Effects.push(this);
flushQueue();
}
this.a = state;
}
};
var RenderEffect = class extends BaseEffect {
constructor(initialValue, compute2, effect, options) {
super(initialValue, compute2, effect, options);
this.m();
RenderEffects.push(this);
}
k(state) {
if (this.a >= state)
return;
if (this.a === STATE_CLEAN) {
RenderEffects.push(this);
flushQueue();
}
this.a = state;
}
};
// src/signals.ts
function createSignal(first, second, third) {
if (typeof first === "function") {
const memo = createMemo((p) => {
const node2 = new Computation2(
first(p ? untrack(p[0]) : second),
null,
third
);
return [node2.read.bind(node2), node2.write.bind(node2)];
});
return [() => memo()[0](), (value) => memo()[1](value)];
}
const node = new Computation2(first, null, second);
return [node.read.bind(node), node.write.bind(node)];
}
function createAsync(fn, initial, options) {
const lhs = new EagerComputation(
{
d: initial
},
(p) => {
const value = p?.d;
const source = fn(value);
const isPromise = source instanceof Promise;
const iterator = source[Symbol.asyncIterator];
if (!isPromise && !iterator) {
return {
wait() {
return source;
},
d: source
};
}
const signal = new Computation2(value, null, options);
signal.write(UNCHANGED, LOADING_BIT);
if (isPromise) {
source.then(
(value2) => {
signal.write(value2, 0);
},
(error) => {
signal.write(error, ERROR_BIT);
}
);
} else {
let abort = false;
onCleanup(() => abort = true);
(async () => {
try {
for await (let value2 of source) {
if (abort)
return;
signal.write(value2, 0);
}
} catch (error) {
signal.write(error, ERROR_BIT);
}
})();
}
return signal;
}
);
return () => lhs.wait().wait();
}
function createMemo(compute2, initialValue, options) {
let node = new Computation2(initialValue, compute2, options);
let value;
return () => {
if (node) {
value = node.wait();
if (!node.b?.length)
node = void 0;
}
return value;
};
}
function createEffect(compute2, effect, initialValue, options) {
void new Effect(
initialValue,
compute2,
effect,
void 0
);
}
function createRenderEffect(compute2, effect, initialValue, options) {
void new RenderEffect(
initialValue,
compute2,
effect,
void 0
);
}
function createRoot(init) {
const owner = new Owner();
return compute(owner, !init.length ? init : () => init(() => owner.dispose()), null);
}
function runWithOwner(owner, run) {
try {
return compute(owner, run, null);
} catch (error) {
owner?.handleError(error);
return void 0;
}
}
function catchError(fn, handler) {
const owner = new Owner();
owner.f = owner.f ? [handler, ...owner.f] : [handler];
try {
compute(owner, fn, null);
} catch (error) {
owner.handleError(error);
}
}
export { Computation2 as Computation, ContextNotFoundError, NoOwnerError, NotReadyError, Owner, catchError, createAsync, createContext, createEffect, createMemo, createRenderEffect, createRoot, createSignal, flushSync, getContext, getObserver, getOwner, hasContext, hasUpdated, isEqual, isPending, latest, onCleanup, runWithOwner, setContext, untrack };

View File

@@ -0,0 +1,10 @@
/**
* See https://dev.to/modderme123/super-charging-fine-grained-reactive-performance-47ph
* State clean corresponds to a node where all the sources are fully up to date
* State check corresponds to a node where some sources (including grandparents) may have changed
* State dirty corresponds to a node where the direct parents of a node has changed
*/
export declare const STATE_CLEAN = 0;
export declare const STATE_CHECK = 1;
export declare const STATE_DIRTY = 2;
export declare const STATE_DISPOSED = 3;

View File

@@ -0,0 +1,161 @@
/**
* Nodes for constructing a graph of reactive values and reactive computations.
*
* - The graph is acyclic.
* - The user inputs new values into the graph by calling .write() on one more computation nodes.
* - The user retrieves computed results from the graph by calling .read() on one or more computation nodes.
* - The library is responsible for running any necessary computations so that .read() is up to date
* with all prior .write() calls anywhere in the graph.
* - We call the input nodes 'roots' and the output nodes 'leaves' of the graph here.
* - Changes flow from roots to leaves. It would be effective but inefficient to immediately
* propagate all changes from a root through the graph to descendant leaves. Instead, we defer
* change most change propagation computation until a leaf is accessed. This allows us to
* coalesce computations and skip altogether recalculating unused sections of the graph.
* - Each computation node tracks its sources and its observers (observers are other
* elements that have this node as a source). Source and observer links are updated automatically
* as observer computations re-evaluate and call get() on their sources.
* - Each node stores a cache state (clean/check/dirty) to support the change propagation algorithm:
*
* In general, execution proceeds in three passes:
*
* 1. write() propagates changes down the graph to the leaves
* direct children are marked as dirty and their deeper descendants marked as check
* (no computations are evaluated)
* 2. read() requests that parent nodes updateIfNecessary(), which proceeds recursively up the tree
* to decide whether the node is clean (parents unchanged) or dirty (parents changed)
* 3. updateIfNecessary() evaluates the computation if the node is dirty (the computations are
* executed in root to leaf order)
*/
import { type Flags } from "./flags.js";
import { Owner } from "./owner.js";
export interface SignalOptions<T> {
name?: string;
equals?: ((prev: T, next: T) => boolean) | false;
unobserved?: () => void;
}
interface SourceType {
_observers: ObserverType[] | null;
_unobserved?: () => void;
_updateIfNecessary: () => void;
_stateFlags: Flags;
_time: number;
}
interface ObserverType {
_sources: SourceType[] | null;
_notify: (state: number) => void;
_handlerMask: Flags;
_notifyFlags: (mask: Flags, newFlags: Flags) => void;
_time: number;
}
/**
* Returns the current observer.
*/
export declare function getObserver(): ObserverType | null;
export declare function incrementClock(): void;
export declare const UNCHANGED: unique symbol;
export type UNCHANGED = typeof UNCHANGED;
export declare class Computation<T = any> extends Owner implements SourceType, ObserverType {
_sources: SourceType[] | null;
_observers: ObserverType[] | null;
_value: T | undefined;
_compute: null | ((p?: T) => T);
_name: string | undefined;
_equals: false | ((a: T, b: T) => boolean);
_unobserved: (() => void) | undefined;
/** Whether the computation is an error or has ancestors that are unresolved */
_stateFlags: number;
/** Which flags raised by sources are handled, vs. being passed through. */
_handlerMask: number;
_error: Computation<boolean> | null;
_loading: Computation<boolean> | null;
_time: number;
constructor(initialValue: T | undefined, compute: null | ((p?: T) => T), options?: SignalOptions<T>);
_read(): T;
/**
* Return the current value of this computation
* Automatically re-executes the surrounding computation when the value changes
*/
read(): T;
/**
* Return the current value of this computation
* Automatically re-executes the surrounding computation when the value changes
*
* If the computation has any unresolved ancestors, this function waits for the value to resolve
* before continuing
*/
wait(): T;
/**
* Return true if the computation is the value is dependent on an unresolved promise
* Triggers re-execution of the computation when the loading state changes
*
* This is useful especially when effects want to re-execute when a computation's
* loading state changes
*/
loading(): boolean;
/**
* Return true if the computation is the computation threw an error
* Triggers re-execution of the computation when the error state changes
*/
error(): boolean;
/** Update the computation with a new value. */
write(value: T | ((currentValue: T) => T) | UNCHANGED, flags?: number, raw?: boolean): T;
/**
* Set the current node's state, and recursively mark all of this node's observers as STATE_CHECK
*/
_notify(state: number): void;
/**
* Notify the computation that one of its sources has changed flags.
*
* @param mask A bitmask for which flag(s) were changed.
* @param newFlags The source's new flags, masked to just the changed ones.
*/
_notifyFlags(mask: Flags, newFlags: Flags): void;
_setError(error: unknown): void;
/**
* This is the core part of the reactivity system, which makes sure that the values are updated
* before they are read. We've also adapted it to return the loading state of the computation,
* so that we can propagate that to the computation's observers.
*
* This function will ensure that the value and states we read from the computation are up to date
*/
_updateIfNecessary(): void;
/**
* Remove ourselves from the owner graph and the computation graph
*/
_disposeNode(): void;
}
/**
* Reruns a computation's _compute function, producing a new value and keeping track of dependencies.
*
* It handles the updating of sources and observers, disposal of previous executions,
* and error handling if the _compute function throws. It also sets the node as loading
* if it reads any parents that are currently loading.
*/
export declare function update<T>(node: Computation<T>): void;
export declare function isEqual<T>(a: T, b: T): boolean;
/**
* Returns the current value stored inside the given compute function without triggering any
* dependencies. Use `untrack` if you want to also disable owner tracking.
*/
export declare function untrack<T>(fn: () => T): T;
/**
* Returns true if the given functinon contains signals that have been updated since the last time
* the parent computation was run.
*/
export declare function hasUpdated(fn: () => any): boolean;
/**
* Returns true if the given function contains async signals that are not ready yet.
*/
export declare function isPending(fn: () => any): boolean;
export declare function latest<T>(fn: () => T): T | undefined;
/**
* A convenient wrapper that calls `compute` with the `owner` and `observer` and is guaranteed
* to reset the global context after the computation is finished even if an error is thrown.
*/
export declare function compute<T>(owner: Owner | null, compute: (val: T) => T, observer: Computation<T>): T;
export declare function compute<T>(owner: Owner | null, compute: (val: undefined) => T, observer: null): T;
export declare class EagerComputation<T = any> extends Computation<T> {
constructor(initialValue: T, compute: () => T, options?: SignalOptions<T>);
_notify(state: number): void;
}
export {};

View File

@@ -0,0 +1,23 @@
import { Computation, type SignalOptions } from "./core.js";
/**
* Effects are the leaf nodes of our reactive graph. When their sources change, they are
* automatically added to the queue of effects to re-execute, which will cause them to fetch their
* sources and recompute
*/
export declare class BaseEffect<T = any> extends Computation<T> {
_effect: (val: T, prev: T | undefined) => void;
_modified: boolean;
_prevValue: T | undefined;
constructor(initialValue: T, compute: () => T, effect: (val: T, prev: T | undefined) => void, options?: SignalOptions<T>);
write(value: T): T;
_setError(error: unknown): void;
_disposeNode(): void;
}
export declare class Effect<T = any> extends BaseEffect<T> {
constructor(initialValue: T, compute: () => T, effect: (val: T, prev: T | undefined) => void, options?: SignalOptions<T>);
_notify(state: number): void;
}
export declare class RenderEffect<T = any> extends BaseEffect<T> {
constructor(initialValue: T, compute: () => T, effect: (val: T, prev: T | undefined) => void, options?: SignalOptions<T>);
_notify(state: number): void;
}

View File

@@ -0,0 +1,11 @@
export declare class NotReadyError extends Error {
}
export declare class NoOwnerError extends Error {
constructor();
}
export declare class ContextNotFoundError extends Error {
constructor();
}
export interface ErrorHandler {
(error: unknown): void;
}

View File

@@ -0,0 +1,8 @@
export type Flags = number;
export declare const ERROR_OFFSET = 0;
export declare const ERROR_BIT: number;
export declare const ERROR: unique symbol;
export declare const LOADING_OFFSET = 1;
export declare const LOADING_BIT: number;
export declare const LOADING: unique symbol;
export declare const DEFAULT_FLAGS: number;

View File

@@ -0,0 +1,6 @@
export { ContextNotFoundError, NoOwnerError, NotReadyError, type ErrorHandler } from "./error.js";
export { Owner, createContext, getContext, setContext, hasContext, getOwner, onCleanup, type Context, type ContextRecord, type Disposable } from "./owner.js";
export { Computation, EagerComputation, getObserver, isEqual, untrack, hasUpdated, isPending, latest, UNCHANGED, compute, type SignalOptions } from "./core.js";
export { Effect, RenderEffect } from "./effect.js";
export { flushSync } from "./scheduler.js";
export * from "./flags.js";

View File

@@ -0,0 +1,88 @@
/**
* Owner tracking is used to enable nested tracking scopes with automatic cleanup.
* We also use owners to also keep track of which error handling context we are in.
*
* If you write the following
*
* const a = createOwner(() => {
* const b = createOwner(() => {});
*
* const c = createOwner(() => {
* const d = createOwner(() => {});
* });
*
* const e = createOwner(() => {});
* });
*
* The owner tree will look like this:
*
* a
* /|\
* b-c-e
* |
* d
*
* Following the _nextSibling pointers of each owner will first give you its children, and then its siblings (in reverse).
* a -> e -> c -> d -> b
*
* Note that the owner tree is largely orthogonal to the reactivity tree, and is much closer to the component tree.
*/
import { type ErrorHandler } from "./error.js";
export type ContextRecord = Record<string | symbol, unknown>;
export interface Disposable {
(): void;
}
/**
* Returns the currently executing parent owner.
*/
export declare function getOwner(): Owner | null;
export declare function setOwner(owner: Owner | null): Owner | null;
export declare class Owner {
_parent: Owner | null;
_nextSibling: Owner | null;
_prevSibling: Owner | null;
_state: number;
_disposal: Disposable | Disposable[] | null;
_context: ContextRecord;
_handlers: ErrorHandler[] | null;
constructor(signal?: boolean);
append(child: Owner): void;
dispose(this: Owner, self?: boolean): void;
_disposeNode(): void;
emptyDisposal(): void;
handleError(error: unknown): void;
}
export interface Context<T> {
readonly id: symbol;
readonly defaultValue: T | undefined;
}
/**
* Context provides a form of dependency injection. It is used to save from needing to pass
* data as props through intermediate components. This function creates a new context object
* that can be used with `getContext` and `setContext`.
*
* A default value can be provided here which will be used when a specific value is not provided
* via a `setContext` call.
*/
export declare function createContext<T>(defaultValue?: T, description?: string): Context<T>;
/**
* Attempts to get a context value for the given key.
*
* @throws `NoOwnerError` if there's no owner at the time of call.
* @throws `ContextNotFoundError` if a context value has not been set yet.
*/
export declare function getContext<T>(context: Context<T>, owner?: Owner | null): T;
/**
* Attempts to set a context value on the parent scope with the given key.
*
* @throws `NoOwnerError` if there's no owner at the time of call.
*/
export declare function setContext<T>(context: Context<T>, value?: T, owner?: Owner | null): void;
/**
* Whether the given context is currently defined.
*/
export declare function hasContext(context: Context<any>, owner?: Owner | null): boolean;
/**
* Runs the given function when the parent owner computation is being disposed.
*/
export declare function onCleanup(disposable: Disposable): void;

View File

@@ -0,0 +1,9 @@
import type { Effect, RenderEffect } from "./effect.js";
import { Computation } from "./core.js";
export declare let Computations: Computation[], RenderEffects: RenderEffect[], Effects: Effect[];
/**
* By default, changes are batched on the microtask queue which is an async process. You can flush
* the queue synchronously to get the latest updates by calling `flushSync()`.
*/
export declare function flushSync(): void;
export declare function flushQueue(): void;

View File

@@ -0,0 +1,4 @@
export { Computation, ContextNotFoundError, NoOwnerError, NotReadyError, Owner, createContext, getContext, setContext, hasContext, getOwner, onCleanup, getObserver, isEqual, untrack, hasUpdated, isPending, latest } from "./core/index.js";
export type { ErrorHandler, SignalOptions, Context, ContextRecord, Disposable } from "./core/index.js";
export { flushSync } from "./core/scheduler.js";
export * from "./signals.js";

View File

@@ -0,0 +1,12 @@
import type { Accessor } from "./signals.js";
export type Maybe<T> = T | void | null | undefined | false;
/**
* Reactive map helper that caches each list item by reference to reduce unnecessary mapping on
* updates.
*
* @see {@link https://github.com/solidjs/x-reactivity#maparray}
*/
export declare function mapArray<Item, MappedItem>(list: Accessor<Maybe<readonly Item[]>>, map: (value: Accessor<Item>, index: Accessor<number>) => MappedItem, options?: {
keyed?: boolean | ((item: Item) => any);
name?: string;
}): Accessor<MappedItem[]>;

View File

@@ -0,0 +1,56 @@
import type { SignalOptions } from "./core/index.js";
import { Owner } from "./core/index.js";
export interface Accessor<T> {
(): T;
}
export interface Setter<T> {
(value: T | SetValue<T>): T;
}
export interface SetValue<T> {
(currentValue: T): T;
}
export type Signal<T> = [read: Accessor<T>, write: Setter<T>];
/**
* Wraps the given value into a signal. The signal will return the current value when invoked
* `fn()`, and provide a simple write API via `write()`. The value can now be observed
* when used inside other computations created with `computed` and `effect`.
*/
export declare function createSignal<T>(initialValue: Exclude<T, Function>, options?: SignalOptions<T>): Signal<T>;
export declare function createSignal<T>(fn: (prev?: T) => T, initialValue?: T, options?: SignalOptions<T>): Signal<T>;
export declare function createAsync<T>(fn: (prev?: T) => Promise<T> | AsyncIterable<T> | T, initial?: T, options?: SignalOptions<T>): Accessor<T>;
/**
* Creates a new computation whose value is computed and returned by the given function. The given
* compute function is _only_ re-run when one of it's dependencies are updated. Dependencies are
* are all signals that are read during execution.
*/
export declare function createMemo<T>(compute: (prev?: T) => T, initialValue?: T, options?: SignalOptions<T>): Accessor<T>;
/**
* Invokes the given function each time any of the signals that are read inside are updated
* (i.e., their value changes). The effect is immediately invoked on initialization.
*/
export declare function createEffect<T>(compute: () => T, effect: (v: T) => (() => void) | void, initialValue?: T, options?: {
name?: string;
}): void;
/**
* Invokes the given function each time any of the signals that are read inside are updated
* (i.e., their value changes). The effect is immediately invoked on initialization.
*/
export declare function createRenderEffect<T>(compute: () => T, effect: (v: T) => (() => void) | void, initialValue?: T, options?: {
name?: string;
}): void;
/**
* Creates a computation root which is given a `dispose()` function to dispose of all inner
* computations.
*/
export declare function createRoot<T>(init: ((dispose: () => void) => T) | (() => T)): T;
/**
* Runs the given function in the given owner so that error handling and cleanups continue to work.
*
* Warning: Usually there are simpler ways of modeling a problem that avoid using this function
*/
export declare function runWithOwner<T>(owner: Owner | null, run: () => T): T | undefined;
/**
* Runs the given function when an error is thrown in a child owner. If the error is thrown again
* inside the error handler, it will trigger the next available parent owner handler.
*/
export declare function catchError<T>(fn: () => T, handler: (error: unknown) => void): void;

View File

@@ -0,0 +1 @@
export * from "./store.js";

View File

@@ -0,0 +1,31 @@
export type Store<T> = Readonly<T>;
export type StoreSetter<T> = (fn: (state: T) => void) => void;
declare const $TRACK: unique symbol, $PROXY: unique symbol;
export { $PROXY, $TRACK };
export type StoreNode = Record<PropertyKey, any>;
export declare namespace SolidStore {
interface Unwrappable {
}
}
export type NotWrappable = string | number | bigint | symbol | boolean | Function | null | undefined | SolidStore.Unwrappable[keyof SolidStore.Unwrappable];
export declare function isWrappable<T>(obj: T | NotWrappable): obj is T;
/**
* Returns the underlying data in the store without a proxy.
* @param item store proxy object
* @example
* ```js
* const initial = {z...};
* const [state, setState] = createStore(initial);
* initial === state; // => false
* initial === unwrap(state); // => true
* ```
*/
export declare function unwrap<T>(item: T, set?: Set<unknown>): T;
export declare function createStore<T extends object = {}>(store: T | Store<T>): [get: Store<T>, set: StoreSetter<T>];
export declare function createStore<T extends object = {}>(fn: (store: T) => void, store: T | Store<T>): [get: Store<T>, set: StoreSetter<T>];
/**
* Creates a mutable derived value
*
* @see {@link https://github.com/solidjs/x-reactivity#createprojection}
*/
export declare function createProjection<T extends Object>(fn: (draft: T) => void, initialValue: T): Readonly<T>;

View File

@@ -0,0 +1 @@
export declare function isUndefined(value: any): value is undefined;

View File

@@ -0,0 +1,779 @@
// src/core/error.ts
var NotReadyError = class extends Error {
};
var NoOwnerError = class extends Error {
constructor() {
super(
""
);
}
};
var ContextNotFoundError = class extends Error {
constructor() {
super(
""
);
}
};
// src/utils.ts
function isUndefined(value) {
return typeof value === "undefined";
}
// src/core/constants.ts
var STATE_CLEAN = 0;
var STATE_CHECK = 1;
var STATE_DIRTY = 2;
var STATE_DISPOSED = 3;
// src/core/owner.ts
var currentOwner = null;
var defaultContext = {};
function getOwner() {
return currentOwner;
}
function setOwner(owner) {
const out = currentOwner;
currentOwner = owner;
return out;
}
var Owner = class {
// We flatten the owner tree into a linked list so that we don't need a pointer to .firstChild
// However, the children are actually added in reverse creation order
// See comment at the top of the file for an example of the _nextSibling traversal
k = null;
g = null;
j = null;
a = STATE_CLEAN;
e = null;
h = defaultContext;
f = null;
constructor(signal = false) {
if (currentOwner && !signal)
currentOwner.append(this);
}
append(child) {
child.k = this;
child.j = this;
if (this.g)
this.g.j = child;
child.g = this.g;
this.g = child;
if (child.h !== this.h) {
child.h = { ...this.h, ...child.h };
}
if (this.f) {
child.f = !child.f ? this.f : [...child.f, ...this.f];
}
}
dispose(self = true) {
if (this.a === STATE_DISPOSED)
return;
let head = self ? this.j || this.k : this, current = this.g, next = null;
while (current && current.k === this) {
current.dispose(true);
current.n();
next = current.g;
current.g = null;
current = next;
}
if (self)
this.n();
if (current)
current.j = !self ? this : this.j;
if (head)
head.g = current;
}
n() {
if (this.j)
this.j.g = null;
this.k = null;
this.j = null;
this.h = defaultContext;
this.f = null;
this.a = STATE_DISPOSED;
this.emptyDisposal();
}
emptyDisposal() {
if (!this.e)
return;
if (Array.isArray(this.e)) {
for (let i = 0; i < this.e.length; i++) {
const callable = this.e[i];
callable.call(callable);
}
} else {
this.e.call(this.e);
}
this.e = null;
}
handleError(error) {
if (!this.f)
throw error;
let i = 0, len = this.f.length;
for (i = 0; i < len; i++) {
try {
this.f[i](error);
break;
} catch (e) {
error = e;
}
}
if (i === len)
throw error;
}
};
function createContext(defaultValue, description) {
return { id: Symbol(description), defaultValue };
}
function getContext(context, owner = currentOwner) {
if (!owner) {
throw new NoOwnerError();
}
const value = hasContext(context, owner) ? owner.h[context.id] : context.defaultValue;
if (isUndefined(value)) {
throw new ContextNotFoundError();
}
return value;
}
function setContext(context, value, owner = currentOwner) {
if (!owner) {
throw new NoOwnerError();
}
owner.h = {
...owner.h,
[context.id]: isUndefined(value) ? context.defaultValue : value
};
}
function hasContext(context, owner = currentOwner) {
return !isUndefined(owner?.h[context.id]);
}
function onCleanup(disposable) {
if (!currentOwner)
return;
const node = currentOwner;
if (!node.e) {
node.e = disposable;
} else if (Array.isArray(node.e)) {
node.e.push(disposable);
} else {
node.e = [node.e, disposable];
}
}
// src/core/flags.ts
var ERROR_OFFSET = 0;
var ERROR_BIT = 1 << ERROR_OFFSET;
var LOADING_OFFSET = 1;
var LOADING_BIT = 1 << LOADING_OFFSET;
var DEFAULT_FLAGS = ERROR_BIT;
// src/core/scheduler.ts
var scheduled = false;
var runningScheduled = false;
var Computations = [];
var RenderEffects = [];
var Effects = [];
function flushSync() {
if (!runningScheduled)
runScheduled();
}
function flushQueue() {
if (scheduled)
return;
scheduled = true;
queueMicrotask(runScheduled);
}
function runTop(node) {
const ancestors = [];
for (let current = node; current !== null; current = current.k) {
if (current.a !== STATE_CLEAN) {
ancestors.push(current);
}
}
for (let i = ancestors.length - 1; i >= 0; i--) {
if (ancestors[i].a !== STATE_DISPOSED)
ancestors[i].l();
}
}
function runScheduled() {
if (!Effects.length && !RenderEffects.length && !Computations.length) {
scheduled = false;
return;
}
runningScheduled = true;
try {
runPureQueue(Computations);
runPureQueue(RenderEffects);
runPureQueue(Effects);
} finally {
const renderEffects = RenderEffects;
const effects = Effects;
Computations = [];
Effects = [];
RenderEffects = [];
scheduled = false;
runningScheduled = false;
incrementClock();
runEffectQueue(renderEffects);
runEffectQueue(effects);
}
}
function runPureQueue(queue) {
for (let i = 0; i < queue.length; i++) {
if (queue[i].a !== STATE_CLEAN)
runTop(queue[i]);
}
}
function runEffectQueue(queue) {
for (let i = 0; i < queue.length; i++) {
if (queue[i].q && queue[i].a !== STATE_DISPOSED) {
queue[i].r(queue[i].d, queue[i].o);
queue[i].q = false;
queue[i].o = queue[i].d;
}
}
}
// src/core/core.ts
var currentObserver = null;
var currentMask = DEFAULT_FLAGS;
var newSources = null;
var newSourcesIndex = 0;
var newFlags = 0;
var clock = 0;
var syncResolve = false;
var updateCheck = null;
function getObserver() {
return currentObserver;
}
function incrementClock() {
clock++;
}
var UNCHANGED = Symbol(0);
var Computation2 = class extends Owner {
b = null;
c = null;
d;
s;
// Used in __DEV__ mode, hopefully removed in production
C;
// Using false is an optimization as an alternative to _equals: () => false
// which could enable more efficient DIRTY notification
t = isEqual;
y;
/** Whether the computation is an error or has ancestors that are unresolved */
i = 0;
/** Which flags raised by sources are handled, vs. being passed through. */
p = DEFAULT_FLAGS;
u = null;
v = null;
w = -1;
constructor(initialValue, compute2, options) {
super(compute2 === null);
this.s = compute2;
this.a = compute2 ? STATE_DIRTY : STATE_CLEAN;
this.d = initialValue;
if (options?.equals !== void 0)
this.t = options.equals;
if (options?.unobserved)
this.y = options?.unobserved;
}
z() {
if (this.s)
this.l();
if (!this.b || this.b.length)
track(this);
newFlags |= this.i & ~currentMask;
if (this.i & ERROR_BIT) {
throw this.d;
} else {
return this.d;
}
}
/**
* Return the current value of this computation
* Automatically re-executes the surrounding computation when the value changes
*/
read() {
return this.z();
}
/**
* Return the current value of this computation
* Automatically re-executes the surrounding computation when the value changes
*
* If the computation has any unresolved ancestors, this function waits for the value to resolve
* before continuing
*/
wait() {
if (!syncResolve && this.loading()) {
throw new NotReadyError();
}
return this.z();
}
/**
* Return true if the computation is the value is dependent on an unresolved promise
* Triggers re-execution of the computation when the loading state changes
*
* This is useful especially when effects want to re-execute when a computation's
* loading state changes
*/
loading() {
if (this.v === null) {
this.v = loadingState(this);
}
return this.v.read();
}
/**
* Return true if the computation is the computation threw an error
* Triggers re-execution of the computation when the error state changes
*/
error() {
if (this.u === null) {
this.u = errorState(this);
}
return this.u.read();
}
/** Update the computation with a new value. */
write(value, flags = 0, raw = false) {
const newValue = !raw && typeof value === "function" ? value(this.d) : value;
const valueChanged = newValue !== UNCHANGED && (!!(flags & ERROR_BIT) || this.t === false || !this.t(this.d, newValue));
if (valueChanged)
this.d = newValue;
const changedFlagsMask = this.i ^ flags, changedFlags = changedFlagsMask & flags;
this.i = flags;
this.w = clock + 1;
if (this.c) {
for (let i = 0; i < this.c.length; i++) {
if (valueChanged) {
this.c[i].m(STATE_DIRTY);
} else if (changedFlagsMask) {
this.c[i].A(changedFlagsMask, changedFlags);
}
}
}
return this.d;
}
/**
* Set the current node's state, and recursively mark all of this node's observers as STATE_CHECK
*/
m(state) {
if (this.a >= state)
return;
this.a = state;
if (this.c) {
for (let i = 0; i < this.c.length; i++) {
this.c[i].m(STATE_CHECK);
}
}
}
/**
* Notify the computation that one of its sources has changed flags.
*
* @param mask A bitmask for which flag(s) were changed.
* @param newFlags The source's new flags, masked to just the changed ones.
*/
A(mask, newFlags2) {
if (this.a >= STATE_DIRTY)
return;
if (mask & this.p) {
this.m(STATE_DIRTY);
return;
}
if (this.a >= STATE_CHECK)
return;
const prevFlags = this.i & mask;
const deltaFlags = prevFlags ^ newFlags2;
if (newFlags2 === prevFlags) ; else if (deltaFlags & prevFlags & mask) {
this.m(STATE_CHECK);
} else {
this.i ^= deltaFlags;
if (this.c) {
for (let i = 0; i < this.c.length; i++) {
this.c[i].A(mask, newFlags2);
}
}
}
}
B(error) {
this.write(error, this.i | ERROR_BIT);
}
/**
* This is the core part of the reactivity system, which makes sure that the values are updated
* before they are read. We've also adapted it to return the loading state of the computation,
* so that we can propagate that to the computation's observers.
*
* This function will ensure that the value and states we read from the computation are up to date
*/
l() {
if (this.a === STATE_DISPOSED) {
throw new Error("Tried to read a disposed computation");
}
if (this.a === STATE_CLEAN) {
return;
}
let observerFlags = 0;
if (this.a === STATE_CHECK) {
for (let i = 0; i < this.b.length; i++) {
this.b[i].l();
observerFlags |= this.b[i].i;
if (this.a === STATE_DIRTY) {
break;
}
}
}
if (this.a === STATE_DIRTY) {
update(this);
} else {
this.write(UNCHANGED, observerFlags);
this.a = STATE_CLEAN;
}
}
/**
* Remove ourselves from the owner graph and the computation graph
*/
n() {
if (this.a === STATE_DISPOSED)
return;
if (this.b)
removeSourceObservers(this, 0);
super.n();
}
};
function loadingState(node) {
const prevOwner = setOwner(node.k);
const options = void 0;
const computation = new Computation2(
void 0,
() => {
track(node);
node.l();
return !!(node.i & LOADING_BIT);
},
options
);
computation.p = ERROR_BIT | LOADING_BIT;
setOwner(prevOwner);
return computation;
}
function errorState(node) {
const prevOwner = setOwner(node.k);
const options = void 0;
const computation = new Computation2(
void 0,
() => {
track(node);
node.l();
return !!(node.i & ERROR_BIT);
},
options
);
computation.p = ERROR_BIT;
setOwner(prevOwner);
return computation;
}
function track(computation) {
if (currentObserver) {
if (!newSources && currentObserver.b && currentObserver.b[newSourcesIndex] === computation) {
newSourcesIndex++;
} else if (!newSources)
newSources = [computation];
else if (computation !== newSources[newSources.length - 1]) {
newSources.push(computation);
}
if (updateCheck) {
updateCheck.d = computation.w > currentObserver.w;
}
}
}
function update(node) {
const prevSources = newSources, prevSourcesIndex = newSourcesIndex, prevFlags = newFlags;
newSources = null;
newSourcesIndex = 0;
newFlags = 0;
try {
node.dispose(false);
node.emptyDisposal();
const result = compute(node, node.s, node);
node.write(result, newFlags, true);
} catch (error) {
if (error instanceof NotReadyError) {
node.write(UNCHANGED, newFlags | LOADING_BIT);
} else {
node.B(error);
}
} finally {
if (newSources) {
if (node.b)
removeSourceObservers(node, newSourcesIndex);
if (node.b && newSourcesIndex > 0) {
node.b.length = newSourcesIndex + newSources.length;
for (let i = 0; i < newSources.length; i++) {
node.b[newSourcesIndex + i] = newSources[i];
}
} else {
node.b = newSources;
}
let source;
for (let i = newSourcesIndex; i < node.b.length; i++) {
source = node.b[i];
if (!source.c)
source.c = [node];
else
source.c.push(node);
}
} else if (node.b && newSourcesIndex < node.b.length) {
removeSourceObservers(node, newSourcesIndex);
node.b.length = newSourcesIndex;
}
newSources = prevSources;
newSourcesIndex = prevSourcesIndex;
newFlags = prevFlags;
node.a = STATE_CLEAN;
}
}
function removeSourceObservers(node, index) {
let source;
let swap;
for (let i = index; i < node.b.length; i++) {
source = node.b[i];
if (source.c) {
swap = source.c.indexOf(node);
source.c[swap] = source.c[source.c.length - 1];
source.c.pop();
if (!source.c.length)
source.y?.();
}
}
}
function isEqual(a, b) {
return a === b;
}
function untrack(fn) {
if (currentObserver === null)
return fn();
return compute(getOwner(), fn, null);
}
function hasUpdated(fn) {
const current = updateCheck;
updateCheck = { d: false };
try {
fn();
return updateCheck.d;
} finally {
updateCheck = current;
}
}
function isPending(fn) {
try {
fn();
return false;
} catch (e) {
return e instanceof NotReadyError;
}
}
function latest(fn) {
const prevFlags = newFlags;
syncResolve = true;
try {
return fn();
} catch {
} finally {
newFlags = prevFlags;
syncResolve = false;
}
}
function compute(owner, compute2, observer) {
const prevOwner = setOwner(owner), prevObserver = currentObserver, prevMask = currentMask;
currentObserver = observer;
currentMask = observer?.p ?? DEFAULT_FLAGS;
try {
return compute2(observer ? observer.d : void 0);
} finally {
setOwner(prevOwner);
currentObserver = prevObserver;
currentMask = prevMask;
}
}
var EagerComputation = class extends Computation2 {
constructor(initialValue, compute2, options) {
super(initialValue, compute2, options);
this.l();
Computations.push(this);
}
m(state) {
if (this.a >= state)
return;
if (this.a === STATE_CLEAN) {
Computations.push(this);
flushQueue();
}
super.m(state);
}
};
// src/core/effect.ts
var USER_EFFECT = 0;
var RENDER_EFFECT = 1;
var Effect = class extends Computation2 {
r;
q = false;
o;
x;
constructor(initialValue, compute2, effect, options) {
super(initialValue, compute2, options);
this.r = effect;
this.o = initialValue;
this.l();
this.x = options?.render ? RENDER_EFFECT : USER_EFFECT;
(this.x ? RenderEffects : Effects).push(this);
}
write(value) {
if (value === UNCHANGED)
return this.d;
this.d = value;
this.q = true;
return value;
}
m(state) {
if (this.a >= state)
return;
if (this.a === STATE_CLEAN) {
(this.x ? RenderEffects : Effects).push(this);
flushQueue();
}
this.a = state;
}
B(error) {
this.handleError(error);
}
n() {
this.r = void 0;
this.o = void 0;
super.n();
}
};
// src/signals.ts
function createSignal(first, second, third) {
if (typeof first === "function") {
const memo = createMemo((p) => {
const node2 = new Computation2(
first(p ? untrack(p[0]) : second),
null,
third
);
return [node2.read.bind(node2), node2.write.bind(node2)];
});
return [() => memo()[0](), (value) => memo()[1](value)];
}
const node = new Computation2(first, null, second);
return [node.read.bind(node), node.write.bind(node)];
}
function createAsync(fn, initial, options) {
const lhs = new EagerComputation(
{
d: initial
},
(p) => {
const value = p?.d;
const source = fn(value);
const isPromise = source instanceof Promise;
const iterator = source[Symbol.asyncIterator];
if (!isPromise && !iterator) {
return {
wait() {
return source;
},
d: source
};
}
const signal = new Computation2(value, null, options);
signal.write(UNCHANGED, LOADING_BIT);
if (isPromise) {
source.then(
(value2) => {
signal.write(value2, 0);
},
(error) => {
signal.write(error, ERROR_BIT);
}
);
} else {
let abort = false;
onCleanup(() => abort = true);
(async () => {
try {
for await (let value2 of source) {
if (abort)
return;
signal.write(value2, 0);
}
} catch (error) {
signal.write(error, ERROR_BIT);
}
})();
}
return signal;
}
);
return () => lhs.wait().wait();
}
function createMemo(compute2, initialValue, options) {
let node = new Computation2(
initialValue,
compute2,
options
);
let value;
return () => {
if (node) {
value = node.wait();
if (!node.b?.length)
node = void 0;
}
return value;
};
}
function createEffect(compute2, effect, initialValue, options) {
void new Effect(
initialValue,
compute2,
effect,
void 0
);
}
function createRenderEffect(compute2, effect, initialValue, options) {
void new Effect(initialValue, compute2, effect, {
render: true,
...void 0
});
}
function createRoot(init) {
const owner = new Owner();
return compute(
owner,
!init.length ? init : () => init(() => owner.dispose()),
null
);
}
function runWithOwner(owner, run) {
try {
return compute(owner, run, null);
} catch (error) {
owner?.handleError(error);
return void 0;
}
}
function catchError(fn, handler) {
const owner = new Owner();
owner.f = owner.f ? [handler, ...owner.f] : [handler];
try {
compute(owner, fn, null);
} catch (error) {
owner.handleError(error);
}
}
export { Computation2 as Computation, ContextNotFoundError, NoOwnerError, NotReadyError, Owner, catchError, createAsync, createContext, createEffect, createMemo, createRenderEffect, createRoot, createSignal, flushSync, getContext, getObserver, getOwner, hasContext, hasUpdated, isEqual, isPending, latest, onCleanup, runWithOwner, setContext, untrack };

View File

@@ -0,0 +1,10 @@
/**
* See https://dev.to/modderme123/super-charging-fine-grained-reactive-performance-47ph
* State clean corresponds to a node where all the sources are fully up to date
* State check corresponds to a node where some sources (including grandparents) may have changed
* State dirty corresponds to a node where the direct parents of a node has changed
*/
export declare const STATE_CLEAN = 0;
export declare const STATE_CHECK = 1;
export declare const STATE_DIRTY = 2;
export declare const STATE_DISPOSED = 3;

View File

@@ -0,0 +1,161 @@
/**
* Nodes for constructing a graph of reactive values and reactive computations.
*
* - The graph is acyclic.
* - The user inputs new values into the graph by calling .write() on one more computation nodes.
* - The user retrieves computed results from the graph by calling .read() on one or more computation nodes.
* - The library is responsible for running any necessary computations so that .read() is up to date
* with all prior .write() calls anywhere in the graph.
* - We call the input nodes 'roots' and the output nodes 'leaves' of the graph here.
* - Changes flow from roots to leaves. It would be effective but inefficient to immediately
* propagate all changes from a root through the graph to descendant leaves. Instead, we defer
* change most change propagation computation until a leaf is accessed. This allows us to
* coalesce computations and skip altogether recalculating unused sections of the graph.
* - Each computation node tracks its sources and its observers (observers are other
* elements that have this node as a source). Source and observer links are updated automatically
* as observer computations re-evaluate and call get() on their sources.
* - Each node stores a cache state (clean/check/dirty) to support the change propagation algorithm:
*
* In general, execution proceeds in three passes:
*
* 1. write() propagates changes down the graph to the leaves
* direct children are marked as dirty and their deeper descendants marked as check
* (no computations are evaluated)
* 2. read() requests that parent nodes updateIfNecessary(), which proceeds recursively up the tree
* to decide whether the node is clean (parents unchanged) or dirty (parents changed)
* 3. updateIfNecessary() evaluates the computation if the node is dirty (the computations are
* executed in root to leaf order)
*/
import { type Flags } from "./flags.js";
import { Owner } from "./owner.js";
export interface SignalOptions<T> {
name?: string;
equals?: ((prev: T, next: T) => boolean) | false;
unobserved?: () => void;
}
interface SourceType {
_observers: ObserverType[] | null;
_unobserved?: () => void;
_updateIfNecessary: () => void;
_stateFlags: Flags;
_time: number;
}
interface ObserverType {
_sources: SourceType[] | null;
_notify: (state: number) => void;
_handlerMask: Flags;
_notifyFlags: (mask: Flags, newFlags: Flags) => void;
_time: number;
}
/**
* Returns the current observer.
*/
export declare function getObserver(): ObserverType | null;
export declare function incrementClock(): void;
export declare const UNCHANGED: unique symbol;
export type UNCHANGED = typeof UNCHANGED;
export declare class Computation<T = any> extends Owner implements SourceType, ObserverType {
_sources: SourceType[] | null;
_observers: ObserverType[] | null;
_value: T | undefined;
_compute: null | ((p?: T) => T);
_name: string | undefined;
_equals: false | ((a: T, b: T) => boolean);
_unobserved: (() => void) | undefined;
/** Whether the computation is an error or has ancestors that are unresolved */
_stateFlags: number;
/** Which flags raised by sources are handled, vs. being passed through. */
_handlerMask: number;
_error: Computation<boolean> | null;
_loading: Computation<boolean> | null;
_time: number;
constructor(initialValue: T | undefined, compute: null | ((p?: T) => T), options?: SignalOptions<T>);
_read(): T;
/**
* Return the current value of this computation
* Automatically re-executes the surrounding computation when the value changes
*/
read(): T;
/**
* Return the current value of this computation
* Automatically re-executes the surrounding computation when the value changes
*
* If the computation has any unresolved ancestors, this function waits for the value to resolve
* before continuing
*/
wait(): T;
/**
* Return true if the computation is the value is dependent on an unresolved promise
* Triggers re-execution of the computation when the loading state changes
*
* This is useful especially when effects want to re-execute when a computation's
* loading state changes
*/
loading(): boolean;
/**
* Return true if the computation is the computation threw an error
* Triggers re-execution of the computation when the error state changes
*/
error(): boolean;
/** Update the computation with a new value. */
write(value: T | ((currentValue: T) => T) | UNCHANGED, flags?: number, raw?: boolean): T;
/**
* Set the current node's state, and recursively mark all of this node's observers as STATE_CHECK
*/
_notify(state: number): void;
/**
* Notify the computation that one of its sources has changed flags.
*
* @param mask A bitmask for which flag(s) were changed.
* @param newFlags The source's new flags, masked to just the changed ones.
*/
_notifyFlags(mask: Flags, newFlags: Flags): void;
_setError(error: unknown): void;
/**
* This is the core part of the reactivity system, which makes sure that the values are updated
* before they are read. We've also adapted it to return the loading state of the computation,
* so that we can propagate that to the computation's observers.
*
* This function will ensure that the value and states we read from the computation are up to date
*/
_updateIfNecessary(): void;
/**
* Remove ourselves from the owner graph and the computation graph
*/
_disposeNode(): void;
}
/**
* Reruns a computation's _compute function, producing a new value and keeping track of dependencies.
*
* It handles the updating of sources and observers, disposal of previous executions,
* and error handling if the _compute function throws. It also sets the node as loading
* if it reads any parents that are currently loading.
*/
export declare function update<T>(node: Computation<T>): void;
export declare function isEqual<T>(a: T, b: T): boolean;
/**
* Returns the current value stored inside the given compute function without triggering any
* dependencies. Use `untrack` if you want to also disable owner tracking.
*/
export declare function untrack<T>(fn: () => T): T;
/**
* Returns true if the given functinon contains signals that have been updated since the last time
* the parent computation was run.
*/
export declare function hasUpdated(fn: () => any): boolean;
/**
* Returns true if the given function contains async signals that are not ready yet.
*/
export declare function isPending(fn: () => any): boolean;
export declare function latest<T>(fn: () => T): T | undefined;
/**
* A convenient wrapper that calls `compute` with the `owner` and `observer` and is guaranteed
* to reset the global context after the computation is finished even if an error is thrown.
*/
export declare function compute<T>(owner: Owner | null, compute: (val: T) => T, observer: Computation<T>): T;
export declare function compute<T>(owner: Owner | null, compute: (val: undefined) => T, observer: null): T;
export declare class EagerComputation<T = any> extends Computation<T> {
constructor(initialValue: T, compute: () => T, options?: SignalOptions<T>);
_notify(state: number): void;
}
export {};

View File

@@ -0,0 +1,19 @@
import { Computation, type SignalOptions } from "./core.js";
/**
* Effects are the leaf nodes of our reactive graph. When their sources change, they are
* automatically added to the queue of effects to re-execute, which will cause them to fetch their
* sources and recompute
*/
export declare class Effect<T = any> extends Computation<T> {
_effect: (val: T, prev: T | undefined) => void;
_modified: boolean;
_prevValue: T | undefined;
_type: 0 | 1;
constructor(initialValue: T, compute: () => T, effect: (val: T, prev: T | undefined) => void, options?: SignalOptions<T> & {
render?: boolean;
});
write(value: T): T;
_notify(state: number): void;
_setError(error: unknown): void;
_disposeNode(): void;
}

View File

@@ -0,0 +1,11 @@
export declare class NotReadyError extends Error {
}
export declare class NoOwnerError extends Error {
constructor();
}
export declare class ContextNotFoundError extends Error {
constructor();
}
export interface ErrorHandler {
(error: unknown): void;
}

View File

@@ -0,0 +1,8 @@
export type Flags = number;
export declare const ERROR_OFFSET = 0;
export declare const ERROR_BIT: number;
export declare const ERROR: unique symbol;
export declare const LOADING_OFFSET = 1;
export declare const LOADING_BIT: number;
export declare const LOADING: unique symbol;
export declare const DEFAULT_FLAGS: number;

View File

@@ -0,0 +1,6 @@
export { ContextNotFoundError, NoOwnerError, NotReadyError, type ErrorHandler } from "./error.js";
export { Owner, createContext, getContext, setContext, hasContext, getOwner, onCleanup, type Context, type ContextRecord, type Disposable } from "./owner.js";
export { Computation, EagerComputation, getObserver, isEqual, untrack, hasUpdated, isPending, latest, UNCHANGED, compute, type SignalOptions } from "./core.js";
export { Effect } from "./effect.js";
export { flushSync } from "./scheduler.js";
export * from "./flags.js";

View File

@@ -0,0 +1,88 @@
/**
* Owner tracking is used to enable nested tracking scopes with automatic cleanup.
* We also use owners to also keep track of which error handling context we are in.
*
* If you write the following
*
* const a = createOwner(() => {
* const b = createOwner(() => {});
*
* const c = createOwner(() => {
* const d = createOwner(() => {});
* });
*
* const e = createOwner(() => {});
* });
*
* The owner tree will look like this:
*
* a
* /|\
* b-c-e
* |
* d
*
* Following the _nextSibling pointers of each owner will first give you its children, and then its siblings (in reverse).
* a -> e -> c -> d -> b
*
* Note that the owner tree is largely orthogonal to the reactivity tree, and is much closer to the component tree.
*/
import { type ErrorHandler } from "./error.js";
export type ContextRecord = Record<string | symbol, unknown>;
export interface Disposable {
(): void;
}
/**
* Returns the currently executing parent owner.
*/
export declare function getOwner(): Owner | null;
export declare function setOwner(owner: Owner | null): Owner | null;
export declare class Owner {
_parent: Owner | null;
_nextSibling: Owner | null;
_prevSibling: Owner | null;
_state: number;
_disposal: Disposable | Disposable[] | null;
_context: ContextRecord;
_handlers: ErrorHandler[] | null;
constructor(signal?: boolean);
append(child: Owner): void;
dispose(this: Owner, self?: boolean): void;
_disposeNode(): void;
emptyDisposal(): void;
handleError(error: unknown): void;
}
export interface Context<T> {
readonly id: symbol;
readonly defaultValue: T | undefined;
}
/**
* Context provides a form of dependency injection. It is used to save from needing to pass
* data as props through intermediate components. This function creates a new context object
* that can be used with `getContext` and `setContext`.
*
* A default value can be provided here which will be used when a specific value is not provided
* via a `setContext` call.
*/
export declare function createContext<T>(defaultValue?: T, description?: string): Context<T>;
/**
* Attempts to get a context value for the given key.
*
* @throws `NoOwnerError` if there's no owner at the time of call.
* @throws `ContextNotFoundError` if a context value has not been set yet.
*/
export declare function getContext<T>(context: Context<T>, owner?: Owner | null): T;
/**
* Attempts to set a context value on the parent scope with the given key.
*
* @throws `NoOwnerError` if there's no owner at the time of call.
*/
export declare function setContext<T>(context: Context<T>, value?: T, owner?: Owner | null): void;
/**
* Whether the given context is currently defined.
*/
export declare function hasContext(context: Context<any>, owner?: Owner | null): boolean;
/**
* Runs the given function when the parent owner computation is being disposed.
*/
export declare function onCleanup(disposable: Disposable): void;

View File

@@ -0,0 +1,9 @@
import type { Effect } from "./effect.js";
import { Computation } from "./core.js";
export declare let Computations: Computation[], RenderEffects: Effect[], Effects: Effect[];
/**
* By default, changes are batched on the microtask queue which is an async process. You can flush
* the queue synchronously to get the latest updates by calling `flushSync()`.
*/
export declare function flushSync(): void;
export declare function flushQueue(): void;

View File

@@ -0,0 +1,4 @@
export { Computation, ContextNotFoundError, NoOwnerError, NotReadyError, Owner, createContext, getContext, setContext, hasContext, getOwner, onCleanup, getObserver, isEqual, untrack, hasUpdated, isPending, latest } from "./core/index.js";
export type { ErrorHandler, SignalOptions, Context, ContextRecord, Disposable } from "./core/index.js";
export { flushSync } from "./core/scheduler.js";
export * from "./signals.js";

View File

@@ -0,0 +1,12 @@
import type { Accessor } from "./signals.js";
export type Maybe<T> = T | void | null | undefined | false;
/**
* Reactive map helper that caches each list item by reference to reduce unnecessary mapping on
* updates.
*
* @see {@link https://github.com/solidjs/x-reactivity#maparray}
*/
export declare function mapArray<Item, MappedItem>(list: Accessor<Maybe<readonly Item[]>>, map: (value: Accessor<Item>, index: Accessor<number>) => MappedItem, options?: {
keyed?: boolean | ((item: Item) => any);
name?: string;
}): Accessor<MappedItem[]>;

View File

@@ -0,0 +1,56 @@
import type { SignalOptions } from './core/index.js';
import { Owner } from './core/index.js';
export interface Accessor<T> {
(): T;
}
export interface Setter<T> {
(value: T | SetValue<T>): T;
}
export interface SetValue<T> {
(currentValue: T): T;
}
export type Signal<T> = [read: Accessor<T>, write: Setter<T>];
/**
* Wraps the given value into a signal. The signal will return the current value when invoked
* `fn()`, and provide a simple write API via `write()`. The value can now be observed
* when used inside other computations created with `computed` and `effect`.
*/
export declare function createSignal<T>(initialValue: Exclude<T, Function>, options?: SignalOptions<T>): Signal<T>;
export declare function createSignal<T>(fn: (prev?: T) => T, initialValue?: T, options?: SignalOptions<T>): Signal<T>;
export declare function createAsync<T>(fn: (prev?: T) => Promise<T> | AsyncIterable<T> | T, initial?: T, options?: SignalOptions<T>): Accessor<T>;
/**
* Creates a new computation whose value is computed and returned by the given function. The given
* compute function is _only_ re-run when one of it's dependencies are updated. Dependencies are
* are all signals that are read during execution.
*/
export declare function createMemo<T>(compute: (prev?: T) => T, initialValue?: T, options?: SignalOptions<T>): Accessor<T>;
/**
* Invokes the given function each time any of the signals that are read inside are updated
* (i.e., their value changes). The effect is immediately invoked on initialization.
*/
export declare function createEffect<T>(compute: () => T, effect: (v: T) => (() => void) | void, initialValue?: T, options?: {
name?: string;
}): void;
/**
* Invokes the given function each time any of the signals that are read inside are updated
* (i.e., their value changes). The effect is immediately invoked on initialization.
*/
export declare function createRenderEffect<T>(compute: () => T, effect: (v: T) => (() => void) | void, initialValue?: T, options?: {
name?: string;
}): void;
/**
* Creates a computation root which is given a `dispose()` function to dispose of all inner
* computations.
*/
export declare function createRoot<T>(init: ((dispose: () => void) => T) | (() => T)): T;
/**
* Runs the given function in the given owner so that error handling and cleanups continue to work.
*
* Warning: Usually there are simpler ways of modeling a problem that avoid using this function
*/
export declare function runWithOwner<T>(owner: Owner | null, run: () => T): T | undefined;
/**
* Runs the given function when an error is thrown in a child owner. If the error is thrown again
* inside the error handler, it will trigger the next available parent owner handler.
*/
export declare function catchError<T>(fn: () => T, handler: (error: unknown) => void): void;

View File

@@ -0,0 +1 @@
export * from "./store.js";

View File

@@ -0,0 +1,31 @@
export type Store<T> = Readonly<T>;
export type StoreSetter<T> = (fn: (state: T) => void) => void;
declare const $TRACK: unique symbol, $PROXY: unique symbol;
export { $PROXY, $TRACK };
export type StoreNode = Record<PropertyKey, any>;
export declare namespace SolidStore {
interface Unwrappable {
}
}
export type NotWrappable = string | number | bigint | symbol | boolean | Function | null | undefined | SolidStore.Unwrappable[keyof SolidStore.Unwrappable];
export declare function isWrappable<T>(obj: T | NotWrappable): obj is T;
/**
* Returns the underlying data in the store without a proxy.
* @param item store proxy object
* @example
* ```js
* const initial = {z...};
* const [state, setState] = createStore(initial);
* initial === state; // => false
* initial === unwrap(state); // => true
* ```
*/
export declare function unwrap<T>(item: T, set?: Set<unknown>): T;
export declare function createStore<T extends object = {}>(store: T | Store<T>): [get: Store<T>, set: StoreSetter<T>];
export declare function createStore<T extends object = {}>(fn: (store: T) => void, store: T | Store<T>): [get: Store<T>, set: StoreSetter<T>];
/**
* Creates a mutable derived value
*
* @see {@link https://github.com/solidjs/x-reactivity#createprojection}
*/
export declare function createProjection<T extends Object>(fn: (draft: T) => void, initialValue: T): Readonly<T>;

View File

@@ -0,0 +1 @@
export declare function isUndefined(value: any): value is undefined;

View File

@@ -0,0 +1,5 @@
Compiled version of: https://github.com/solidjs/signals/commits/main/
Head:
- SHA: 4d75d3f84ce22b560988f3b27a5065c0fd2e69a8
- Date: Apr 17, 2024

View File

@@ -0,0 +1,4 @@
import { Accessor, Setter } from "./2024-11-02/types/signals";
export type Signal<T> = Accessor<T> & { set: Setter<T>; reset: VoidFunction };
export type Signals = Awaited<typeof import("./wrapper.js").default>;

View File

@@ -0,0 +1,136 @@
// @ts-check
/**
* @import { SignalOptions } from "./2024-11-02/types/core/core"
* @import { getOwner as GetOwner, onCleanup as OnCleanup, Owner } from "./2024-11-02/types/core/owner"
* @import { createSignal as CreateSignal, createEffect as CreateEffect, Accessor, Setter, createMemo as CreateMemo, createRoot as CreateRoot, runWithOwner as RunWithOwner } from "./2024-11-02/types/signals";
* @import { Signal } from "./types";
*/
const importSignals = import("./2024-11-02/script.js").then((_signals) => {
const signals = {
createSolidSignal: /** @type {CreateSignal} */ (_signals.createSignal),
createSolidEffect: /** @type {CreateEffect} */ (_signals.createEffect),
createEffect: /** @type {CreateEffect} */ (compute, effect) => {
let dispose = /** @type {VoidFunction | null} */ (null);
// @ts-ignore
_signals.createEffect(compute, (v) => {
dispose?.();
signals.createRoot((_dispose) => {
dispose = _dispose;
effect(v);
});
signals.onCleanup(() => dispose?.());
});
signals.onCleanup(() => dispose?.());
},
createMemo: /** @type {CreateMemo} */ (_signals.createMemo),
createRoot: /** @type {CreateRoot} */ (_signals.createRoot),
getOwner: /** @type {GetOwner} */ (_signals.getOwner),
runWithOwner: /** @type {RunWithOwner} */ (_signals.runWithOwner),
onCleanup: /** @type {OnCleanup} */ (_signals.onCleanup),
flushSync: _signals.flushSync,
/**
* @template T
* @param {T} initialValue
* @param {SignalOptions<T> & {save?: {keyPrefix: string; key: string; serialize: (v: NonNullable<T>) => string; deserialize: (v: string) => NonNullable<T>}}} [options]
* @returns {Signal<T>}
*/
createSignal(initialValue, options) {
const [get, set] = this.createSolidSignal(
/** @type {any} */ (initialValue),
options,
);
// @ts-ignore
get.set = set;
// @ts-ignore
get.reset = () => set(initialValue);
if (options?.save) {
const save = options.save;
const paramKey = save.key;
const storageKey = `${save.keyPrefix}-${paramKey}`;
let serialized = /** @type {string | null} */ (null);
serialized = new URLSearchParams(window.location.search).get(paramKey);
if (serialized === null) {
serialized = localStorage.getItem(storageKey);
}
if (serialized) {
set(save.deserialize(serialized));
}
let firstEffect = true;
this.createEffect(get, (value) => {
if (!save) return;
if (!firstEffect) {
if (
value !== undefined &&
value !== null &&
(initialValue === undefined ||
initialValue === null ||
save.serialize(value) !== save.serialize(initialValue))
) {
localStorage.setItem(storageKey, save.serialize(value));
} else {
localStorage.removeItem(storageKey);
}
}
if (
value !== undefined &&
value !== null &&
(initialValue === undefined ||
initialValue === null ||
save.serialize(value) !== save.serialize(initialValue))
) {
writeParam(paramKey, save.serialize(value));
} else {
removeParam(paramKey);
}
firstEffect = false;
});
}
// @ts-ignore
return get;
},
};
return signals;
});
/**
* @param {string} key
* @param {string | undefined} value
*/
function writeParam(key, value) {
const urlParams = new URLSearchParams(window.location.search);
if (value !== undefined) {
urlParams.set(key, String(value));
} else {
urlParams.delete(key);
}
window.history.replaceState(
null,
"",
`${window.location.pathname}?${urlParams.toString()}`,
);
}
/**
* @param {string} key
*/
function removeParam(key) {
writeParam(key, undefined);
}
export default importSignals;

View File

@@ -0,0 +1,8 @@
URL:
https://github.com/leeoniya/uFuzzy/commits/main/dist
Head:
- SHA: 6bb27a8d8c41e4be5458844afc5c89f6c2399512
- Date: Feb 21, 2024
- Version: v1.0.14

Some files were not shown because too many files have changed in this diff Show More