JavaScript framework
We provide a JavaScript framework intended to help you in the development of adapters, overlays and docks. Below you will find all the exposed constants, functions and classes, grouped by category.
Common code
This code is exported by all the JavaScript files listed below.
Constants
name | type | value |
---|---|---|
load | string | 'load' |
session | string | 'session' |
alerts | string | 'alerts' |
chat | string | 'chat' |
other | string | 'other' |
facebook | string | 'facebook' |
tiktok | string | 'tiktok' |
trovo | string | 'trovo' |
twitch | string | 'twitch' |
youtube | string | 'youtube' |
event | string | 'event' |
merch | string | 'merch' |
tip | string | 'tip' |
redemption | string | 'redemption' |
reward | string | 'reward' |
subscriber | string | 'subscriber' |
cheer | string | 'cheer' |
elixir | string | 'elixir' |
follower | string | 'follower' |
raid | string | 'raid' |
sponsor | string | 'sponsor' |
superChat | string | 'superchat' |
fan | string | 'fan' |
like | string | 'like' |
videoLike | string | 'videolike' |
supporter | string | 'supporter' |
share | string | 'share' |
stars | string | 'stars' |
gift | string | 'gift' |
message | string | 'message' |
deleteMessage | string | 'delete-message' |
deleteMessages | string | 'delete-messages' |
botCounter | string | 'bot:counter' |
URL
parameters
The parameters
object contains the parameters applied to the current page through the query string, except the lang
, fonts
, theme
and zoom
parameters. This object is safe for indexing. The system parameters are described in detail on the page dedicated to overlays.
Events
Listener
The Listener
class is used to make it easier to listen to events. Its TypeScript signature is as follows:
type Callback = (event: Event) => any;
declare class Listener {
constructor(event: string, callback: Callback, host?: EventTarget, passive?: false);
on(): void;
off(): void;
}
Parameters
name | description | optional |
---|---|---|
event | Name of the event to listen to | no |
callback | Function called on event | no |
host | Object to listen to the event on | yes (window by default) |
passive | Defines whether the event is passive (true ) or not (false ) | yes (true by default) |
Methods
name | description |
---|---|
on | Start listening for the event (called on initialization) |
off | Stop listening to the event |
Example
const listener = new Listener('click', console.log, document.body);
listener.off();
listener.on();
adapters.js file
The adapters.js file contains everything that may be useful for adapter development, in addition to the common code described above.
<script type="module">
import {} from 'https://obs.multistream.tools/v1/adapters.js';
</script>
Do not add any hash or query string to the file import URL, otherwise the module would be executed several times instead of just once, which could give rise to unwanted side effects.
Constants
name | type | value |
---|---|---|
wildCard | string | '*' |
onWidgetLoad | string | 'onWidgetLoad' |
onEventReceived | string | 'onEventReceived' |
onSessionUpdate | string | 'onSessionUpdate' |
Platforms
The Platform
, Facebook
, Trovo
, Twitch
and YouTube
classes are described on the page dedicated to platforms.
Adapters
The Adapter
, StreamElementsAdapter
, FacebookStreamElementsAdapter
, TrovoStreamElementsAdapter
, TwitchStreamElementsAdapter
, YouTubeStreamElementsAdapter
and TikFinityAdapter
classes are described on the page dedicated to adapters.
overlay.js file
The overlay.js file contains everything that can be useful for developing overlays and docks, in addition to the common code described above.
<script type="module">
import {} from 'https://obs.multistream.tools/v1/overlay.js';
</script>
Do not add any hash or query string to the file import URL, otherwise the module would be executed several times instead of just once, which could give rise to unwanted side effects.
Constants
name | type | value |
---|---|---|
mute | string | 'mute' |
pause | string | 'pause' |
skip | string | 'skip' |
Shortcuts
name | value |
---|---|
from | Array.from |
isArray | Array.isArray |
parse | JSON.parse |
stringify | JSON.stringify |
assign | Object.assign |
create | Object.create |
entries | Object.entries |
keys | Object.keys |
origin | location.origin |
pathname | location.pathname |
search | location.search |
html | document.documentElement |
head | document.head |
body | document.body |
Utilities
isString
The isString
function allows you to know whether the value passed as a parameter is a string or not. Its TypeScript signature is as follows:
declare const isString: (value: any) => boolean;
Parameters
name | description | optional |
---|---|---|
value | Value to test | no |
Example
isString(''); // true
isString({}); // false
isNumber
The isNumber
function allows you to know whether the value passed as a parameter is a number or not. Its TypeScript signature is as follows:
declare const isNumber: (value: any) => boolean;
Parameters
name | description | optional |
---|---|---|
value | Value to test | no |
Example
isNumber(1); // true
isNumber('1'); // false
isTrue
The isTrue
function allows you to know whether the value passed as a parameter is true
or not. Its TypeScript signature is as follows:
declare const isTrue: (value: any) => boolean;
Parameters
name | description | optional |
---|---|---|
value | Value to test | no |
Example
isTrue(true); // true
isTrue('true'); // false
isTrue(new Boolean(true)); // false
validate
The validate
function allows you to test whether the value passed as a parameter satisfies a given predicate; if the predicate returns true
, the call to the validate
function returns the value passed as a parameter. Its TypeScript signature is as follows:
type Predicate = (value: any) => boolean;
declare const validate: (predicate: Predicate, value: any, fallback?: any) => any;
Parameters
name | description | optional |
---|---|---|
predicate | Test predicate | no |
value | Value to test | no |
fallback | Default value | yes (undefined by default) |
Example
let { exampleParam } = parameters;
exampleParam = validate(isString, exampleParam, ''); // `exampleParam` or `''`
validateString
The validateString
function allows you to test whether the value passed as a parameter is a string; if so, the call to the validateString
function returns the value passed as a parameter. Its TypeScript signature is as follows:
declare const validateString: (value: any, fallback?: any) => any;
Parameters
name | description | optional |
---|---|---|
value | Value to test | no |
fallback | Default value | yes ('' by default) |
Example
let { exampleParamA, exampleParamB } = parameters;
exampleParamA = validateString(exampleParamA); // `exampleParamA` or `''`
exampleParamB = validateString(exampleParamB, 'fallback'); // `exampleParamB` or `'fallback'`
validateString('', 'fallback'); // 'fallback'
validateNumber
The validateNumber
function allows you to test whether the value passed as a parameter is a number; if so, the call to the validateNumber
function returns the value passed as a parameter. Its TypeScript signature is as follows:
declare const validateNumber: (value: any, fallback?: any) => any;
Parameters
name | description | optional |
---|---|---|
value | Value to test | no |
fallback | Default value | yes (undefined by default) |
Example
let { exampleParamA, exampleParamB } = parameters;
exampleParamA = validateNumber(exampleParamA); // `exampleParamA` or `undefined`
exampleParamB = validateNumber(exampleParamB, 42); // `exampleParamB` or `42`
validateNumber(0, 9000); // 0
validateArray
The validateArray
function allows you to test whether the value passed as a parameter is a string; if so, the call to the validateArray
function returns an array containing the values passed as parameter separated by commas. Its TypeScript signature is as follows:
type Mapper = (value: string) => any;
declare const validateArray: (value: string, fallback?: string, mapper?: Mapper) => any[];
Parameters
name | description | optional |
---|---|---|
value | Value to test | no |
fallback | Default value | yes |
mapper | A function used to modify each value of the array | yes |
Example
let { exampleParamA, exampleParamB, exampleParamC } = parameters;
exampleParamA = validateArray(exampleParamA); // instanceof Array
exampleParamB = validateArray(exampleParamB, 'valueA,valueB'); // instanceof Array
exampleParamC = validateArray(exampleParamC, undefined, value => value.toLowerCase()); // instanceof Array
validateSet
The validateSet
function allows you to test whether the value passed as a parameter is a string; if so, the call to the validateSet
function returns an instance of the native Set
class containing the values passed as parameter separated by commas. Its TypeScript signature is as follows:
type Mapper = (value: string) => any;
declare const validateSet: (value: string, fallback?: string, mapper?: Mapper) => Set<any>;
Parameters
name | description | optional |
---|---|---|
value | Value to test | no |
fallback | Default value | yes |
mapper | A function used to modify each value of the set | yes |
Example
let { exampleParamA, exampleParamB, exampleParamC } = parameters;
exampleParamA = validateSet(exampleParamA); // instanceof Set
exampleParamB = validateSet(exampleParamB, 'valueA,valueB'); // instanceof Set
exampleParamC = validateSet(exampleParamC, undefined, value => value.toLowerCase()); // instanceof Set
ensureArray
The ensureArray
function ensures that the value passed as a parameter is a data array and performs the conversion if this is not the case; so-called falsy values are filtered. Its TypeScript signature is as follows:
declare const ensureArray: (value: any | any[]) => any[];
Parameters
name | description | optional |
---|---|---|
value | Value to convert to an array if necessary | no |
Example
ensureArray(['']); // []
ensureArray(''); // []
ensureArray([{}]); // [{}]
ensureArray({}); // [{}]
setWithValues
The setWithValues
function allows you to initialize an instance of the Set
class containing the values passed as parameters, one or more in the form of an array; so-called falsy values are filtered. Its TypeScript signature is as follows:
declare const setWithValues: (value: any | any[]) => Set<any>;
Parameters
name | description | optional |
---|---|---|
value | Value(s) contained in the created Set | no |
Example
setWithValues(['', {}]).size; // 1
setWithValues('').size; // 0
setWithValues({}).size; // 1
alias
The alias
function allows you to lock the first parameters of a given function; if the value of the first
parameter is an array, the return value will be an array of functions. Its TypeScript signature is as follows:
type Callback = (...args: any[]) => any;
declare const alias: (callback: Callback, first: any | any[], ...args: any[]) => Callback | Callback[];
Parameters
name | description | optional |
---|---|---|
callback | Function for which we want to lock the parameters | no |
first | First parameter to lock, treated differently if it is an array | no |
...args | Possible additional parameters | yes |
Example
const [log1, log2] = alias(console.log, [1, 2]);
log1(2); // 1 2
log2(3); // 2 3
const log3 = alias(console.log, 3, 4);
log3(5, 6); // 3 4 5 6
get
The get
function allows you to retrieve or assign the value stored in a given map for a given key; if no truthy value exists, an instance of the class passed as a parameter will be created, stored and returned. Its TypeScript signature is as follows:
type Class = {
new (...args: any[]): any;
};
declare const get: (map: Map<any, any>, key: any, Class: Class) => any;
Parameters
name | description | optional |
---|---|---|
map | Instance of the Map class on which to retrieve or assign the value | no |
key | Key for which to retrieve or assign the value on the map | no |
Class | Class instantiated and stored in the map if no truthy value exists for the given key | no |
Example
const key1 = 'key1';
const map = new Map([[key1, 1]]);
get(map, key1, Set); // 1
get(map, 'key2', Set); // instanceof Set
getSafeMap
The getSafeMap
function allows you to construct a safe copy for indexing of an object passed as a parameter, that is to say without a prototype chain. Its TypeScript signature is as follows:
declare const getSafeMap: (object: object) => object;
Parameters
name | description | optional |
---|---|---|
object | Object of which to create a safe copy for indexing | no |
Example
const key = 'key';
const object = { [key]: 'value' };
object[key]; // 'value'
typeof object.hasOwnProperty; // 'function'
const safeObject = getSafeMap(object);
safeObject[key]; // 'value'
typeof safeObject.hasOwnProperty; // 'undefined'
toMilliSeconds
The toMilliSeconds
function allows you to convert into milliseconds a number of seconds passed as a parameter. Its TypeScript signature is as follows:
declare const toMilliSeconds: (seconds: number) => number;
Parameters
name | description | optional |
---|---|---|
seconds | Number of seconds to convert to milliseconds | no |
Example
toMilliSeconds(5); // 5000
Mappings
Mapping
The Mapping
class is used to associate different events for different platforms, for example to group follower
(Twitch) and subscriber
(YouTube) events with a similar meaning; this is a subclass of the native String
class. Its TypeScript signature is as follows:
type Mappings = {
[platform: string]: string;
};
type Mapped = string | Mapping;
declare class Mapping extends String {
constructor(event: string, mappings: Mappings, group?: true);
get group(): boolean;
map(platform: string): Mapped;
is(event: Mapped, platform: string): boolean;
format(): string;
}
Parameters
name | description | optional |
---|---|---|
event | Basis event name, the most common one | no |
mappings | Object defining variants for specific platforms | no |
group | Indicates whether the event can be a group (see adapters) | yes |
Properties
name | description |
---|---|
group | Indicates whether the event can be a group |
Methods
name | description |
---|---|
map | Returns the variant associated with the given platform, or the mapping itself |
is | Returns true if the event passed as a parameter corresponds to the given platform, false otherwise |
format | Returns a formatted representation of the mapping, useful in particular for possible display |
Example
const cheerMapping = new Mapping(cheer, {
[trovo]: elixir,
[youtube]: superChat
});
cheerMapping.group; // false
cheerMapping.map(trovo); // elixir
cheerMapping.map(twitch); // cheerMapping
cheerMapping.map(youtube); // superChat
cheerMapping.is(follower, trovo); // false
cheerMapping.is(cheer, twitch); // true
cheerMapping.is(superChat, youtube); // true
cheerMapping.format(); // 'cheer, elixir (trovo), superchat (youtube)'
Pre-configured
We provide the following mappings, ready-to-use, to save you from having to model them yourself.
mapping | events |
---|---|
cheerMapping | cheer , stars (Facebook), gift (TikTok), elixir (Trovo), superChat (YouTube) |
followerMapping | follower , fan (Facebook), subscriber (YouTube) |
merchMapping | merch |
raidMapping | raid |
shareMapping | share |
subscriberMapping | subscriber , supporter (Facebook), sponsor (YouTube) |
tipMapping | tip |
likeMapping | like , videoLike (Facebook) |
URL
getOrigin
The getOrigin
function allows you to extract the origin of a URL passed as a parameter. Its TypeScript signature is as follows:
declare const getOrigin: (url: string) => string;
Parameters
name | description | optional |
---|---|---|
url | URL for which we want to extract the origin | no |
Example
getOrigin('https://obs.multistream.tools/v1/overlay.js'); // 'https://obs.multistream.tools'
getParams
The getParams
function allows you to construct an object from a query string passed as a parameter. Its TypeScript signature is as follows:
type Params = {
[key: string]: boolean | number | string | null | undefined;
};
declare const getParams: (queryString: string) => Params;
Parameters
name | description | optional |
---|---|---|
queryString | Query string with or without '?' at the beginning | no |
Example
getParams('?param1=a¶m2=1¶m3'); // { param1: 'a', param2: 1, param3: true }
split
The split
function allows you to separate several values, delimited by commas, from a string passed as a parameter. Its TypeScript signature is as follows:
declare const split: (value: string) => string[];
Parameters
name | description | optional |
---|---|---|
value | Potentially multiple values separated by commas | no |
Example
split('value1,value2'); // ['value1', 'value2']
reloadPage
The reloadPage
function allows you to reload the current page. Its TypeScript signature is as follows:
declare const reloadPage: () => void;
showTab
The showTab
function allows displaying a given tab (see our CSS framework) from a DOM element passed as a parameter, navigation can be optional thanks to the force
parameter. Its TypeScript signature is as follows:
declare const showTab: (element: HTMLElement, force?: false) => void;
Parameters
name | description | optional |
---|---|---|
element | Must contain an id property whose value matches that of a tab | no |
force | Force (true ) or not (false ) navigation if another tab already is displayed | yes (true by default) |
Example
const tab1 = document.getElementById('tab1');
const tab2 = document.getElementById('tab2');
showTab(tab1);
showTab(tab2, false);
DOM
prepend
The prepend
function allows you to insert content at the start of a given DOM element, one or more values in the form of an array; so-called falsy values are filtered. Its TypeScript signature is as follows:
type Content = string | HTMLElement;
declare const prepend: (content: Content | Content[], host?: HTMLElement) => HTMLElement;
Parameters
name | description | optional |
---|---|---|
content | Content to insert | no |
host | Element to insert content into | yes (document.body by default) |
Parameters
const world = document.createElement('p');
world.textContent = 'world';
prepend(['hello', world, null]); // document.body
prepend('hello world'); // document.body
append
The append
function works in the same way as the prepend
function except that it allows you to insert content at the end of a given DOM element.
replaceChildren
The replaceChildren
function works in the same way as the prepend
function with the difference that it allows you to completely replace the content of a given DOM element.
removeChildren
The removeChildren
function allows you to remove the content of a given DOM element. Its TypeScript signature is as follows:
declare const removeChildren: (host?: HTMLElement) => HTMLElement;
Parameters
name | description | optional |
---|---|---|
host | Element to remove content for | yes (document.body by default) |
Example
const hello = document.createElement('p');
hello.textContent = 'hello';
removeChildren(); // document.body
removeChildren(hello); // hello
setClasses
The setClasses
function allows you to add/remove CSS classes to a DOM element, one or more values in the form of an array; so-called falsy values are filtered. Its TypeScript signature is as follows:
declare const setClasses: (classes: string | string[], host?: HTMLElement, add?: false) => HTMLElement;
Parameters
name | description | optional |
---|---|---|
classes | CSS classes to add or remove | no |
host | Element to add/remove classes to | yes (document.body by default) |
add | Add (true ) or remove (false ) classes | yes (true by default) |
Example
setClasses(['classA', 'classB']); // document.body
setClasses('classB', undefined, false); // document.body
setData
The setData
function allows you to add and reset data to a given DOM element. Its TypeScript signature is as follows:
declare const setData: (data: object, host?: HTMLElement, reset?: true) => HTMLElement;
Parameters
name | description | optional |
---|---|---|
data | Data to add to the element | no |
host | Element to add/reset data to | yes (document.body by default) |
reset | Reset (true ) or not (false ) data | yes (false by default) |
Example
setData({ data1: 1 }); // document.body
setData({ data2: 2 }, undefined, true); // document.body
setData(null, undefined, true); // document.body
element
The element
function allows you to create a DOM element, optionally adding CSS classes, content, data and properties to it; so-called falsy values are filtered for CSS classes and content. Its TypeScript signature is as follows:
type Content = string | HTMLElement;
type Properties = {
classes?: string | string[];
content: Content | Content[];
data?: object;
[key: string]: any;
};
declare const element: (tag: string, properties?: Properties) => HTMLElement;
Parameters
name | description | optional |
---|---|---|
tag | Tag of the element to create | no |
properties | Properties to initialize on the created element | yes |
Example
element('div'); // instanceof HTMLDivElement
element('p', {
classes: 'classA',
content: 'hello world',
data: { data1: 1 },
id: 'elementId'
}); // instanceof HTMLParagraphElement
button
The button
function is a shortcut to the element
function allowing you to create elements of type button; the properties
parameter remains unchanged.
input
The input
function is a shortcut to the element
function allowing you to create elements of type input; the properties
parameter remains unchanged.
label
The label
function is a shortcut to the element
function allowing you to create elements of type label; the properties
parameter remains unchanged.
li
The li
function is a shortcut to the element
function allowing you to create elements of type li; the properties
parameter remains unchanged.
link
The link
function is a shortcut to the element
function allowing you to create elements of type link; the properties
parameter remains unchanged.
span
The span
function is a shortcut to the element
function allowing you to create elements of type span; the properties
parameter remains unchanged.
enable
The enable
function allows you to enable or disable a DOM element (interactive one). Its TypeScript signature is as follows:
type Host = HTMLButtonElement | HTMLFieldSetElement | HTMLOptGroupElement | HTMLOptionElement | HTMLSelectElement | HTMLTextAreaElement | HTMLInputElement;
declare const enable: (host: Host, enabled?: false) => Host;
Parameters
name | description | optional |
---|---|---|
host | Element to enable/disable | no |
enabled | Enable (true ) or disable (false ) the element | yes (true by default) |
Example
const button = element('button');
enable(button); // button
enable(button, false); // button
getValue
The getValue
function allows you to retrieve the value of the value
property of a DOM element; depending on the parameters passed as input, this value can be a list. Its TypeScript signature is as follows:
type ValueNode = Node & {
value: string;
};
type Host = ValueNode | RadioNodeList | undefined | null;
declare const getValue: (host: Host, multiple?: true) => any | any[];
Parameters
name | description | optional |
---|---|---|
host | Element for which to retrieve the value of the value property | no |
multiple | Indicates whether the element should be treated as a list (true ) or not (false ) | yes (false by default) |
Example
const input = element('input', { value: 'hello world' });
getValue(input); // 'hello world'
getValue(input, true); // ['hello world']
getValue(undefined); // undefined
getValue(undefined, true); // []
crossOrigin
The crossOrigin
function allows you to configure the value of the crossOrigin
property of a DOM element. Its TypeScript signature is as follows:
type Host = HTMLAudioElement | HTMLImageElement | HTMLLinkElement | HTMLScriptElement | HTMLVideoElement;
type Value = 'anonymous' | 'use-credentials' | '';
declare const crossOrigin: (host: Host, value?: Value) => Host;
Parameters
name | description | optional |
---|---|---|
host | Element for which to configure the crossOrigin property value | no |
value | Value to configure for the crossOrigin property | yes ('anonymous' by default) |
Example
const image = element('img');
crossOrigin(image); // image
crossOrigin(image, 'use-credentials'); // image
hide
The hide
function allows you to hide or show a given DOM element by adding or removing the hidden
class, exposed by our CSS framework. Its TypeScript signature is as follows:
declare const hide: (hidden?: false, host?: HTMLElement) => HTMLElement;
Parameters
name | description | optional |
---|---|---|
hidden | Hide (true ) or show (false ) the given element | yes (true by default) |
host | Element to hide or show | yes (document.body by default) |
Example
hide(); // document.body
hide(false); // document.body
setText
The setText
function allows you to modify the textual content of a given DOM element. Its TypeScript signature is as follows:
declare const setText: (text: string, host?: HTMLElement) => HTMLElement;
Parameters
name | description | optional |
---|---|---|
text | New text content for the given element | no |
host | Element for which to modify the textual content | yes (document.body by default) |
Example
setText('hello world'); // document.body
setVariable
The setVariable
function allows you to configure/delete the value of a CSS variable on a given DOM element. Its TypeScript signature is as follows:
type Value = string | number | undefined | null;
declare const setVariable: (name: string, value: Value, host?: HTMLElement) => HTMLElement;
Parameters
name | description | optional |
---|---|---|
name | Name of the CSS variable to configure | no |
value | Value of the CSS variable to configure, undefined or null to delete | no |
host | Element on which to modify the CSS variable | yes (document.documentElement by default) |
Example
setVariable('hello world'); // document.body
select
The select
function allows you to retrieve an array of DOM elements by CSS selector. Its TypeScript signature is as follows:
declare const select: (selector: string, host?: HTMLElement) => HTMLElement[];
Parameters
name | description | optional |
---|---|---|
selector | CSS selector to locate elements | no |
host | Element to select elements from | yes (document.documentElement by default) |
Example
select('meta'); // HTMLMetaElement[]
select('div', body); // HTMLDivElement[]
Events
ClickListener
The ClickListener
class is a subclass of the Listener
class described previously; this is used to facilitate listening to events of type click. Its TypeScript signature is as follows:
declare class ClickListener extends Listener {
constructor(callback: Callback, host?: EventTarget, passive?: false);
}
Namespace
Namespace
The Namespace
class is used to create a namespace in order to avoid possible collisions. The generated keys are automatically prefixed by the origin of the current page; a custom suffix can be added if needed. Its TypeScript signature is as follows:
declare class Namespace {
constructor(suffix?: string, prefix?: string);
key(name: string): string;
}
Parameters
name | description | optional |
---|---|---|
suffix | Custom suffix for all generated keys | yes |
prefix | Custom prefix for all generated keys | yes (origin by default) |
Methods
name | description |
---|---|
key | Generate a prefixed key to avoid naming conflicts |
Example
const namespaceA = new Namespace();
namespaceA.key('keyName'); // '<currentPageOrigin>.keyName'
const namespaceB = new Namespace('suffixName');
namespaceB.key('otherName'); // '<currentPageOrigin>suffixName.otherName'
Persistence
Store
The Store
class is used to save data to the local storage of the browser; this is a subclass of the Namespace
class described previously. The storage keys are automatically prefixed by the address (origin + pathname
) of the current page to avoid any possible conflict. Its TypeScript signature is as follows:
declare class Store extends Namespace {
constructor(suffix?: false | null | string);
set(key: string, value: any): void;
get(key: string): any | null;
remove(key: string): void;
}
Parameters
name | description | optional |
---|---|---|
suffix | Custom suffix for all generated keys, makes sharing storage easier | yes (pathname by default) |
Methods
name | description |
---|---|
get | Retrieve a previously stored value for a given key |
set | Store/overwrite a value for a given key |
remove | Delete a previously stored value for a given key |
Example
const store = new Store();
const key = 'counter';
store.get(key); // null
store.set(key, 1);
store.set(key, 2);
store.get(key); // 2
store.remove(key);
Forms
Form
The Form
class is used to add behavior to a form such as persisting the values of certain fields; this is a subclass of the Store
class described previously. Its TypeScript signature is as follows:
type ResetCallback = () => any;
type ChangeCallback = (name: string, element: HTMLElement) => any;
type SubmitCallback = (event: SubmitEvent) => any;
type Options = {
persisted?: string[] | true;
reset?: ResetCallback | false;
change?: ChangeCallback;
submit: SubmitCallback;
};
type FieldBuilder = (removeButton: HTMLButtonElement) => HTMLElement;
declare class Form extends Store {
constructor(host: HTMLFormElement, options: Options, suffix?: false | null | string);
buildRemovableField(fieldBuilder: FieldBuilder, buttonText?: string): HTMLElement;
addRemovableFieldOnClick(clickHost: HTMLElement, addHost: HTMLElement, fieldBuilder: FieldBuilder, buttonText?: string): ClickListener;
}
Parameters
name | description | optional |
---|---|---|
host | Form element to add behavior to | no |
options | Object describing the behavior to add to the form | no |
options.persisted | List of field names (name attribute) whose (valid) value must be persisted, or true for all | yes |
options.reset | Function to call after resetting the form, pass false if it does not have a reset button | yes |
options.change | Function to call when the values of the persisted fields change, if valid | yes |
options.submit | Function to call on form submission (the event.preventDefault method is called internally) | no |
suffix | Custom suffix for all generated keys, makes sharing storage easier | yes (pathname by default) |
Methods
name | description |
---|---|
buildRemovableField | Create a field that can be deleted by clicking a button |
addRemovableFieldOnClick | Add fields, which can be deleted, to a list by clicking on a given element |
Example
const formElement = document.getElementById('form');
const form = new Form(formElement, {
persisted: ['fieldA', 'fieldB'], // Pass `true` to persist all fields.
reset: false,
change(fieldName, field) {
console.log('change', fieldName, field);
},
submit(event) {
console.log('submit', event);
}
});
const itemBuilder = removeButton => li({
content: [element('input'), removeButton]
});
form.buildRemovableField(itemBuilder); // instanceof HTMLLIElement
const addButton = document.getElementById('add');
const fieldsList = document.getElementById('list');
form.addRemovableFieldOnClick(addButton, fieldsList, itemBuilder, 'Delete'); // instanceof ClickListener
Waiting queue
Queue
The Queue
class is used to create and manage FIFO (First In First Out) queues. Its TypeScript signature is as follows:
type Callback = () => void;
declare class Queue {
constructor(duration?: number, manual?: true);
add(onStart: Callback, onEnd: Callback): void;
pause(paused?: false): void;
skip(): void;
clear(): void;
dispose(): void;
}
Parameters
name | description | optional |
---|---|---|
duration | Hold duration, expressed in seconds | yes (parameters.queueDuration by default) |
manual | Automatically react (false ) or not (true ) to pause and skip system events | yes (false by default) |
Methods
name | description |
---|---|
add | Add a new item to the queue |
pause | Pause or resume the execution of the queue |
skip | Directly go to the next item in the queue, has no effect when the queue is paused |
clear | Allows you to completely empty the queue |
dispose | Cleanup method to call, when the manual parameter is false , if the instance is no longer used or you want to disconnect it from system events |
The onStart
and onEnd
functions are respectively called when an element starts to exit the queue and after it has completely exited.
Example
const queue = new Queue(25);
[1, 2, 3].forEach(number => queue.add(
() => console.log('onStart', number),
() => console.log('onEnd', number)
));
queue.pause();
queue.pause(false);
queue.skip();
queue.clear();
queue.dispose();
Spam
AntiSpam
The AntiSpam
class is used to check that a given action is not considered spam. Its TypeScript signature is as follows:
declare class AntiSpam {
constructor(threshold?: number, delta?: number);
check(action: any): boolean;
}
Parameters
name | description | optional |
---|---|---|
threshold | Maximum number of accepted repetitions for the same action | yes (parameters.antiSpamThreshold by default) |
delta | Duration after which the same action will no longer be considered spam, expressed in seconds | yes (parameters.antiSpamDelta by default) |
Methods
name | description |
---|---|
check | Returns true if the given action is not considered spam, false otherwise |
Example
const antiSpam = new AntiSpam(2, 0.5);
const action = 'action';
antiSpam.check(action); // true
antiSpam.check(action); // true
antiSpam.check(action); // false
Audio
Sound
The Sound
class is used to play audio files; this is a subclass of the native Audio
class, simply adding missing amenities. Its TypeScript signature is as follows:
type CrossOrigin = 'anonymous' | 'use-credentials' | '';
declare class Sound extends Audio {
constructor(url: string, volume?: number, crossOrigin?: CrossOrigin, manual?: true);
stop(): void;
mute(muted?: false): void;
dispose(): void;
}
Parameters
name | description | optional |
---|---|---|
url | Address of the audio file to load | no |
volume | Audio file playback volume, between 0 and 1 | yes (parameters.volume by default) |
crossOrigin | Value to configure for the crossOrigin property | yes ('anonymous' by default) |
manual | Automatically react (false ) or not (true ) to mute system events | yes (false by default) |
Methods
name | description |
---|---|
stop | Completely stop playing the audio file |
mute | Mute (true ) or unmute (false ) the sound without stopping the playback of the audio file |
dispose | Cleanup method to call, when the manual parameter is false , if the instance is no longer used or you want to disconnect it from system events |
Example
const sound = new Sound('<fileURL>', 0.5);
sound.play();
sound.mute();
sound.mute(false);
sound.stop();
sound.dispose();
Communication
Emitter
The Emitter
class is used to emit custom events in our system; this is a subclass of the Namespace
class described previously. Its TypeScript signature is as follows:
declare class Emitter extends Namespace {
constructor(crossOrigin?: boolean, namespace?: string);
emit(category: string, data?: any, otherProperties?: object): void;
}
Parameters
name | description | optional |
---|---|---|
crossOrigin | Indicates whether emitted events can be received by overlays of different origins (true ) | yes (false by default) |
namespace | Adds a namespace to emitted events, recommended when crossOrigin is true | yes |
Methods
name | description |
---|---|
emit | Emit custom events |
Example
const emitter = new Emitter();
const category = 'customEvent';
const props = { key: 'value' };
const data = { props };
emitter.emit(category); // Emitted event: { category }
emitter.emit(category, data); // Emitted event: { category, data }
emitter.emit(category, data, props); // Emitted event: { category, data, ...props }
emitter.emit(category, undefined, props); // Emitted event: { category, ...props }
Observer
The Observer
class is used to listen to events emitted in our system, native or custom ones; this is a subclass of the Listener
class described previously. Its TypeScript signature is as follows:
type Id = string;
type AlertData = {
name: string;
sender?: string;
message?: string;
tier?: string;
amount?: number;
};
type SessionData = {
[key: string]: object | object[];
};
type LoadData = {
session: SessionData;
};
type ChatData = object;
type MessageData = {
renderedText: string;
data: {
userId: Id;
msgId: Id;
nick: string;
displayName: string;
};
};
type DeleteMessageData = {
msgId: Id;
};
type DeleteMessagesData = {
userId: Id;
};
type OtherData = object;
type Event<T = undefined, U = undefined> = {
data: T;
event: U;
[key: string]: any;
};
type PlatformEvent<T, U = undefined> = Event<T, U> & {
platform: string;
group?: Id;
root?: true;
};
type Callback<T> = (event: T) => any;
type SystemEvents = {
load?: Callback<PlatformEvent<LoadData>>;
session?: Callback<PlatformEvent<SessionData>>;
alerts?: Callback<PlatformEvent<AlertData, string>>;
chat?: Callback<
PlatformEvent<MessageData, 'message'> |
PlatformEvent<DeleteMessageData, 'delete-message'> |
PlatformEvent<DeleteMessagesData, 'delete-messages'> |
PlatformEvent<ChatData, string>
>;
other?: Callback<PlatformEvent<OtherData, string>>;
mute?: Callback<Event<boolean>>;
pause?: Callback<Event<boolean>>;
skip?: Callback<Event>;
};
type CustomEvents = {
[key: string]: Callback<Event<any, any>>;
};
type Events = SystemEvents | CustomEvents;
declare class Observer extends Listener {
constructor(events: Events);
}
Parameters
name | description | optional |
---|---|---|
events | Object listing the functions to call upon receipt of given events | no |
Example
const logger = type => data => console.log(type, data);
const emitter = new Emitter();
const customEvent = 'customEvent';
const observer = new Observer({
// System events.
load: logger('load'),
session: logger('session'),
alerts: logger('alerts'),
chat: logger('chat'),
other: logger('other'),
mute: logger('mute'),
pause: logger('pause'),
skip: logger('skip'),
// OBS related system events.
getCurrentScene: logger('getCurrentScene'),
obsSceneChanged: logger('obsSceneChanged'),
// Custom event.
[emitter.key(customEvent)]: logger(customEvent)
});
observer.off();
observer.on();
OBS
obsAPI
The obsAPI
function allows you to use the OBS JavaScript API, the complete list of possibilities is available on this page. Its TypeScript signature is as follows:
declare const obsAPI: (method: string, ...args: any[]) => void;
Parameters
name | description | optional |
---|---|---|
method | Name of the method to call (getter or setter) | no |
...args | Parameters to pass when calling the method | yes |
Example
const pluginVersion = 'pluginVersion';
const getCurrentScene = 'getCurrentScene';
new Observer({
[pluginVersion]({ data }) {
// Do whatever you want with the value here.
}
[getCurrentScene]({ data }) {
// Do whatever you want with the value here.
}
});
// Getters.
obsAPI(pluginVersion);
obsAPI(getCurrentScene);
// Setters.
obsAPI('stopStreaming');
obsAPI('setCurrentScene', 'new scene name');
Theming
loadStyles
The loadStyles
function allows you to load a given stylesheet. Its TypeScript signature is as follows:
type CrossOrigin = 'anonymous' | 'use-credentials' | '';
declare const loadStyles: (url: string, crossOrigin: CrossOrigin) => HTMLLinkElement;
Parameters
name | description | optional |
---|---|---|
url | Address of the stylesheet to load (local, remote, or data URL) | no |
crossOrigin | Value to configure for the crossOrigin property | yes ('anonymous' by default) |
Example
loadStyles('<stylesheetURL>'); // instanceof HTMLLinkElement
loadStyles('<stylesheetDataURL>', 'use-credentials'); // instanceof HTMLLinkElement
loadFonts
The loadFonts
function allows you to load fonts via the Google Fonts API and apply them as the --fontFamily1
to --fontFamilyN
CSS variables. Its TypeScript signature is as follows:
declare const loadFonts: (query: string) => HTMLLinkElement | false;
If the global fonts
parameter is used either to change fonts or disable them, calling the loadFonts
function will have no effect and the return value will be false
.
You should call this function only once to load every font you would need and rely on CSS variables to dynamically switch them later if you want to.
The value of the Google Fonts API family
parameter must always come first and the value of the display
parameter is block
by default.
Parameters
name | description | optional |
---|---|---|
query | Google Fonts query, without ?family= | no |
Example
loadFonts('Droid+Sans|Tangerine:bold&display=auto'); // instanceof HTMLLinkElement or false
Internationalization
defaultLang
The constant named defaultLang
corresponds to the default value of the lang
attribute set on the html
tag of the Web page associated with your overlay/dock.
It is important to always set a default value to this attribute for accessibility reasons and so that our internationalization system can work correctly. For example:
<html lang="en"></html>
lang
The constant named lang
corresponds to the value passed as the system parameter of the same name; or to that of the navigator.language
property by default, i.e. the language of the browser displaying the Web page of your overlay/dock (in this case that of the OBS user interface).
i18n
The i18n
function helps with messages translation. You should only call it once and only if your overlay/dock needs to be translated into multiple languages. Its TypeScript signature is as follows:
type Translations = {
[lang: string]: object;
};
declare const i18n: (translations?: Translations) => object;
Parameters
name | description | optional |
---|---|---|
translations | Objects containing translation data, indexed by language | yes |
Example
// Given `lang="en"` on `html` tag, `'fr'` as `lang` system parameter value
// and `<div data-i18n="hello">Hello</div>` in `body` element.
i18n().hello; // 'Hello' (default value)
// 'Bonjour'
const { hello } = i18n({
fr: { hello: 'Bonjour' },
es: { hello: 'Holà' }
});
document.documentElement.lang; // 'fr'
When no translation data is passed as a parameter, the i18n
function simply synchronizes the value of the lang
attribute, on the html
tag of the page, with the one of the constant named lang
described above; this can be useful when you want to manage translations in another way.
When translation data is passed as a parameter, the i18n
function seeks to determine the closest match between the defined languages and the value of the constant named lang
; this match, if found, is then applied as the value of the lang
attribute on the html
tag of the page. For example:
// Given `lang="fr"` on `html` tag and `'en-US'` as `lang` system parameter value.
// 'Color'
const { color } = i18n({
'en-GB': { color: 'Colour' },
en: { color: 'Color' }
});
document.documentElement.lang; // 'en'
In both cases, the i18n
function iterates through each DOM element on the page with a data-i18n
attribute and:
- replaces its textual content automatically with any defined translation data, of type
string
, whose key corresponds to the value of thedata-i18n
attribute in question - gets/returns its textual content when no translation data is defined for the key in question
The return value of the i18n
function is therefore an object containing the fusion of the translation data for the desired language (if defined) and that of the default language. This object is safe for indexing.
It is also possible to define translation data of types other than string
, they will simply not be applied automatically but manually, as you wish. For example:
const helloEN = user => `Hello ${user}!`;
const helloFR = user => `Bonjour ${user} !`;
const { hello = helloEN } = i18n({ fr: { hello: helloFR } });
setText(hello('TheFrenchBiff'));
You can also pass translation data for the default language, which can be particularly useful in the case of dynamic messages that are not part of the initial content of the page (content for which we would prefer the use of the previously mentioned data-i18n
attributes).
// Given `lang="en"` on `html` tag, `'fr'` as `lang` system parameter value
// and `<div data-i18n="hello">Hello</div>` in `body` element.
const {
hello, // 'Bonjour'
you, // 'toi'
message // 'message'
} = i18n({
[defaultLang]: { you: 'you', message: 'message' },
fr: { hello: 'Bonjour', you, 'toi' }
});
Note that it is entirely possible to omit any translation data for which the value is not different than the default one.
For a practical example, go to our page dedicated to overlay development.