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

Members

(static, constant) $HTML :object

Utility object that provides several methods to build simple and complex DOM objects

Type:
  • object

(static, constant) DEFAULT :number

Type:
  • number

(static, constant) FALSE :number

Type:
  • number

(static, constant) LOG_LEVELS :Array.<string>

List of valid verbosity levels

Type:
  • Array.<string>

(static, constant) LOG_OPTIONS :object

Options of the logging system

Type:
  • object

(static, constant) LOG_PRINT_LABELS :Array.<string>

Labels printed on logs for each message type

Type:
  • Array.<string>

(static, constant) TRUE :number

Type:
  • number

(static, constant) Utils

Miscellaneous utility functions and constants

(static, constant) 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)

(static, constant) settings

Global constants

(inner) _messages

Current dictionary of string translations

Methods

(static) appendStyleAtHead(css, psopt) → {external:HTMLStyleElement}

Appends a stylesheet element to the head or root node nearest to the given HTMLElement.

Parameters:
NameTypeAttributesDescription
cssstring

The content of the stylesheet

psmodule:JClicPlayer.JClicPlayer<optional>

An optional PlayStation (currently a JClicPlayer) used as a base to find the root node

Returns:
  • The appended style element
Type: 
external:HTMLStyleElement

(static) attrForEach(attributes, callback)

Traverses all the attributes defined in an Element, calling a function with its name and value as a parameters

Parameters:
NameTypeDescription
attributesexternal:NamedNodeMap

The Element.attributes
object to be traversed

callbackfunction

The function to be called for each Attr
object. It should take two parametres: name and value

