Skip to content

repalash/ts-browser-helpers

Repository files navigation

TS Browser Helpers

NPM Package License: Apache 2.0

A collection of utility classes, functions and types for javascript/typescript projects, for use in the browser.

Installation

npm install ts-browser-helpers

Docs

API documentation

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
IDialogWrapper A simple interface for dialog wrappers that can be used to abstract away the browser's built-in dialog methods or custom implementations.
htmlDialogWrapper A custom dialog wrapper that uses HTML elements to create alert, prompt, and confirm dialogs inspired by radix/shadcn style. Provides API similar to the browser's built-in dialog methods, with better UI and more options.
windowDialogWrapper A dialog wrapper that uses the browser's built-in window.alert, window.prompt, and window.confirm methods.
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
colorToDataUrl Creates an image data url from a color string.
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
cloneScriptTag Clones a script tag.
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.
setInnerHTMLWithScripts Sets the innerHTML of an element and recreates all script tags so they are executed.

Decorators

Function Description
OnChangeDispatchEventType Type of the event dispatched by onChangeDispatchEvent.
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.
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.
serializable Decorator to mark a class as serializable using the Serialization class.
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.

Event

Name Description
SimpleEventDispatcher A simple event dispatcher with typed event types, see IEventDispatcher.
IEvent A simple event interface with typed event types.
IEventDispatcher A simple event dispatcher interface with IEvent as event type.

File System

Function Description
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.
readFile Reads the raw text from a file.
verifyPermission Verify the user has granted permission to read or write to the file, if permission hasn't been granted, request permission.
writeFile Writes the contents to disk.

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
ImageCanvasOptions Options for imageToCanvas.
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.
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.
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))
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.
isWebpExportSupported Check if the browser supports exporting to webp, with the canvas.toDataURL('image/webp') method.

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
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.
safeSetProperty Set value only if setter exists

Maths

Function Description
absMax Returns the number which is larger in absolute value.
clearBit Clears the bit at the given position.
updateBit Updates the bit at the given position to the given value.
uuidV4 Generate a UUID v4 https://stackoverflow.com/a/53723395/2229899

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.
PointerDragHelper A helper class to handle pointer events and dispatch drag events: drag, dragStart and dragEnd with NDC coordinates and time.
findLastIndex like Array.prototype.findIndex but from the end
includesAll Returns true if the array includes all the elements of the sub array
mobileAndTabletCheck Check if the browser is running on a mobile or tablet device.
prettyScrollbar Styles the default scrollbar to be more pretty and less intrusive (especially on dark backgrounds), (similar to MacOS)
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()

Primitive

Name Description
PrimitiveValObject Primitive value compatible object interface.
PrimitiveVal Primitive value type. It can be a string, number, boolean, null, an object that implements the PrimitiveValObject interface, or an array of primitive values.
clonePrimitive Clones a primitive value or an object that implements the PrimitiveValObject interface.
copyPrimitive Copies a primitive value or an object that implements the PrimitiveValObject interface. If the target is an array, it will copy the values from the source array to the target array. If the target is an object that implements the PrimitiveValObject interface, it will call the copy method on the target. If the target is not an array or an object that implements the PrimitiveValObject interface, it will return a clone of the source value.
equalsPrimitive Checks if two primitive values are equal.

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
escapeHtml Escape HTML special characters in a string
escapeRegExp Escape a string for use in a regular expression
getFilenameFromPath Get the filename from a path, similar to PHP's basename()
longestCommonPrefix Find the longest common prefix in an array of strings https://stackoverflow.com/questions/68702774/longest-common-prefix-in-javascript
parseFileExtension Parse a file extension from a path
replaceAll Replace all occurrences of a string in another string
safeReplaceString Replace a string in a text, optionally prepending, appending, replacing all occurrences, and/or calling a callback if the string is not found
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.

Type

Name Description
IDisposable Disposable interface for objects that can be disposed. Has a single method dispose
IJSONSerializable Interface for objects that can be serialized to JSON, with to and from JSON methods
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
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

URL

Function Description
getUrlQueryParam Get URL query parameter. If not found, return default value. Similar to PHP's $_GET
pathJoin Join path parts with separator. Similar to PHP's pathJoin
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
setUrlQueryParam Set URL query parameter. If value is null, remove parameter. Similar to PHP's $_GET

Undo

Name Description
JSUndoManager Main class JSUndoManager
ActionUndoCommand Interface for a command that performs an action(function).
JSUndoManagerOptions JSUndoManagerOptions interface that defines the options for the JSUndoManager class.
SetValueUndoCommand Interface for a command that sets a value with a binding.
SetValueUndoCommandProps Properties for the SetValueUndoCommand.
JSUndoManagerCommand Combined command type for JSUndoManager that can be either a simple command or a preset command.
JSUndoManagerCommand1 Simple command interface for JSUndoManager with explicit actions
JSUndoManagerCommand2 Command interface for JSUndoManager with a type field.
recordUndoCommand Records an undo command in the undo manager, supports merging of subsequent setValue commands
setValueUndoCommand Sets a value in the target object with undo/redo support.

Used in

  • WebGi - Premium Photo-realistic 3D rendering framework and tools for web applications and online commerce.
  • ThreePipe - A 3D viewer framework for the web.
  • uiconfig.js - A simple, lightweight and easy to use UI configuration library for javascript/typescript projects.

About

A collection of utility classes, functions and types for javascript/typescript projects, for use in the browser.

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors