Skip to content
On this page

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

NameDescription
TYPED_ARRAYSMapping of typed array constructors by name
arrayBufferToBase64Convert an ArrayBuffer to Base64 string
base64ToArrayBufferConvert a Base64 string to ArrayBuffer
getTypedArrayCreate a typed array from an ArrayBuffer by name

Browser

FunctionDescription
blobToDataURLConvert a blob to a data url.
downloadBlobDownload a blob as a file in the browser.
downloadFileDownload a file in the browser.
uploadFilePrompt the user to select a file or directory in the browser.

Color

FunctionDescription
LinearToSRGBConverts a single color channel from the linear color space to sRGB.
SRGBToLinearConverts a single color channel from the sRGB color space to linear.

DOM

FunctionDescription
createCanvasElementCreates a HTML canvas element.
createDivCreates an HTML div element.
createImageCreates a HTML image element from a url.
createScriptFromURLCreates a HTML script element from a url.
createStylesCreates a HTML style element with the given styles.

Decorators

FunctionDescription
onChangeDecorator 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.
serializeDecorator to mark a class property as serializable using the Serialization class.

Encryption

FunctionDescription
aesGcmDecryptDecrypts ciphertext encrypted with aesGcmEncrypt() using supplied password. (c) Chris Veness MIT Licence
aesGcmEncryptEncrypts 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

FunctionDescription
embedUrlRefsFind all URLs in svg, download them and replace with the URL in svg with the downloaded data URLs.
htmlToCanvasRenders an HTML string to a canvas. This is done by first embedding HTML into a svg and then rendering the svg to a canvas.
htmlToPngRenders an HTML string to a png. This is done by first embedding HTML into a svg and then rendering the svg to a png.
htmlToSvgEmbeds an HTML string into a svg tag and converts to svg string or svg as data url

Images

FunctionDescription
imageBitmapToBase64Convert an image ImageBitmap or CanvasImageSource to a base64 data url.
imageBitmapToBlobConvert an image ImageBitmap or CanvasImageSource to a blob.
imageBitmapToCanvasConvert an image ImageBitmap or CanvasImageSource to a new canvas with a max width. Good for resizing images keeping the aspect ratio and generating previews.
imageToCanvasConverts an HTML image to a canvas. This creates a new canvas element and draws the image on it.
imageUrlToImageDataDownloads/parse the image from an url/data url and draw to an ImageData object.

JS Object

NameDescription
FnCallercalls fn.call(obj) or fn() appropriately
copyPropsCopy properties from source to dest. Similar to Object.assign, but only copies properties that exist in source, dest and propList.
deepAccessObjectAccess property in an object using a string path. Similar to lodash.get
getKeyByValueFind the key of an object with a given value.
getOrCallGet value, but if it is a function, call it with args
getPropertyDescriptorGet property descriptor from object or its prototype chain
isPropertyWritableCheck if property is writable in object or its prototype chain
safeSetPropertySet value only if setter exists

Maths

FunctionDescription
absMaxReturns the number which is larger in absolute value.

Other

