Assorted JavaScript services.
$ npm install -S @haensl/services
$ yarn add @haensl/services
-
Use services in your code:
import { platform } from '@haensl/services';
if (platform.hasWindow) {
// code that relies on existance
// of a global window object
}
- component: Wraps utility functions useful in a component context, e.g. generate stateful class names.
- error: Wraps utility functions pertaining to
Error
s. - numbers: Wraps utility functions pertaining to numbers, e.g. generating random numbers.
- platform: Wraps information about the platform, e.g. is there a
window
? what is the current scroll position? is there local storage? etc. - throttle: Wraps functionality to throttle function execution, e.g.
debounce
.
The component service wraps utility functions useful when working with components.
Returns a class list string composed of the basename
followed by the basename
concatenated with any truthy properties in states
, wherein the concatenation is separated by separator
(default: two dashes, --
).
import React, { useState } from 'react';
import { component } from '@haensl/services';
const MyComponent = () => {
const [isDoingStuff, setIsDoingStuff] = useState(false);
// code manipulating isDoingStuff
const cn = component.className({
isDoingStuff
}, 'MyComponent');
// if isDoingStuff is true
// cn === "MyComponent MyComponent--isDoingStuff"
// else
// cn === "MyComponent"
return (
<div className={ cn }> // className="MyComponent MyComponent--isDoingStuff"
// ...
</div>
);
};
Sets the value
of an HTMLInputElement and triggers an 'input'
event. This is for example useful in cases where frameworks' event management makes it hard to programmatically trigger events that adhere to the native JavaScript event behaviour.
import React, { useEffect, useRef, useState } from 'react';
import { component } from '@haensl/services';
const MyComponent = ({
defaultValue = '',
onChange
}) => {
const [value, setValue] = useState(defaultValue);
const input = useRef();
useEffect(() => {
if (!input.current) {
return;
}
component.setInputValue(input.current, defaultValue);
}, [defaultValue]);
return (
<div>
// ...
<input
ref={ input }
onChange={ onChange }
value={ value }
/>
</div>
);
};
error service>
The error service wraps utility functions pertaining to Error
s.
Attaches HTTP Response meta data to an Error
. This is an async
operation.
const response = await fetch('/some/api');
if (!response.ok) {
const error = new Error('Failing to fetch from API!');
// extract metadata such as headers, status, etc from response and attach to error object.
await attach(response, error);
throw error;
}
The numbers service wraps utility functions pertaining to numbers, e.g. random number generation.
Returns a random floating point number between min (inclusive) and max (exclusive). Due to JavaScript rounding, the value will never equal max
.
import { numbers } from '@haensl/services';
// generates a random number between 0 (inclusive) and 1 (exclusive)
const n = numbers.rand();
// generates a random number between 1 (inclusive) and 300 (exclusive)
const k = numbers.rand({ min: 1, max: 300});
Returns a random integer number between min and max (inclusive).
import { numbers } from '@haensl/services';
// generates a random number between 0 (inclusive) and 3 (inclusive)
const n = numbers.randInt({ min: 0, max: 3 });
The platform service wraps information about the current runtime platform, e.g. is there a window
? what is the current scroll position? is there local storage? etc.
Boolean, indicating whether or not the current runtime provides a global document
object.
import { platform } from '@haensl/services';
if (platform.hasDocument) {
// code that relies on global document object,
// e.g.
if (/utf-8/i.test(document.characterSet)) {
// do stuff that requires utf-8 encoding
}
}
Boolean, indicating whether or not the current runtime provides a global document.documentElement
object.
import { platform } from '@haensl/services';
if (platform.hasDocumentElement) {
// code that relies on the existence of document.documentElement,
// e.g.
if (!(document.documentElement instanceof HTMLHtmlElement)) {
// do stuff the XML way, because we're not in an HTML document
}
}
Boolean, indicating whether or not the current runtime provides a global window.localStorage
object.
import { platform } from '@haensl/services';
if (platform.hasLocalStorage) {
// code that relies on local storage,
// e.g.
window.localStorage.setItem('my-data', data);
} else {
// code that saves data elsewhere
}
Boolean, indicating whether or not the current runtime provides a global window.sessionStorage
object.
import { platform } from '@haensl/services';
if (platform.hasSessionStorage) {
// code that relies on session storage,
// e.g.
window.sessionStorage.setItem('my-data', data);
} else {
// code that saves data elsewhere
}
Boolean, indicating whether or not the current runtime provides a global window
object.
import { platform } from '@haensl/services';
if (platform.hasWindow) {
// code that relies on the global window object,
// e.g.
myComponent.scrollX = window.scrollX + 100;
}
Returns an object with properties x
and y
reflecting the current scroll position if applicaple, null
otherwise.
import { platform } from '@haensl/services';
if (platform.hasWindow) {
window.addEventListener('scroll', () => {
console.log(platform.scrollPosition());
// will print objects like
// { x: 0, y: 10 }
});
} else if (!platform.hasDocument) {
console.log(platform.scrollPosition());
// will print null since there is neither document nor window!
}
The throttle service wraps functionality used to throttle function execution, e.g. debounce
.
Returns a new function that debounces fn
by debounceMs
milliseconds. Debouncing means fn
is only executed if there are no calls for debounceMs
milliseconds.
import { throttle, platform } from '@haensl/services';
if (platform.hasWindow) {
// only logs when there are no calls
// for 50 milliseconds
const onScroll = throttle.debounce(() => {
console.log(platform.scrollPosition());
}, 50);
window.addEventListener('scroll', onScroll);
}