Utils
Source: Utils.js:32
File : Utils.js
Created : 01/04/2015
By : Francesc Busquets francesc@gmail.com
JClic.js
An HTML5 player of JClic activities
https://projectestac.github.io/jclic.js
- License: EUPL-1.2
Static Methods
init(
options: object,
setLog?: boolean,
setLang?: boolean,
): object
Initializes the global settings
Parameters
options(object) — An object with global settingssetLog(boolean, optional, default: true) — Whentrue, the log level will be setsetLang(boolean, optional, default: true) — Whentrue, the current language will be set
Returns
object— The normalizedoptionsobject
getMsg(key: string): string
Function that will return the translation of the provided key
into the current language.
Parameters
key(string) — ID of the expression to be translated
Returns
string
normalizeLocale(locale: string)
Converts expressions of type 'pt-br', 'FR', 'ca_es@valencia'... to the format expected by the i18n system:
lc[_CC][@variant] where 'lc' is a two or three lowercase letter language code, CC is an optional two uppercase
letter country code, followed by an optional 'variant' consisting in letters and/or digits.
Parameters
locale(string) — The locale expression to be normalized
Returns
- string - The normalized locale
checkPreferredLanguage(
availableLangs: Array.<string>,
defaultLang?: string,
requestedLang?: string,
): string
Checks if the language preferred by the user (based on browser and/or specific settings)
is in a list of available languages.
Parameters
availableLangs(Array.<string>) — Array of available languages. It should contain at least one item.defaultLang(string, optional, default: "en") — Language to be used by default when not found the selected onerequestedLang(string, optional, default: "''") — Request this specific language
Returns
string
setLogLevel(level: string)
Establishes the current verbosity level of the logging system
Parameters
level(string) — One of the valid strings in module:Utils.LOG_LEVELS
log(type: string, msg: string)
Reports a new message to the logging system
Parameters
type(string) — The type of message. Mus beerror,warn,info,debugortrace.msg(string) — The main message to be logged. Additional parameters can be added, like
inconsole.log(see: https://developer.mozilla.org/en-US/docs/Web/API/Console/log)
getBoolean(val: string, defaultValue?: boolean): number
Gets a boolean value from a textual expression
Parameters
val(string) — The value to be parsed (truefor true, null or otherwise forfalse)defaultValue(boolean, optional, default: false) — The default value to return whenvalis false
Returns
number
getVal(val: any, defaultValue?: any): any
Gets a value from an given expression that can be null, undefined or empty string ('')
Parameters
val(any) — The expression to parsedefaultValue(any, optional, default: null) — The value to return whenvalisnull,''orundefined
Returns
any
getNumber(val: any, defaultValue?: number): number
Gets a number from a string or another number
Parameters
val(any) — The expression to parsedefaultValue(number, optional, default: 0) — The default value
Returns
number
getPercent(val: number): string
Gets the plain percent expression (without decimals) of the given value
Parameters
val(number) — The value to be expressed as a percentile
Returns
string
zp(val: number): string
Returns the two-digits text expression representing the given number (lesser than 100) zero-padded at left
Useful for representing hours, minutes and seconds
Parameters
val(number) — The number to be processed
Returns
string
getHMStime(millis: number): string
Returns a given time in [00h 00'00"] format
Parameters
millis(number) — Amount of milliseconds to be processed
Returns
string
getDateTime(date: external:Date): string
Returns a formatted string with the provided date and time
Parameters
date(external:Date) — The date to be formatted. Whennullorundefined, the current date will be used.
Returns
string
parseOldDate(text: string): external:Date
Parse 'date' fields generated by "JClic Author" in format d/m/y, with
variable number of digits.
Parameters
text(string) — The old 'date' field
Returns
cleanOldLanguageTag(text: string): string
Extracts just the ISO-639 language code from complex
expressions like "English (en)", buid by JClic Author.
Parameters
text(string) — The expression to parse
Returns
string
getTriState(val: string, def: any): number
Gets a numeric value (0, 1 or 2) from a set of possible values: false, true and default.
Parameters
val(string) — The text to be parseddef(any) — An optional default value
Returns
number
fillString(tag: string, repeats: number): string
Returns a string with the given tag repeated n times
Parameters
tag(string) — The tag to be repeatedrepeats(number) — The number of times to repeat the tag
Returns
string
isNullOrUndef(val: any): boolean
Checks if the provided value is 'null' or 'undefined'.
Parameters
val(any) — The value to be parsed
Returns
boolean
isEquivalent(a: any, b: any): boolean
Checks if two expressions are equivalent.
Returns true when both parameters are null or undefined, and also when both have
equivalent values.
Parameters
a(any)b(any)
Returns
boolean
getXmlText(xml: object): string
Reads paragraphs, identified by <p></p> elements, inside XML data
Parameters
xml(object) — The DOM-XML element to be parsed
Returns
string
parseXmlNode(xml: object, withText?: boolean): object
Parse the provided XML element node, returning a complex object
Parameters
xml(object) — The root XML element to parsewithText(boolean, optional, default: false) — Whentrue, any text found inside the XML element is also included in the resulting object.
Returns
object
getXmlNodeText(xml: object): string | object
Parse the given XML node, known as containing only text elements,
and return its content as a string (when possible)
Parameters
xml(object) — The XML element to parse
Returns
string | object
reduceTextsToStrings(obj: object): object
Recursively explore the given object, converting to a string
all attributes with a single attribute named 'text'.
Example:
{a:1, b:{text:"hello"}, c:{d:2, text:"world"}} => {a:1, b:"hello", c:{d:2, text:"world"}}
Parameters
obj(object) — The object to explore
Returns
object
cssToString(cssObj: object): string
Creates a string suitable to be used in the 'style' attribute of HTML tags, filled with the
CSS attributes contained in the provided object.
Parameters
cssObj(object)
Returns
string
checkColor(color?: string, defaultColor?: string): string
Converts java-like color codes (like '0xRRGGBB') to valid CSS values like '#RRGGBB' or 'rgba(r,g,b,a)'
Parameters
color(string, optional) — A color, as codified in JavadefaultColor(string, optional) — The default color to be used
Returns
string
colorHasTransparency(color: string): boolean
Checks if the provided color has an alpha value less than 1
Parameters
color(string) — The color to be analyzed
Returns
boolean
cloneObject(obj: object): object
Clones the provided object
See: https://stackoverflow.com/questions/41474986/how-to-clone-a-javascript-es6-class-instance
Parameters
obj(object)
Returns
object
normalizeObject(obj: object): object
Converts string values to number or boolean when needed
Parameters
obj(object) — The object to be processed
Returns
object
getAttr(obj: object, keys?: Array.<string>): object
Returns an partial clone of an object, containing only the own attributes specified in an array of possible keys.
When the value of an attribute is of type 'Object' and this object has a method named getAttributes, the result of calling
this method is returned instead of the crude object.
Parameters
obj(object) — The object to be processedkeys(Array.<string>, optional) — An optional array of keys to be included in the resulting object.
When null or not set, all keys ofobjare included. Keys can include a default value separed by '|'.
Attributes with default value will be excluded from the resulting object.
Returns
object
getValue(value: any): any
Gets the minimal representation of the given value (object, array, string, number...)
Parameters
value(any) — The value to be processed
Returns
any
isEmpty(v: any): boolean
Checks if the given value is an empty object, null or a zero-length string
Parameters
v(any) — The value to be checked
Returns
boolean
setAttr(obj: object, data: object, attr: Array.<string>): object
Fills an object with specific attributes from another data object
Parameters
obj(object) — The target objectdata(object) — The data objectattr(Array.<string>) — The list of attributes to be copied fromdatatoobj
Elements of this list can be:
a) Just a string. In this case, the native object will be used as a value
b) An object with the following members:
-key{string} - The attribute name
-fn{function} - The function to be invoked to build the object
-params{string[]} - Optional params to be passed to thesetAttributesmethod of the created object
-group{string} - Used whendatais an object or an array (possible values areobjectandarray), and multiple results
should be aggregated in a resulting object or array with the same keys (or ordering) as data.
-init{string} - Optional parameter indicating iffnshould be passed with an additional param. This param can be:
-key- The member's key
Returns
object
buildObj(
objType: function,
data?: object,
init?: any,
params?: Array.<object>,
): object
Builds a new object based on the provided constructor, data and initialization value
Objects used with this function should implement setAttributes, or an static method named factory
Parameters
objType(function) — A class or function to be invoked to build the object.data(object, optional) — An optional object filled with the attributes to be assigned to the newly created object.init(any, optional) — An optional value to be passed to the function when invoked withnewparams(Array.<object>, optional, default: "[]") — Optional array of params to be passed when callingsetAttributeson the final object
Returns
object
isSeparator(ch: string): boolean
Check if the given char is a separator
Parameters
ch(string) — A string with a single character
Returns
boolean
isWordDelimiter(ch: string): boolean
Check if the given char is a word delimiter
Parameters
ch(string) — A string with a single character
Returns
boolean
stringToWords(str: *): Array.<object>
Converts a string in an array of objects with 'text' and 'sep' attributes, where 'text' are single words and 'sep'
are the word separators following each word in the sentence.
Parameters
str(*) — The text to be tokenized
Returns
Array.<object>
Example
<p>stringToWords("Hello, World! That's all") returns:<br>
[<br>
{text: "Hello", sep: ", "},<br>
{text: "World", sep: "! "},<br>
{text: "That", sep: "'"},<br>
{text: "s", sep: " "},<br>
{text: "all", sep: ""},<br>
]</p>roundTo(v: number, n: number): number
Rounds v to the nearest multiple of n
Parameters
v(number)n(number) — Cannot be zero!
Returns
number
fx(v: any, n: number): any
Set the maximum number of decimals for a number
Parameters
v(any) — The value to be converted to a fixed number of decimals. Can be anything.n(number, default: 4) — the maximum number of decimals
Returns
any
compareMultipleOptions(
answer: string,
check: string,
checkCase?: boolean,
numeric?: boolean,
): boolean
Compares the provided answer against multiple valid options. These valid options are
concatenated in a string, separated by pipe chars (|). The comparing can be case sensitive.
Parameters
answer(string) — The text to check against tocheck(string) — String containing one or multiple options, separated by|checkCase(boolean, optional, default: false) — When true, the comparing will be case-sensitivenumeric(boolean, optional, default: false) — When true, we are comparing numeric expressions
Returns
boolean
endsWith(text: string, expr: string, trim?: boolean): boolean
Checks if the given string ends with the specified expression
Parameters
text(string) — The string where to find the expressionexpr(string) — The expression to search for.trim(boolean, optional) — Whentrue, thetextstring will be trimmed before check
Returns
boolean
startsWith(text: string, expr: string, trim?: boolean): boolean
Checks if the given string starts with the specified expression
Parameters
text(string) — The string where to find the expressionexpr(string) — The expression to search for.trim(boolean, optional) — Whentrue, thetextstring will be trimmed before check
Returns
boolean
nSlash(str: string): string
Replaces all occurrences of the backslash character () by a regular slash (/)
This is useful to normalize bad path names present in some old JClic projects
Parameters
str(string) — The string to be normalized
Returns
string
isURL(exp: string): boolean
Checks if the given expression is an absolute URL
Parameters
exp(string) — The expression to be checked
Returns
boolean
getBasePath(path: string): string
Gets the base path of the given file path (absolute or full URL). This base path always ends
with /, meaning it can be concatenated with relative paths without adding a separator.
Parameters
path(string) — The full path to be parsed
Returns
string
getRelativePath(file: string, path?: string): string
Gets the full path of file relative to basePath
Parameters
file(string) — The file namepath(string, optional) — The base path
Returns
string
getPath(basePath: string, path: string): string
Gets the complete path of a relative or absolute URL, using the provided basePath
Parameters
basePath(string) — The base URLpath(string) — The filename
Returns
string
getPathPromise(
basePath: string,
path: string,
zip?: external:JSZip,
): external:Promise
Gets a promise with the complete path of a relative or absolute URL, using the provided basePath
Parameters
basePath(string) — The base URLpath(string) — The filenamezip(external:JSZip, optional) — An optional external:JSZip object where to look
for the file
Returns
getSvg(
svg: string,
width?: string,
height?: string,
fill?: string,
): string
Replaces width, height and fill attributes of a simple SVG image
with the provided values
Parameters
svg(string) — The SVG image as XML stringwidth(string, optional) — Optional setting for "width" propertyheight(string, optional) — Optional setting for "height" propertyfill(string, optional) — Optional setting for "fill" property
Returns
string
svgToURI(
svg: string,
width?: string,
height?: string,
fill?: string,
): string
Encodes a svg expression into a data URI
suitable for the src property of img elements, optionally changing its original size and fill values.
Parameters
svg(string) — The SVG image as XML stringwidth(string, optional) — Optional setting for "width" propertyheight(string, optional) — Optional setting for "height" propertyfill(string, optional) — Optional setting for "fill" property
Returns
string
toCssSize(
exp: string | number,
css: object,
key: string,
def: string,
): string
Converts the given expression into a valid value for CSS size values
Parameters
exp(string | number) — The expression to be evaluated. Can be a numeric value,nullorundefined.
Positive values are in "px" units, negative ones are "%"css(object) — An optional Object where the resulting expression (if any) will be savedkey(string) — The key under which the result will be stored incssdef(string) — Default value to be used whenexpisnullorundefined
Returns
string
getImgClipUrl(img: object, rect: module:AWT.Rectangle): string
Gets a clip of the give image data, in a URL base64 encoded format
Parameters
img(object) — The binary data of the realized image, usually obtained from amodule:bads/MediaBagElement.MediaBagElementrect(module:AWT.Rectangle) — A rectangle containing the requested clip
Returns
string
getRootHead(el?: external:HTMLElement): external:HTMLElement
Finds the nearest head or root node of a given HTMLElement, useful to place <style/> elements when
the main component of JClic is behind a shadow-root.
This method will be replaced by a call to Node.getRootNode()
when fully supported by all major browsers.
Parameters
el(external:HTMLElement, optional) — The element from which to start the search
Returns
appendStyleAtHead(
css: string,
ps?: module:JClicPlayer.JClicPlayer,
): external:HTMLStyleElement
Appends a style element to the head or root node nearest to the given HTMLElement.
Parameters
css(string) — The content of the stylesheetps(module:JClicPlayer.JClicPlayer, optional) — An optionalPlayStation(currently a JClicPlayer) used as a base to find the root node
Returns
appendStylesheetAtHead(
href: string,
ps?: module:JClicPlayer.JClicPlayer,
): external:HTMLLinkElement
Appends a stylesheet element to the head or root node nearest to the given HTMLElement.
Parameters
href(string) — URL pointing to the stylesheetps(module:JClicPlayer.JClicPlayer, optional) — An optionalPlayStation(currently a JClicPlayer) used as a base to find the root node
Returns
attrForEach(
attributes: external:NamedNodeMap,
callback: function,
)
Traverses all the attributes defined in an Element, calling a function with its name and value as a parameters
Parameters
attributes(external:NamedNodeMap) — The Element.attributes
object to be traversedcallback(function) — The function to be called for each Attr
object. It should take two parametres:nameandvalue
findParentsWithChild(
obj: object,
childName: string,
): Array.<object>
Recursive traversal of all nodes of the given object looking for children having the childName attribute
WARNING: Don't call this method on objects with circular dependencies!
Parameters
obj(object) — The object to be analizedchildName(string) — Name of the attribute to search for
Returns
Array.<object>
getCaretCharacterOffsetWithin(element: object): number
Gets the caret position within the given element. Thanks to
Tim Down answers in:
http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container
and http://stackoverflow.com/questions/6240139/highlight-text-range-using-javascript/6242538
Parameters
element(object) — A DOM element
Returns
number
getTextNodesIn(node: object): Array.<object>
Utility function called by module:Utils.getCaretCharacterOffsetWithin
Parameters
node(object) — A text node
Returns
Array.<object>
setSelectionRange(el: object, start: number, end: number)
Sets the selection range (or the cursor position, when start and end are the same) to a
specific position inside a DOM element.
Parameters
el(object) — The DOM element where to set the cursorstart(number) — The start position of the selection (or cursor position)end(number) — The end position of the selection. When null or identical tostart,
indicates a cursor position.
mReplace(replacements: Array.<Object>, str: String): String
Performs multiple replacements on the provided string
See: https://stackoverflow.com/questions/2501435/replacing-multiple-patterns-in-a-block-of-data
Parameters
replacements(Array.<Object>) — Array of pairs formed by an "expression" (regexp or string) and a "value" (string) to replace the fragments foundstr(String) — The string to be checked for replacements
Returns
String
Instance Fields
_messages
Current dictionary of string translations
Other
Event
The Event interface represents an event which takes place in the DOM.
HTMLElement
The HTMLElement interface represents any HTML element. Some elements directly implement this
interface, others implement it via an interface that inherits it.
jQuery
A jQuery object
jqXHR
The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset
of the browser's native XMLHttpRequest object.
As of jQuery 1.5, jqXHR objects implement the Promise interface, giving them
all the properties, methods, and behavior of a Promise.
CanvasRenderingContext2D
The CanvasRenderingContext2D interface provides the 2D rendering context for the drawing surface
of a <canvas> element.
HTMLImageElement
The HTMLImageElement interface provides special properties and methods (beyond the regular
HTMLElement interface it
also has available to it by inheritance) for manipulating the layout and presentation of
<img> elements.
HTMLAudioElement
The HTMLAudioElement interface provides access to the properties of <audio> elements, as
well as methods to manipulate them. It derives from the
HTMLMediaElement interface.
AudioContext
The AudioContext interface represents an audio-processing graph built from audio modules linked together.
Collator
The Intl.Collator object is a constructor for collators, objects that enable language sensitive
string comparison.
JSZip
A JSZip object
MediaRecorder
The MediaRecorder interface of the MediaRecorder API
provides functionality to easily capture media.
Promise
The Promise object is used for asynchronous computations. A Promise represents an operation
that hasn't completed yet, but is expected in the future.
Storage
The Storage interface of the Web Storage API provides access to the session storage or local storage for a particular domain,
allowing you to for example add, modify or delete stored data items.
NamedNodeMap
The NamedNodeMap interface represents a collection of Attr objects. Objects inside a NamedNodeMap are not in any particular
order, unlike NodeList, although they may be accessed by an index as in an array.
MidiPlayerJS
MidiPlayerJS is a JavaScript library which reads standard MIDI files and emits JSON events in real time.
Date
JavaScript Date objects represent a single moment in time in a platform-independent format.
HTMLStyleElement
The HTMLStyleElement interface represents a style element.
It inherits properties and methods from its parent, HTMLElement, and from LinkStyle.
HTMLLinkElement
The HTMLLinkElement interface represents reference information for external resources and the relationship of those resources to a document and vice versa.
It inherits properties and methods from its parent, HTMLElement, and from LinkStyle.
Instrument
Type of MIDI instrument used by Soundfont Player
pkg
Exports third-party NPM packages used by JClic, so they become available to other scripts through
the global variable JClicObject (defined in module:JClic.JClic)
LOG_LEVELS: Array.<string>
List of valid verbosity levels
LOG_PRINT_LABELS: Array.<string>
Labels printed on logs for each message type
LOG_OPTIONS: object
Options of the logging system
FALSE: number
TRUE: number
DEFAULT: number
$HTML: object
Utility object that provides several methods to build simple and complex DOM objects
settings
Global constants
Utils
Miscellaneous utility functions and constants