NameDescription
DamperThe 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.
JSUndoManagerMain class JSUndoManager
PointerDragHelperA helper class to handle pointer events and dispatch drag events: drag, dragStart and dragEnd with NDC coordinates and time.
SimpleEventDispatcherA simple event dispatcher with typed event types, see IEventDispatcher.
IDisposableDisposable interface for objects that can be disposed. Has a single method dispose
IEventA simple event interface with typed event types.
IEventDispatcherA simple event dispatcher interface with IEvent as event type.
IJSONSerializableInterface for objects that can be serialized to JSON, with to and from JSON methods
ImageCanvasOptionsOptions for imageToCanvas.
JSUndoManagerOptions-
AnyFunctionType for any function
AnyOptionsType for any object
ClassGeneric type for class.
FofFoF - Short for Function of - a generic type for function
JSUndoManagerCommand-
JSUndoManagerCommand1-
JSUndoManagerCommand2-
PartialPickPartial pick type with all keys optional
PartialRecordPartial record type with all keys optional
StringKeyOfExtract keys from object that are strings
ValOrArrType for a value of type T or an array of values of type T
ValOrArrOpType for a value of type `T
ValOrFuncType for a value of type T or a function that returns a value of type T
ValOrFuncOpType for a value of type T
blobToImageLoad a Blob or a file containing an image and return an HTMLImageElement.
canvasFlipYReturns 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.
clearBitClears the bit at the given position.
cloneScriptTagClones a script tag.
colorToDataUrlCreates an image data url from a color string.
findLastIndexlike Array.prototype.findIndex but from the end
getFileHandleOpen a handle to an existing file on the local file system.
getNewFileHandleCreate a handle to a new (text) file on the local file system.
imageDataToCanvasConverts 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))
includesAllReturns true if the array includes all the elements of the sub array
isWebpExportSupportedCheck if the browser supports exporting to webp, with the canvas.toDataURL('image/webp') method.
longestCommonPrefixFind the longest common prefix in an array of strings https://stackoverflow.com/questions/68702774/longest-common-prefix-in-javascript
mobileAndTabletCheckCheck if the browser is running on a mobile or tablet device.
objectHasOwnCheck if an object has a property. Same as Object.hasOwn or Object.hasOwnProperty
objectMapExecute 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.
objectMap2Shorthand 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.
onChange2Similar to onChange, but accepts any function and paramType defaults to 'void'. The function is called with no parameters. if 'void'
onChange3Similar to onChange, but accepts any function and paramType defaults to 'object'. The function is called with an object parameter: {key, value, oldValue, target}.
onChangeDispatchEventSimilar to onChange but dispatches an event instead of calling a function. Requires dispatchEvent to be defined on the target.
pathJoinJoin path parts with separator. Similar to PHP's pathJoin
prettyScrollbarStyles the default scrollbar to be more pretty and less intrusive (especially on dark backgrounds), (similar to MacOS)
readFileReads the raw text from a file.
remoteWorkerURLReturns 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
safeReplaceStringReplace a string in a text, optionally prepending, appending, replacing all occurrences, and/or calling a callback if the string is not found
serializableDecorator to mark a class as serializable using the Serialization class.
setInnerHTMLWithScriptsSets the innerHTML of an element and recreates all script tags so they are executed.
updateBitUpdates the bit at the given position to the given value.
uuidV4Generate a UUID v4 https://stackoverflow.com/a/53723395/2229899
verifyPermissionVerify the user has granted permission to read or write to the file, if permission hasn't been granted, request permission.
wrapThisFunctionCall 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()
wrapThisFunction2Call 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()
writeFileWrites the contents to disk.

SVGs

FunctionDescription
makeColorSvgReturns a data url for a 16x16 svg rectangle with the given color.
makeColorSvgCircleReturns a data url for a 16x16 svg circle with the given color.
makeTextSvgReturns a data url for a svg with the given text.
svgToCanvasRenders an SVG to a canvas.
svgToPngRenders an SVG to a png data url.

Serialization

NameDescription
SerializationSerialization class with static methods for serializing and deserializing objects. Properties and classes can be marked serializable by adding serialize and serializable decorators.
SerializerSerializer interface for primitive, array and struct/custom object types

Template Literals

FunctionDescription
cssA template literal tag that does nothing. Useful for syntax highlighting of CSS code.
glslA template literal tag that does nothing. Useful for syntax highlighting of GLSL code.
htmlA template literal tag that does nothing. Useful for syntax highlighting of HTML code.
svgUrlConverts 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

FunctionDescription
escapeRegExpEscape a string for use in a regular expression
getFilenameFromPathGet the filename from a path, similar to PHP's basename()
parseFileExtensionParse a file extension from a path
replaceAllReplace all occurrences of a string in another string
toCamelCaseConvert a string to camel case
toTitleCaseConvert a string to title case

Time

FunctionDescription
nowReturns the current time in milliseconds. If performance.now() is available, it is used, otherwise Date.now() is used.
timeoutReturns a promise that resolves after the given duration. Basically a setTimeout that returns a promise.

URL

FunctionDescription
getUrlQueryParamGet URL query parameter. If not found, return default value. Similar to PHP's $_GET
setUrlQueryParamSet URL query parameter. If value is null, remove parameter. Similar to PHP's $_GET

Made with ❤️ using the awesome vitepress