(static) buildObj(objType, dataopt, initopt, paramsopt) → {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:
NameTypeAttributesDefaultDescription
objTypefunction

A class or function to be invoked to build the object.

dataobject<optional>

An optional object filled with the attributes to be assigned to the newly created object.

initany<optional>

An optional value to be passed to the function when invoked with new

paramsArray.<object><optional>
[]

Optional array of params to be passed when calling setAttributes on the final object

Returns:
  • The resulting object
Type: 
object

(static) checkColor(coloropt, defaultColoropt) → {string}

Converts java-like color codes (like '0xRRGGBB') to valid CSS values like '#RRGGBB' or 'rgba(r,g,b,a)'

Parameters:
NameTypeAttributesDescription
colorstring<optional>

A color, as codified in Java

defaultColorstring<optional>

The default color to be used

Returns:
Type: 
string

(static) checkPreferredLanguage(availableLangs, defaultLangopt, requestedLangopt) → {string}

Checks if the language preferred by the user (based on browser and/or specific settings)
is in a list of available languages.

Parameters:
NameTypeAttributesDefaultDescription
availableLangsArray.<string>

Array of available languages. It should contain at least one item.

defaultLangstring<optional>
en

Language to be used by default when not found the selected one

requestedLangstring<optional>
''

Request this specific language

Returns:
  • The most suitable language for this request
Type: 
string

(static) cleanOldLanguageTag(text) → {string}

Extracts just the ISO-639 language code from complex
expressions like "English (en)", buid by JClic Author.

Parameters:
NameTypeDescription
textstring

The expression to parse

Returns:
  • The ISO-639 language code, or '--' if none found
Type: 
string

(static) cloneObject(obj) → {object}

Clones the provided object
See: https://stackoverflow.com/questions/41474986/how-to-clone-a-javascript-es6-class-instance

Parameters:
NameTypeDescription
objobject
Returns:
Type: 
object

(static) colorHasTransparency(color) → {boolean}

Checks if the provided color has an alpha value less than 1

Parameters:
NameTypeDescription
colorstring

The color to be analyzed

Returns:
Type: 
boolean

(static) compareMultipleOptions(answer, check, checkCaseopt, numericopt) → {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:
NameTypeAttributesDefaultDescription
answerstring

The text to check against to

checkstring

String containing one or multiple options, separated by |

checkCaseboolean<optional>
false

When true, the comparing will be case-sensitive

numericboolean<optional>
false

When true, we are comparing numeric expressions

Returns:
Type: 
boolean

(static) cssToString(cssObj) → {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:
NameTypeDescription
cssObjobject
Returns:
Type: 
string

(static) endsWith(text, expr, trimopt) → {boolean}

Checks if the given string ends with the specified expression

Parameters:
NameTypeAttributesDescription
textstring

The string where to find the expression

exprstring

The expression to search for.

trimboolean<optional>

When true, the text string will be trimmed before check

Returns:
Type: 
boolean

(static) fillString(tag, repeats) → {string}

Returns a string with the given tag repeated n times

Parameters:
NameTypeDescription
tagstring

The tag to be repeated

repeatsnumber

The number of times to repeat the tag

Returns:
Type: 
string

(static) findParentsWithChild(obj, childName) → {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:
NameTypeDescription
objobject

The object to be analized

childNamestring

Name of the attribute to search for

Returns:
  • Array of children having the searched attribute
Type: 
Array.<object>

(static) fx(v, n) → {any}

Set the maximum number of decimals for a number

Parameters:
NameTypeDefaultDescription
vany

The value to be converted to a fixed number of decimals. Can be anything.

nnumber4

the maximum number of decimals

Returns:
  • When v is a number, a number with fixed decimals is returned. Otherwise, returns v
Type: 
any

(static) getAttr(obj, keysopt) → {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:
NameTypeAttributesDescription
objobject

The object to be processed

keysArray.<string><optional>

An optional array of keys to be included in the resulting object.
When null or not set, all keys of obj are included. Keys can include a default value separed by '|'.
Attributes with default value will be excluded from the resulting object.

Returns:
Type: 
object

(static) getBasePath(path) → {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:
NameTypeDescription
pathstring

The full path to be parsed

Returns:
Type: 
string

(static) getBoolean(val, defaultValueopt) → {number}

Gets a boolean value from a textual expression

Parameters:
NameTypeAttributesDefaultDescription
valstring

The value to be parsed (true for true, null or otherwise for false)

defaultValueboolean<optional>
false

The default value to return when val is false

Returns:
Type: 
number

(static) getCaretCharacterOffsetWithin(element) → {number}

Parameters:
NameTypeDescription
elementobject

A DOM element

Returns:
Type: 
number

(static) getDateTime(date) → {string}

Returns a formatted string with the provided date and time

Parameters:
NameTypeDescription
dateexternal:Date

The date to be formatted. When null or undefined, the current date will be used.

Returns:
Type: 
string

(static) getHMStime(millis) → {string}

Returns a given time in [00h 00'00"] format

Parameters:
NameTypeDescription
millisnumber

Amount of milliseconds to be processed

Returns:
Type: 
string

(static) getImgClipUrl(img, rect) → {string}

Gets a clip of the give image data, in a URL base64 encoded format

Parameters:
NameTypeDescription
imgobject

The binary data of the realized image, usually obtained from a module:bads/MediaBagElement.MediaBagElement

rectmodule:AWT.Rectangle

A rectangle containing the requested clip

Returns:
  • The URL with the image clip, as a PNG file encoded in base64
Type: 
string

(static) getMsg(key) → {string}

Function that will return the translation of the provided key
into the current language.

Parameters:
NameTypeDescription
keystring

ID of the expression to be translated

Returns:
  • The translated text
Type: 
string

(static) getNumber(val, defaultValueopt) → {number}

Gets a number from a string or another number

Parameters:
NameTypeAttributesDefaultDescription
valany

The expression to parse

defaultValuenumber<optional>
0

The default value

Returns:
Type: 
number

(static) getPath(basePath, path) → {string}

Gets the complete path of a relative or absolute URL, using the provided basePath

Parameters:
NameTypeDescription
basePathstring

The base URL

pathstring

The filename

Returns:
Type: 
string

(static) getPathPromise(basePath, path, zipopt) → {external:Promise}

Gets a promise with the complete path of a relative or absolute URL, using the provided basePath

Parameters:
NameTypeAttributesDescription
basePathstring

The base URL

pathstring

The filename

zipexternal:JSZip<optional>

An optional external:JSZip object where to look
for the file

Returns:
Type: 
external:Promise

(static) getPercent(val) → {string}

Gets the plain percent expression (without decimals) of the given value

Parameters:
NameTypeDescription
valnumber

The value to be expressed as a percentile

Returns:
Type: 
string

(static) getRelativePath(file, pathopt) → {string}

Gets the full path of file relative to basePath

Parameters:
NameTypeAttributesDescription
filestring

The file name

pathstring<optional>

The base path

Returns:
Type: 
string

(static) getRootHead(elopt) → {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:
NameTypeAttributesDescription
elexternal:HTMLElement<optional>

The element from which to start the search

Returns:
Type: 
external:HTMLElement

(static) getSvg(svg, widthopt, heightopt, fillopt) → {string}

Replaces width, height and fill attributes of a simple SVG image
with the provided values

Parameters:
NameTypeAttributesDescription
svgstring

The SVG image as XML string

widthstring<optional>

Optional setting for "width" property

heightstring<optional>

Optional setting for "height" property

fillstring<optional>

Optional setting for "fill" property

Returns:
  • The resulting svg code
Type: 
string

(static) getTextNodesIn(node) → {Array.<object>}

Parameters:
NameTypeDescription
nodeobject

A text node

Returns:
Type: 
Array.<object>

(static) getTriState(val, def) → {number}

Gets a numeric value (0, 1 or 2) from a set of possible values: false, true and default.

Parameters:
NameTypeDescription
valstring

The text to be parsed

defany

An optional default value

Returns:
Type: 
number

(static) getVal(val, defaultValueopt) → {any}

Gets a value from an given expression that can be null, undefined or empty string ('')

Parameters:
NameTypeAttributesDefaultDescription
valany

The expression to parse

defaultValueany<optional>
null

The value to return when val is null, '' or undefined

Returns:
Type: 
any

(static) getValue(value) → {any}

Gets the minimal representation of the given value (object, array, string, number...)

Parameters:
NameTypeDescription
valueany

The value to be processed

Returns:
Type: 
any

(static) getXmlNodeText(xml) → {string|object}

Parse the given XML node, known as containing only text elements,
and return its content as a string (when possible)

Parameters:
NameTypeDescription
xmlobject

The XML element to parse

Returns:
Type: 
string | object

(static) getXmlText(xml) → {string}

Reads paragraphs, identified by <p></p> elements, inside XML data

Parameters:
NameTypeDescription
xmlobject

The DOM-XML element to be parsed

Returns:
Type: 
string

(static) init(options, setLogopt, setLangopt) → {object}

Initializes the global settings

Parameters:
NameTypeAttributesDefaultDescription
optionsobject

An object with global settings

setLogboolean<optional>
true

When true, the log level will be set

setLangboolean<optional>
true

When true, the current language will be set

Returns:

The normalized options object

Type: 
object

(static) isEmpty(v) → {boolean}

Checks if the given value is an empty object, null or a zero-length string

Parameters:
NameTypeDescription
vany

The value to be checked

Returns:
  • true if v is {}, null or ""
Type: 
boolean

(static) isEquivalent(a, b) → {boolean}

Checks if two expressions are equivalent.
Returns true when both parameters are null or undefined, and also when both have
equivalent values.

Parameters:
NameTypeDescription
aany
bany
Returns:
Type: 
boolean

(static) isNullOrUndef(val) → {boolean}

Checks if the provided value is 'null' or 'undefined'.

Parameters:
NameTypeDescription
valany

The value to be parsed

Returns:
Type: 
boolean

(static) isSeparator(ch) → {boolean}

Check if the given char is a separator

Parameters:
NameTypeDescription
chstring

A string with a single character

Returns:
Type: 
boolean

(static) isURL(exp) → {boolean}

Checks if the given expression is an absolute URL

Parameters:
NameTypeDescription
expstring

The expression to be checked

Returns:
Type: 
boolean

(static) isWordDelimiter(ch) → {boolean}

Check if the given char is a word delimiter

Parameters:
NameTypeDescription
chstring

A string with a single character

Returns:
Type: 
boolean

(static) log(type, msg)

Reports a new message to the logging system

Parameters:
NameTypeDescription
typestring

The type of message. Mus be error, warn, info, debug or trace.

msgstring

The main message to be logged. Additional parameters can be added, like
in console.log (see: https://developer.mozilla.org/en-US/docs/Web/API/Console/log)

(static) mReplace(replacements, str) → {String}

Performs multiple replacements on the provided string
See: https://stackoverflow.com/questions/2501435/replacing-multiple-patterns-in-a-block-of-data

Parameters:
NameTypeDescription
replacementsArray.<Object>

Array of pairs formed by an "expression" (regexp or string) and a "value" (string) to replace the fragments found

strString

The string to be checked for replacements

Returns:
  • The original string with the fragments found already replaced
Type: 
String

(static) nSlash(str) → {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:
NameTypeDescription
strstring

The string to be normalized

Returns:
Type: 
string

(static) normalizeLocale(locale)

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:
NameTypeDescription
localestring

The locale expression to be normalized

Returns:

string - The normalized locale

(static) normalizeObject(obj) → {object}

Converts string values to number or boolean when needed

Parameters:
NameTypeDescription
objobject

The object to be processed

Returns:
  • A new object with normalized content
Type: 
object

(static) parseOldDate(text) → {external:Date}

Parse 'date' fields generated by "JClic Author" in format d/m/y, with
variable number of digits.

Parameters:
NameTypeDescription
textstring

The old 'date' field

Returns:
  • Always return a Date object (now, if text was invalid)
Type: 
external:Date

(static) parseXmlNode(xml, withTextopt) → {object}

Parse the provided XML element node, returning a complex object

Parameters:
NameTypeAttributesDefaultDescription
xmlobject

The root XML element to parse

withTextboolean<optional>
false

When true, any text found inside the XML element is also included in the resulting object.

Returns:
Type: 
object

(static) reduceTextsToStrings(obj) → {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:
NameTypeDescription
objobject

The object to explore

Returns:
  • The same object, with text attributes reduced to strings
Type: 
object

(static) roundTo(v, n) → {number}

Rounds v to the nearest multiple of n

Parameters:
NameTypeDescription
vnumber
nnumber

Cannot be zero!

Returns:
Type: 
number

(static) setAttr(obj, data, attr) → {object}

Fills an object with specific attributes from another data object

Parameters:
NameTypeDescription
objobject

The target object

dataobject

The data object

attrArray.<string>

The list of attributes to be copied from data to obj
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 the setAttributes method of the created object
- group {string} - Used when data is an object or an array (possible values are object and array), 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 if fn should be passed with an additional param. This param can be:
- key - The member's key

Returns:
  • Always returns obj
Type: 
object

(static) setLogLevel(level)

Establishes the current verbosity level of the logging system

Parameters:
NameTypeDescription
levelstring

One of the valid strings in module:Utils.LOG_LEVELS

(static) setSelectionRange(el, start, end)

Sets the selection range (or the cursor position, when start and end are the same) to a
specific position inside a DOM element.

Parameters:
NameTypeDescription
elobject

The DOM element where to set the cursor

startnumber

The start position of the selection (or cursor position)

endnumber

The end position of the selection. When null or identical to start,
indicates a cursor position.

(static) startsWith(text, expr, trimopt) → {boolean}

Checks if the given string starts with the specified expression

Parameters:
NameTypeAttributesDescription
textstring

The string where to find the expression

exprstring

The expression to search for.

trimboolean<optional>

When true, the text string will be trimmed before check

Returns:
Type: 
boolean

(static) 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:
NameTypeDescription
str*

The text to be tokenized

Returns:
Type: 
Array.<object>
Example
<p>stringToWords(&quot;Hello, World! That's all&quot;) returns:<br>
[<br>
{text: &quot;Hello&quot;, sep: &quot;, &quot;},<br>
{text: &quot;World&quot;, sep: &quot;! &quot;},<br>
{text: &quot;That&quot;, sep: &quot;'&quot;},<br>
{text: &quot;s&quot;, sep: &quot; &quot;},<br>
{text: &quot;all&quot;, sep: &quot;&quot;},<br>
]</p>

(static) svgToURI(svg, widthopt, heightopt, fillopt) → {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:
NameTypeAttributesDescription
svgstring

The SVG image as XML string

widthstring<optional>

Optional setting for "width" property

heightstring<optional>

Optional setting for "height" property

fillstring<optional>

Optional setting for "fill" property

Returns:
  • The resulting Data URI
Type: 
string

(static) toCssSize(exp, css, key, def) → {string}

Converts the given expression into a valid value for CSS size values

Parameters:
NameTypeDescription
expstring | number

The expression to be evaluated. Can be a numeric value, null or undefined.
Positive values are in "px" units, negative ones are "%"

cssobject

An optional Object where the resulting expression (if any) will be saved

keystring

The key under which the result will be stored in css

defstring

Default value to be used when exp is null or undefined

Returns:
  • A valid CSS value, or null if it can't be found. Default units are px
Type: 
string

(static) zp(val) → {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:
NameTypeDescription
valnumber

The number to be processed

Returns:
Type: 
string