@tldraw/utils
Version:
tldraw infinite canvas SDK (private utilities).
638 lines (523 loc) • 17.2 kB
TypeScript
import { default as isEqual } from 'lodash.isequal';
import { default as isEqualWith } from 'lodash.isequalwith';
import { default as throttle } from 'lodash.throttle';
import { default as uniq } from 'lodash.uniq';
/* Excluded from this release type: annotateError */
/* Excluded from this release type: areArraysShallowEqual */
/* Excluded from this release type: areObjectsShallowEqual */
/* Excluded from this release type: assert_2 */
/* Excluded from this release type: assertExists */
/**
* `@bind` is a decorator that binds the method to the instance of the class (legacy stage-2
* typescript decorators).
*
* @public
*/
export declare function bind<T extends (...args: any[]) => any>(target: object, propertyKey: string, descriptor: TypedPropertyDescriptor<T>): TypedPropertyDescriptor<T>;
/**
* `@bind` is a decorator that binds the method to the instance of the class (TC39 decorators).
*
* @public
*/
export declare function bind<This extends object, T extends (...args: any[]) => any>(originalMethod: T, context: ClassMethodDecoratorContext<This, T>): void;
/* Excluded from this release type: clearLocalStorage */
/* Excluded from this release type: clearSessionStorage */
/* Excluded from this release type: compact */
/**
* Debounce a function.
*
* @example
*
* ```ts
* const A = debounce(myFunction, 1000)
* ```
*
* @public
* @see source - https://gist.github.com/ca0v/73a31f57b397606c9813472f7493a940
*/
export declare function debounce<T extends unknown[], U>(callback: (...args: T) => PromiseLike<U> | U, wait: number): {
(...args: T): Promise<U>;
cancel(): void;
};
/**
* Deduplicate the items in an array
*
* @public
*/
export declare function dedupe<T>(input: T[], equals?: (a: any, b: any) => boolean): T[];
/** @public */
export declare const DEFAULT_SUPPORT_VIDEO_TYPES: readonly ("video/mp4" | "video/quicktime" | "video/webm")[];
/** @public */
export declare const DEFAULT_SUPPORTED_IMAGE_TYPES: readonly ("image/apng" | "image/avif" | "image/gif" | "image/jpeg" | "image/png" | "image/svg+xml" | "image/webp")[];
/** @public */
export declare const DEFAULT_SUPPORTED_MEDIA_TYPE_LIST: string;
/** @public */
export declare const DEFAULT_SUPPORTED_MEDIA_TYPES: readonly ("image/apng" | "image/avif" | "image/gif" | "image/jpeg" | "image/png" | "image/svg+xml" | "image/webp" | "video/mp4" | "video/quicktime" | "video/webm")[];
/* Excluded from this release type: deleteFromLocalStorage */
/* Excluded from this release type: deleteFromSessionStorage */
/** @public */
export declare interface ErrorAnnotations {
tags: Record<string, bigint | boolean | null | number | string | symbol | undefined>;
extras: Record<string, unknown>;
}
/** @public */
export declare interface ErrorResult<E> {
readonly ok: false;
readonly error: E;
}
/* Excluded from this release type: ExecutionQueue */
/* Excluded from this release type: exhaustiveSwitchError */
/** @public */
export declare type Expand<T> = T extends infer O ? {
[K in keyof O]: O[K];
} : never;
/* Excluded from this release type: fetch_2 */
/**
* Helpers for files
*
* @public
*/
export declare class FileHelpers {
/**
* @param url - The url of the file.
*/
static urlToArrayBuffer(url: string): Promise<ArrayBuffer>;
static urlToBlob(url: string): Promise<Blob>;
static urlToDataUrl(url: string): Promise<string>;
/**
* Convert a file to a base64 encoded data url.
*
* @example
*
* ```ts
* const A = FileHelpers.toDataUrl(myImageFile)
* ```
*
* @param file - The file as a blob.
*/
static blobToDataUrl(file: Blob): Promise<string>;
/**
* Convert a file to a unicode text string.
*
* @example
*
* ```ts
* const A = FileHelpers.fileToDataUrl(myTextFile)
* ```
*
* @param file - The file as a blob.
*/
static blobToText(file: Blob): Promise<string>;
static rewriteMimeType(blob: Blob, newMimeType: string): Blob;
static rewriteMimeType(blob: File, newMimeType: string): File;
}
/* Excluded from this release type: filterEntries */
/* Excluded from this release type: fpsThrottle */
/* Excluded from this release type: getChangedKeys */
/* Excluded from this release type: getErrorAnnotations */
/**
* Get the first item from an iterable Set or Map.
*
* @example
*
* ```ts
* const A = getFirstItem(new Set([1, 2, 3])) // 1
* const B = getFirstItem(
* new Map([
* ['a', 1],
* ['b', 2],
* ])
* ) // 1
* ```
*
* @param value - The iterable Set or Map.
* @public
*/
export declare function getFirstFromIterable<T = unknown>(set: Map<any, T> | Set<T>): T;
/* Excluded from this release type: getFromLocalStorage */
/* Excluded from this release type: getFromSessionStorage */
/**
* Hash an ArrayBuffer using the FNV-1a algorithm.
*
* @public
*/
export declare function getHashForBuffer(buffer: ArrayBuffer): string;
/**
* Hash a string using the FNV-1a algorithm.
*
* @public
*/
export declare function getHashForObject(obj: any): string;
/**
* Hash a string using the FNV-1a algorithm.
*
* @public
*/
export declare function getHashForString(string: string): string;
/**
* Get the index above a given index.
* @param below - The index below.
* @public
*/
export declare function getIndexAbove(below?: IndexKey | null | undefined): IndexKey;
/**
* Get the index below a given index.
* @param above - The index above.
* @public
*/
export declare function getIndexBelow(above?: IndexKey | null | undefined): IndexKey;
/**
* Get the index between two indices.
* @param below - The index below.
* @param above - The index above.
* @public
*/
export declare function getIndexBetween(below: IndexKey | null | undefined, above: IndexKey | null | undefined): IndexKey;
/**
* Get n number of indices, starting at an index.
* @param n - The number of indices to get.
* @param start - The index to start at.
* @public
*/
export declare function getIndices(n: number, start?: IndexKey): IndexKey[];
/**
* Get a number of indices above an index.
* @param below - The index below.
* @param n - The number of indices to get.
* @public
*/
export declare function getIndicesAbove(below: IndexKey | null | undefined, n: number): IndexKey[];
/**
* Get a number of indices below an index.
* @param above - The index above.
* @param n - The number of indices to get.
* @public
*/
export declare function getIndicesBelow(above: IndexKey | null | undefined, n: number): IndexKey[];
/**
* Get a number of indices between two indices.
* @param below - The index below.
* @param above - The index above.
* @param n - The number of indices to get.
* @public
*/
export declare function getIndicesBetween(below: IndexKey | null | undefined, above: IndexKey | null | undefined, n: number): IndexKey[];
/* Excluded from this release type: getOwnProperty */
/* Excluded from this release type: groupBy */
/* Excluded from this release type: hasOwnProperty */
/* Excluded from this release type: Image_2 */
/**
* A string made up of an integer part followed by a fraction part. The fraction point consists of
* zero or more digits with no trailing zeros. Based on
* {@link https://observablehq.com/@dgreensp/implementing-fractional-indexing}.
*
* @public
*/
export declare type IndexKey = string & {
__brand: 'indexKey';
};
/**
* Inverse lerp between two values. Given a value `n` in the range [a, b], returns a number between
* 0 and 1.
*
* @public
*/
export declare function invLerp(a: number, b: number, t: number): number;
/**
* Get whether a value is not undefined.
*
* @param value - The value to check.
* @public
*/
export declare function isDefined<T>(value: T): value is typeof value extends undefined ? never : T;
export { isEqual }
/* Excluded from this release type: isEqualAllowingForFloatingPointErrors */
export { isEqualWith }
/* Excluded from this release type: isNativeStructuredClone */
/**
* Get whether a value is null
*
* @param value - The value to check.
* @public
*/
export declare function isNonNull<T>(value: T): value is typeof value extends null ? never : T;
/**
* Get whether a value is nullish (null, undefined).
*
* @param value - The value to check.
* @public
*/
export declare function isNonNullish<T>(value: T): value is typeof value extends undefined ? never : typeof value extends null ? never : T;
/** @public */
export declare type JsonArray = JsonValue[];
/** @public */
export declare interface JsonObject {
[key: string]: JsonValue | undefined;
}
/** @public */
export declare type JsonPrimitive = boolean | null | number | string;
/** @public */
export declare type JsonValue = JsonArray | JsonObject | JsonPrimitive;
/* Excluded from this release type: last */
/**
* Linear interpolate between two values.
*
* @example
*
* ```ts
* const A = lerp(0, 1, 0.5)
* ```
*
* @public
*/
export declare function lerp(a: number, b: number, t: number): number;
/** @public */
export declare function lns(str: string): string;
/** @public */
export declare type MakeUndefinedOptional<T extends object> = Expand<{
[P in {
[K in keyof T]: undefined extends T[K] ? never : K;
}[keyof T]]: T[P];
} & {
[P in {
[K in keyof T]: undefined extends T[K] ? K : never;
}[keyof T]]?: T[P];
}>;
/* Excluded from this release type: mapObjectMapValues */
/* Excluded from this release type: maxBy */
/* Excluded from this release type: measureAverageDuration */
/* Excluded from this release type: measureCbDuration */
/* Excluded from this release type: measureDuration */
/**
* Helpers for media
*
* @public
*/
export declare class MediaHelpers {
/**
* Load a video from a url.
* @public
*/
static loadVideo(src: string): Promise<HTMLVideoElement>;
static getVideoFrameAsDataUrl(video: HTMLVideoElement, time?: number): Promise<string>;
/**
* Load an image from a url.
* @public
*/
static getImageAndDimensions(src: string): Promise<{
h: number;
image: HTMLImageElement;
w: number;
}>;
/**
* Get the size of a video blob
*
* @param blob - A SharedBlob containing the video
* @public
*/
static getVideoSize(blob: Blob): Promise<{
h: number;
w: number;
}>;
/**
* Get the size of an image blob
*
* @param blob - A Blob containing the image.
* @public
*/
static getImageSize(blob: Blob): Promise<{
h: number;
w: number;
}>;
static isAnimated(file: Blob): Promise<boolean>;
static isAnimatedImageType(mimeType: null | string): boolean;
static isStaticImageType(mimeType: null | string): boolean;
static isVectorImageType(mimeType: null | string): boolean;
static isImageType(mimeType: string): boolean;
static usingObjectURL<T>(blob: Blob, fn: (url: string) => Promise<T>): Promise<T>;
}
/* Excluded from this release type: mergeArraysAndReplaceDefaults */
/* Excluded from this release type: minBy */
/* Excluded from this release type: mockUniqueId */
/**
* Modulate a value between two ranges.
*
* @example
*
* ```ts
* const A = modulate(0, [0, 1], [0, 100])
* ```
*
* @param value - The interpolation value.
* @param rangeA - From [low, high]
* @param rangeB - To [low, high]
* @param clamp - Whether to clamp the the result to [low, high]
* @public
*/
export declare function modulate(value: number, rangeA: number[], rangeB: number[], clamp?: boolean): number;
/* Excluded from this release type: noop */
/* Excluded from this release type: objectMapEntries */
/* Excluded from this release type: objectMapEntriesIterable */
/* Excluded from this release type: objectMapFromEntries */
/* Excluded from this release type: objectMapKeys */
/* Excluded from this release type: objectMapValues */
/** @public */
export declare interface OkResult<T> {
readonly ok: true;
readonly value: T;
}
/* Excluded from this release type: omit */
/* Excluded from this release type: omitFromStackTrace */
/* Excluded from this release type: partition */
/** @public */
export declare class PerformanceTracker {
private startTime;
private name;
private frames;
private started;
private frame;
recordFrame: () => void;
start(name: string): void;
stop(): void;
isStarted(): boolean;
}
/** @public */
export declare class PngHelpers {
static isPng(view: DataView, offset: number): boolean;
static getChunkType(view: DataView, offset: number): string;
static readChunks(view: DataView, offset?: number): Record<string, {
dataOffset: number;
size: number;
start: number;
}>;
static parsePhys(view: DataView, offset: number): {
ppux: number;
ppuy: number;
unit: number;
};
static findChunk(view: DataView, type: string): {
dataOffset: number;
size: number;
start: number;
};
static setPhysChunk(view: DataView, dpr?: number, options?: BlobPropertyBag): Blob;
}
/* Excluded from this release type: promiseWithResolve */
/** @public */
export declare type RecursivePartial<T> = {
[P in keyof T]?: RecursivePartial<T[P]>;
};
/* Excluded from this release type: registerTldrawLibraryVersion */
/* Excluded from this release type: Required_2 */
/* Excluded from this release type: restoreUniqueId */
/** @public */
export declare type Result<T, E> = ErrorResult<E> | OkResult<T>;
/** @public */
export declare const Result: {
err<E>(error: E): ErrorResult<E>;
ok<T>(value: T): OkResult<T>;
};
/* Excluded from this release type: retry */
/**
* Seeded random number generator, using [xorshift](https://en.wikipedia.org/wiki/Xorshift). The
* result will always be betweeen -1 and 1.
*
* Adapted from [seedrandom](https://github.com/davidbau/seedrandom).
*
* @public
*/
export declare function rng(seed?: string): () => number;
/**
* Rotate the contents of an array.
*
* @public
*/
export declare function rotateArray<T>(arr: T[], offset: number): T[];
/** @public */
export declare const safeParseUrl: (url: string, baseUrl?: string | URL) => undefined | URL;
/* Excluded from this release type: setInLocalStorage */
/* Excluded from this release type: setInSessionStorage */
/* Excluded from this release type: sleep */
/** @public */
export declare function sortById<T extends {
id: any;
}>(a: T, b: T): -1 | 1;
/**
* Sort by index.
* @param a - An object with an index property.
* @param b - An object with an index property.
* @public */
export declare function sortByIndex<T extends {
index: IndexKey;
}>(a: T, b: T): -1 | 0 | 1;
/* Excluded from this release type: stringEnum */
/* Excluded from this release type: STRUCTURED_CLONE_OBJECT_PROTOTYPE */
/**
* Create a deep copy of a value. Uses the structuredClone API if available, otherwise uses JSON.parse(JSON.stringify()).
*
* @param i - The value to clone.
* @public */
declare const structuredClone_2: <T>(i: T) => T;
export { structuredClone_2 as structuredClone }
export { throttle }
/* Excluded from this release type: throttleToNextFrame */
/** @public */
export declare class Timers {
private timeouts;
private intervals;
private rafs;
constructor();
/** @public */
setTimeout(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number;
/** @public */
setInterval(contextId: string, handler: TimerHandler, timeout?: number, ...args: any[]): number;
/** @public */
requestAnimationFrame(contextId: string, callback: FrameRequestCallback): number;
/** @public */
dispose(contextId: string): void;
disposeAll(): void;
forContext(contextId: string): {
dispose: () => void;
requestAnimationFrame: (callback: FrameRequestCallback) => number;
setInterval: (handler: TimerHandler, timeout?: number, ...args: any[]) => number;
setTimeout: (handler: TimerHandler, timeout?: number, ...args: any[]) => number;
};
}
export { uniq }
/**
* Generate a unique id.
*
* @example
*
* ```ts
* const id = uniqueId()
* ```
*
* @public
*/
export declare function uniqueId(size?: number): string;
/* Excluded from this release type: validateIndexKey */
/* Excluded from this release type: warnDeprecatedGetter */
/* Excluded from this release type: warnOnce */
/**
* A micro cache used when storing records in memory (using a WeakMap).
* @public
*/
export declare class WeakCache<K extends object, V> {
/** The map of items to their cached values. */
items: WeakMap<K, V>;
/**
* Get the cached value for a given record. If the record is not present in the map, the callback
* will be used to create the value (with the result being stored in the cache for next time).
*
* @param item - The item to get.
* @param cb - The callback to use to create the value when a cached value is not found.
*/
get<P extends K>(item: P, cb: (item: P) => V): NonNullable<V>;
}
/**
* The index key for the first index - 'a0'.
* @public
*/
export declare const ZERO_INDEX_KEY: IndexKey;
export { }