1.1.0 • Published 5 years ago

@monogrid/js-utils v1.1.0

Weekly downloads
99
License
MIT
Repository
gitlab
Last release
5 years ago

@monogrid/js-utils

This is a collection of generic Javascript utilities to help develpment on MONOGRID sites.

Installation

npm install --save @monogrid/js-utils

or

yarn add @monogrid/js-utils

Modules

Classes

FileUtils

A collection of File related utilities.

FileUtils~downloadFile(content, fileName, contentType)

Downloads a file to the user's machine.

Kind: inner method of FileUtils

ParamTypeDescription
contentStringThe content to be downloaded.
fileNameStringThe name of the file downloaded into the user's PC.
contentTypeStringThe file type.

FileUtils~loadFile(accept) ⇒ Promise.<Array>

Prompts the user to select a single file from his harddrive.

Kind: inner method of FileUtils
Returns: Promise.<Array> - Array of files selected by the user.

ParamTypeDescription
acceptStringAccept string to restrict file selection to certain file types.

FileUtils~loadJSON() ⇒ Promise.<String>

Prompts the user to select a single JSON file from his harddrive and returns the result of his selection.

Kind: inner method of FileUtils
Returns: Promise.<String> - The parsed JSON file.

FileUtils~loadImage() ⇒ Promise.<Image>

Prompts the user to select a single JSON file from his harddrive and returns the result of his selection

Kind: inner method of FileUtils
Returns: Promise.<Image> - The selected image object.

normalizeWheel

An utility function to normalize the mouseWheel input in the browser.

Typechecks:

normalizeWheel~normalizeWheel()

Mouse wheel (and 2-finger trackpad) support on the web sucks. It is complicated, thus this doc is long and (hopefully) detailed enough to answer your questions.

If you need to react to the mouse wheel in a predictable way, this code is like your bestest friend. hugs

As of today, there are 4 DOM event types you can listen to:

'wheel' -- Chrome(31+), FF(17+), IE(9+) 'mousewheel' -- Chrome, IE(6+), Opera, Safari 'MozMousePixelScroll' -- FF(3.5 only!) (2010-2013) -- don't bother! 'DOMMouseScroll' -- FF(0.9.7+) since 2003

So what to do? The is the best:

normalizeWheel.getEventType()

In your event callback, use this code to get sane interpretation of the deltas. This code will return an object with properties:

spinX -- normalized spin speed (use for zoom) - x plane spinY -- " - y plane pixelX -- normalized distance (to pixels) - x plane pixelY -- " - y plane

Wheel values are provided by the browser assuming you are using the wheel to scroll a web page by a number of lines or pixels (or pages). Values can lety significantly on different platforms and browsers, forgetting that you can scroll at different speeds. Some devices (like trackpads) emit more events at smaller increments with fine granularity, and some emit massive jumps with linear speed or acceleration.

This code does its best to normalize the deltas for you:

  • spin is trying to normalize how far the wheel was spun (or trackpad dragged). This is super useful for zoom support where you want to throw away the chunky scroll steps on the PC and make those equal to the slow and smooth tiny steps on the Mac. Key data: This code tries to resolve a single slow step on a wheel to 1.

  • pixel is normalizing the desired scroll delta in pixel units. You'll get the crazy differences between browsers, but at least it'll be in pixels!

  • positive value indicates scrolling DOWN/RIGHT, negative UP/LEFT. This should translate to positive value zooming IN, negative zooming OUT. This matches the newer 'wheel' event.

Why are there spinX, spinY (or pixels)?

  • spinX is a 2-finger side drag on the trackpad, and a shift + wheel turn with a mouse. It results in side-scrolling in the browser by default.

  • spinY is what you expect -- it's the classic axis of a mouse wheel.

  • I dropped spinZ/pixelZ. It is supported by the DOM 3 'wheel' event and probably is by browsers in conjunction with fancy 3D controllers .. but you know.

Implementation info:

Examples of 'wheel' event if you scroll slowly (down) by one step with an average mouse:

OS X + Chrome (mouse) - 4 pixel delta (wheelDelta -120) OS X + Safari (mouse) - N/A pixel delta (wheelDelta -12) OS X + Firefox (mouse) - 0.1 line delta (wheelDelta N/A) Win8 + Chrome (mouse) - 100 pixel delta (wheelDelta -120) Win8 + Firefox (mouse) - 3 line delta (wheelDelta -120)

On the trackpad:

OS X + Chrome (trackpad) - 2 pixel delta (wheelDelta -6) OS X + Firefox (trackpad) - 1 pixel delta (wheelDelta N/A)

On other/older browsers.. it's more complicated as there can be multiple and also missing delta values.

The 'wheel' event is more standard:

http://www.w3.org/TR/DOM-Level-3-Events/#events-wheelevents

The basics is that it includes a unit, deltaMode (pixels, lines, pages), and deltaX, deltaY and deltaZ. Some browsers provide other values to maintain backward compatibility with older events. Those other values help us better normalize spin speed. Example of what the browsers provide:

                     | event.wheelDelta | event.detail
   ------------------+------------------+--------------
     Safari v5/OS X  |       -120       |       0
     Safari v5/Win7  |       -120       |       0
    Chrome v17/OS X  |       -120       |       0
    Chrome v17/Win7  |       -120       |       0
           IE9/Win7  |       -120       |   undefined
    Firefox v4/OS X  |     undefined    |       1
    Firefox v4/Win7  |     undefined    |       3

Kind: inner method of normalizeWheel

NumberUtils

A collection of Number related utilities

NumberUtils~lerpNumber(v0, v1, t) ⇒ Number

Linearly interpolates a Number

Kind: inner method of NumberUtils
Returns: Number - Interpolation between v0 and v1 based on t

ParamTypeDescription
v0NumberInitial value
v1NumberFinal value
tNumberzero to one

NumberUtils~range(oldValue, oldMin, oldMax, newMin, newMax, clamped)

TODO: Documentation

Kind: inner method of NumberUtils

ParamType
oldValue*
oldMin*
oldMax*
newMin*
newMax*
clamped*

NumberUtils~clamp(value, min, max) ⇒ Number

Clamps a value between min and max values

Kind: inner method of NumberUtils
Returns: Number - A number clamped between min and max

ParamTypeDefaultDescription
valueNumberThe value to be clamped.
minNumber0Minimum value.
maxNumber1Maximum value.

NumberUtils~map(value, min, max)

TODO: Documentation

Kind: inner method of NumberUtils

ParamType
valueNumber
minNumber
maxNumber

NumberUtils~angleDistance(alpha, beta)

TODO: Documentation

Kind: inner method of NumberUtils

ParamType
alphaNumber
betaNumber

NumberUtils~angleDistanceSign(alpha, beta)

TODO: Documentation

Kind: inner method of NumberUtils

ParamType
alphaNumber
betaNumber

NumberUtils~smoothstep(min, max, value) ⇒ Number

Smoothstep implementation. https://en.wikipedia.org/wiki/Smoothstep

Kind: inner method of NumberUtils
Returns: Number - Value of the interpolation

ParamTypeDescription
minNumberInitial value
maxNumberFinal Value
valueNumber-

NumberUtils~mix(value1, value2, percent)

Similar to linear interpolation.

Kind: inner method of NumberUtils

ParamTypeDescription
value1NumberMinimum value.
value2NumberMaximum value.
percentNumberzero to one value percent

NumberUtils~sign(value) ⇒ Number

Returns the sign of a number in -1,0,1 form.

Kind: inner method of NumberUtils
Returns: Number - 0 if value is zero, -1 if value is less than 0, 1 otherwise

ParamTypeDescription
valueNumbera number to be tested

NumberUtils~randByPower(min, max, power, rd)

TODO: Documentation

Kind: inner method of NumberUtils

ParamTypeDefaultDescription
minNumber
maxNumber
powerNumber
rdNumberMath.randomOptional Random number generator

NumberUtils~mapToPower(value, min, max, power)

TODO: Documentation

Kind: inner method of NumberUtils

ParamType
valueNumber
minNumber
maxNumber
powerNumber

NumberUtils~distance(x1, y1, x2, y2) ⇒ Number

Computes distance between two points in 2D space.

