TypeScript and Browser Helpers
Lots of Browser Helpers and typescript utilities
Github - https://github.com/repalash/ts-browser-helpers
Docs - https://repalash.com/ts-browser-helpers/
ArrayBuffer
Name | Description |
---|---|
TYPED_ARRAYS | Mapping of typed array constructors by name |
arrayBufferToBase64 | Convert an ArrayBuffer to Base64 string |
base64ToArrayBuffer | Convert a Base64 string to ArrayBuffer |
getTypedArray | Create a typed array from an ArrayBuffer by name |
Browser
Function | Description |
---|---|
blobToDataURL | Convert a blob to a data url. |
downloadBlob | Download a blob as a file in the browser. |
downloadFile | Download a file in the browser. |
uploadFile | Prompt the user to select a file or directory in the browser. |
Color
Function | Description |
---|---|
LinearToSRGB | Converts a single color channel from the linear color space to sRGB. |
SRGBToLinear | Converts a single color channel from the sRGB color space to linear. |
DOM
Function | Description |
---|---|
createCanvasElement | Creates a HTML canvas element. |
createDiv | Creates an HTML div element. |
createImage | Creates a HTML image element from a url. |
createScriptFromURL | Creates a HTML script element from a url. |
createStyles | Creates a HTML style element with the given styles. |
Decorators
Function | Description |
---|---|
onChange | Decorator that redefines a property with getter and setter, and calls a function when the property is changed. Parameters passed to the function are the property key and the new value. |
serialize | Decorator to mark a class property as serializable using the Serialization class. |
Encryption
Function | Description |
---|---|
aesGcmDecrypt | Decrypts ciphertext encrypted with aesGcmEncrypt() using supplied password. (c) Chris Veness MIT Licence |
aesGcmEncrypt | Encrypts plaintext using AES-GCM with supplied password, for decryption with aesGcmDecrypt(). (c) Chris Veness MIT Licence https://gist.github.com/chrisveness/43bcda93af9f646d083fad678071b90a Modified to work with Uint8Array and string content. |
HTML To Image
Function | Description |
---|---|
embedUrlRefs | Find all URLs in svg, download them and replace with the URL in svg with the downloaded data URLs. |
htmlToCanvas | Renders an HTML string to a canvas. This is done by first embedding HTML into a svg and then rendering the svg to a canvas. |
htmlToPng | Renders an HTML string to a png. This is done by first embedding HTML into a svg and then rendering the svg to a png. |
htmlToSvg | Embeds an HTML string into a svg tag and converts to svg string or svg as data url |
Images
Function | Description |
---|---|
imageBitmapToBase64 | Convert an image ImageBitmap or CanvasImageSource to a base64 data url. |
imageBitmapToBlob | Convert an image ImageBitmap or CanvasImageSource to a blob. |
imageBitmapToCanvas | Convert an image ImageBitmap or CanvasImageSource to a new canvas with a max width. Good for resizing images keeping the aspect ratio and generating previews. |
imageToCanvas | Converts an HTML image to a canvas. This creates a new canvas element and draws the image on it. |
imageUrlToImageData | Downloads/parse the image from an url/data url and draw to an ImageData object. |
JS Object
Name | Description |
---|---|
FnCaller | calls fn.call(obj) or fn() appropriately |
copyProps | Copy properties from source to dest. Similar to Object.assign, but only copies properties that exist in source, dest and propList. |
deepAccessObject | Access property in an object using a string path. Similar to lodash.get |
getKeyByValue | Find the key of an object with a given value. |
getOrCall | Get value, but if it is a function, call it with args |
getPropertyDescriptor | Get property descriptor from object or its prototype chain |
isPropertyWritable | Check if property is writable in object or its prototype chain |
safeSetProperty | Set value only if setter exists |
Maths
Function | Description |
---|---|
absMax | Returns the number which is larger in absolute value. |
Other
Name | Description |
---|---|
Damper | The Damper class is a generic second-order critically damped system that does one linear step of the desired length of time. The only parameter is DECAY_MILLISECONDS. This common parameter makes all states converge at the same rate regardless of scale. xNormalization is a number to provide the rough scale of x, such that NIL_SPEED clamping also happens at roughly the same convergence for all states. |
JSUndoManager | Main class JSUndoManager |
PointerDragHelper | A helper class to handle pointer events and dispatch drag events: drag , dragStart and dragEnd with NDC coordinates and time. |
SimpleEventDispatcher | A simple event dispatcher with typed event types, see IEventDispatcher. |
IDisposable | Disposable interface for objects that can be disposed. Has a single method dispose |
IEvent | A simple event interface with typed event types. |
IEventDispatcher | A simple event dispatcher interface with IEvent as event type. |
IJSONSerializable | Interface for objects that can be serialized to JSON, with to and from JSON methods |
ImageCanvasOptions | Options for imageToCanvas. |
JSUndoManagerOptions | - |
AnyFunction | Type for any function |
AnyOptions | Type for any object |
Class | Generic type for class. |
Fof | FoF - Short for Function of - a generic type for function |
JSUndoManagerCommand | - |
JSUndoManagerCommand1 | - |
JSUndoManagerCommand2 | - |
PartialPick | Partial pick type with all keys optional |
PartialRecord | Partial record type with all keys optional |
StringKeyOf | Extract keys from object that are strings |
ValOrArr | Type for a value of type T or an array of values of type T |
ValOrArrOp | Type for a value of type `T |
ValOrFunc | Type for a value of type T or a function that returns a value of type T |
ValOrFuncOp | Type for a value of type T |
blobToImage | Load a Blob or a file containing an image and return an HTMLImageElement. |
canvasFlipY | Returns a new canvas with the image/canvas-content flipped vertically. Useful for putImageData(as it does not respect scale and translate) and WebGL textures, which are flipped vertically. |
clearBit | Clears the bit at the given position. |
cloneScriptTag | Clones a script tag. |
colorToDataUrl | Creates an image data url from a color string. |
findLastIndex | like Array.prototype.findIndex but from the end |
getFileHandle | Open a handle to an existing file on the local file system. |
getNewFileHandle | Create a handle to a new (text) file on the local file system. |
imageDataToCanvas | Converts an ImageData to a canvas. This creates a new canvas element and draws the image data on it. Image Data can be created from image pixels like from gl.readPixels This can be used to convert a WebGL texture/render target to a canvas/data url. Note: if the output is flipped, use canvasFlipY after this, like canvasFlipY(imageDataToCanvas(imageData)) |
includesAll | Returns true if the array includes all the elements of the sub array |
isWebpExportSupported | Check if the browser supports exporting to webp, with the canvas.toDataURL('image/webp') method. |
longestCommonPrefix | Find the longest common prefix in an array of strings https://stackoverflow.com/questions/68702774/longest-common-prefix-in-javascript |
mobileAndTabletCheck | Check if the browser is running on a mobile or tablet device. |
objectHasOwn | Check if an object has a property. Same as Object.hasOwn or Object.hasOwnProperty |
objectMap | Execute a function on each property of an object and return the result as a new object This allows in place modification of the object. To create a new object, set inPlace to false, or use objectMap2 to modify the keys as well Similar to Array.map but for objects. |
objectMap2 | Shorthand for Object.fromEntries(Object.entries(obj).map(fn)) Similar to objectMap but uses Object.fromEntries to create the new object, so keys can also be changed. |
onChange2 | Similar to onChange, but accepts any function and paramType defaults to 'void'. The function is called with no parameters. if 'void' |
onChange3 | Similar to onChange, but accepts any function and paramType defaults to 'object'. The function is called with an object parameter: {key, value, oldValue, target} . |
onChangeDispatchEvent | Similar to onChange but dispatches an event instead of calling a function. Requires dispatchEvent to be defined on the target. |
pathJoin | Join path parts with separator. Similar to PHP's pathJoin |
prettyScrollbar | Styles the default scrollbar to be more pretty and less intrusive (especially on dark backgrounds), (similar to MacOS) |
readFile | Reads the raw text from a file. |
remoteWorkerURL | Returns a blob:// URL which points to a javascript file which will call importScripts with the given URL, to be used for cross-origin workers. https://stackoverflow.com/questions/21913673/execute-web-worker-from-different-origin |
safeReplaceString | Replace a string in a text, optionally prepending, appending, replacing all occurrences, and/or calling a callback if the string is not found |
serializable | Decorator to mark a class as serializable using the Serialization class. |
setInnerHTMLWithScripts | Sets the innerHTML of an element and recreates all script tags so they are executed. |
updateBit | Updates the bit at the given position to the given value. |
uuidV4 | Generate a UUID v4 https://stackoverflow.com/a/53723395/2229899 |
verifyPermission | Verify the user has granted permission to read or write to the file, if permission hasn't been granted, request permission. |
wrapThisFunction | Call f1 before calling f2 Sample usage const logRender = ()=>console.log('render') obj.render = wrapThisFunction(logRender, obj.beforeRender) // now calling obj.beforeRender(), will log 'render' and then call obj.beforeRender() |
wrapThisFunction2 | Call f1 with the same params as f2 before calling f2 Sample usage const logRender = ()=>console.log('render') obj.render = wrapThisFunction(logRender, obj.beforeRender) // now calling obj.beforeRender(), will log 'render' and then call obj.beforeRender() |
writeFile | Writes the contents to disk. |
SVGs
Function | Description |
---|---|
makeColorSvg | Returns a data url for a 16x16 svg rectangle with the given color. |
makeColorSvgCircle | Returns a data url for a 16x16 svg circle with the given color. |
makeTextSvg | Returns a data url for a svg with the given text. |
svgToCanvas | Renders an SVG to a canvas. |
svgToPng | Renders an SVG to a png data url. |
Serialization
Name | Description |
---|---|
Serialization | Serialization class with static methods for serializing and deserializing objects. Properties and classes can be marked serializable by adding serialize and serializable decorators. |
Serializer | Serializer interface for primitive, array and struct/custom object types |
Template Literals
Function | Description |
---|---|
css | A template literal tag that does nothing. Useful for syntax highlighting of CSS code. |
glsl | A template literal tag that does nothing. Useful for syntax highlighting of GLSL code. |
html | A template literal tag that does nothing. Useful for syntax highlighting of HTML code. |
svgUrl | Converts an SVG string to data url. This is useful for creating images from SVGs, or using SVGs in CSS. To use put in template string: url(${svgUrl`<svg>...</svg>`}) |
Text
Function | Description |
---|---|
escapeRegExp | Escape a string for use in a regular expression |
getFilenameFromPath | Get the filename from a path, similar to PHP's basename() |
parseFileExtension | Parse a file extension from a path |
replaceAll | Replace all occurrences of a string in another string |
toCamelCase | Convert a string to camel case |
toTitleCase | Convert a string to title case |
Time
Function | Description |
---|---|
now | Returns the current time in milliseconds. If performance.now() is available, it is used, otherwise Date.now() is used. |
timeout | Returns a promise that resolves after the given duration. Basically a setTimeout that returns a promise. |
URL
Function | Description |
---|---|
getUrlQueryParam | Get URL query parameter. If not found, return default value. Similar to PHP's $_GET |
setUrlQueryParam | Set URL query parameter. If value is null, remove parameter. Similar to PHP's $_GET |