Kind: inner method of NumberUtils
Returns: Number - Distance between x1,y1 and x2,y2

ParamTypeDescription
x1Numberx coordinate of first point
y1Numbery coordinate of first point
x2Numberx coordinate of second point
y2Numbery coordinate of second point

NumberUtils~distanceCompare(x1, y1, x2, y2) ⇒ Number

Not a real distance calculation. Useful to sort objects by distance ( much faster because no sqrt )

Kind: inner method of NumberUtils
Returns: Number - bogus distance between x1,y1 and x2,y2. DO NOT USE WHEN A REAL DISTANCE IS NEEDED

ParamTypeDescription
x1Numberx coordinate of first point
y1Numbery coordinate of first point
x2Numberx coordinate of second point
y2Numbery coordinate of second point

ObjectUtils

A collection of Object related utilities

ObjectUtils~isPlainObject(o) ⇒ Boolean

Determines if the object has been constructed using javascript generic {} syntax

Kind: inner method of ObjectUtils
Returns: Boolean - true if the object is a plain object, false otherwise.

ParamTypeDescription
o*The object to be tested.

Platform

Holds information on the Platform where this code is run

Properties

NameTypeDescription
mobileBooleanDevice is a mobile (includes tablets and phones)
phoneBooleanDevice is a phone (excludes tablets)
tabletBooleanDevice is a tablet (excludes phones)
androidBooleanDevice is Android based
iosBooleanDevice is iOS based
ipadBooleanDevice is an iPad
iphoneBooleanDevice is an iPhone
wphoneBooleanDevice is an Windows Phone
edgeBooleanBrowser is Microsoft Edge
firefoxBooleanBrowser is Mozilla Firefox
ie11BooleanBrowser is Microsoft Internet Explorer 11
safariBooleanBrowser is Safari
prerendererBooleanPage is visited by a prerenderer (like Phantom JS)
volumeBooleanDevice supports volume setting via js (iOS doesn't support this)

VueUtils

A collection of Vue.js related utilities

VueUtils~defineReactive(value, model)

Allows to define a set of reactive properties of "value" (Object) by looking into "model" (Object) and comparing the two

Kind: inner method of VueUtils

ParamType
valueObject
modelObject

ElasticNumber

Kind: global class
Properties

NameTypeDescription
valueNumberThe real value of the number.
targetNumberThe desired value of the number.
speedNumberThe speed at which the ElasticNumber will make value reach target.

new ElasticNumber()

An Utility class that allows to tween a numeric value (target) into a smoothed value (value)

Example

constructor () {
 this.myNumber = new ElasticNumber();
 this.time = new Date().getTime()
}

onUpdate () {
 const now = new Date().getTime()
 const delta = now - this.time
 this.myNumber.target = Math.random() * 100
 this.myNumber.update(delta);

 this.mySprite.x = this.myNumber.value
 this.time = now
}

ElasticNumber.update(delta)

Updates the ElasticNumber on tick. Value will be updated from target.

Kind: static method of ElasticNumber

ParamTypeDescription
deltaNumberdelta time in milliseconds

Gyroscope

Kind: global class
Properties

NameType
orientationXNumber
orientationYNumber
enabledBoolean

new Gyroscope()

An utility singleton that returns a device's Gyroscope data in the form of orientationX and orientationY.

The values are updated every frame and the system stops updating if it determines that the device does not have gyroscope capabilities.

RAF

Kind: global class

new RAF()

An utility singleton that holds all requestAnimationFrame subscribers and calls them in sequence each frame.

Example

import RAF from 'js-utils'

constructor () {
 RAF.add(this.onUpdate)
}

onUpdate () {
 // do stuff
}

onDestroy () {
 RAF.remove(this.onUpdate)
}

raF.add(listener)

Adds a subscriber to be called at each requestAnimationFrame

Kind: instance method of RAF

ParamTypeDescription
listenerfunctionA subscriber function

raF.remove(listener)

Removes a subscriber from requestAnimationFrame

Kind: instance method of RAF

ParamTypeDescription
listenerfunctionA subscriber function

LICENSE

Copyright (c) 2020, MONOGRID S.R.L.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.