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
- object
(static, constant) DEFAULT :number
- number
(static, constant) FALSE :number
- number
(static, constant) LOG_LEVELS :Array.<string>
List of valid verbosity levels
- Array.<string>
(static, constant) LOG_OPTIONS :object
Options of the logging system
- object
(static, constant) LOG_PRINT_LABELS :Array.<string>
Labels printed on logs for each message type
- Array.<string>
(static, constant) TRUE :number
- 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
.
Name | Type | Attributes | Description |
---|---|---|---|
css | string | The content of the stylesheet | |
ps | module:JClicPlayer. | <optional> | An optional |
- The appended style element
(static) attrForEach(attributes, callback)
Traverses all the attributes defined in an Element, calling a function with its name and value as a parameters
Name | Type | Description |
---|---|---|
attributes | external:NamedNodeMap | The Element.attributes |
callback | function | The function to be called for each Attr |
(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
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
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 with | |
params | Array.<object> | <optional> | [] | Optional array of params to be passed when calling |
- 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)'
Name | Type | Attributes | Description |
---|---|---|---|
color | string | <optional> | A color, as codified in Java |
defaultColor | string | <optional> | The default color to be used |
- 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.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
availableLangs | Array.<string> | Array of available languages. It should contain at least one item. | ||
defaultLang | string | <optional> | en | Language to be used by default when not found the selected one |
requestedLang | string | <optional> | '' | Request this specific language |
- 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.
Name | Type | Description |
---|---|---|
text | string | The expression to parse |
- 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
Name | Type | Description |
---|---|---|
obj | object |
- Type:
- object
(static) colorHasTransparency(color) → {boolean}
Checks if the provided color has an alpha value less than 1
Name | Type | Description |
---|---|---|
color | string | The color to be analyzed |
- 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.
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
answer | string | The text to check against to | ||
check | string | String containing one or multiple options, separated by | ||
checkCase | boolean | <optional> | false | When true, the comparing will be case-sensitive |
numeric | boolean | <optional> | false | When true, we are comparing numeric expressions |
- 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.
Name | Type | Description |
---|---|---|
cssObj | object |
- Type:
- string
(static) endsWith(text, expr, trimopt) → {boolean}
Checks if the given string ends with the specified expression
Name | Type | Attributes | Description |
---|---|---|---|
text | string | The string where to find the expression | |
expr | string | The expression to search for. | |
trim | boolean | <optional> | When |
- Type:
- boolean
(static) fillString(tag, repeats) → {string}
Returns a string with the given tag
repeated n times
Name | Type | Description |
---|---|---|
tag | string | The tag to be repeated |
repeats | number | The number of times to repeat the tag |
- 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!
Name | Type | Description |
---|---|---|
obj | object | The object to be analized |
childName | string | Name of the attribute to search for |
- Array of children having the searched attribute
- Type:
- Array.<object>
(static) fx(v, n) → {any}
Set the maximum number of decimals for a number
Name | Type | Default | Description |
---|---|---|---|
v | any | The value to be converted to a fixed number of decimals. Can be anything. | |
n | number | 4 | the maximum number of decimals |
- When
v
is a number, a number with fixed decimals is returned. Otherwise, returnsv
- 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.
Name | Type | Attributes | Description |
---|---|---|---|
obj | object | The object to be processed | |
keys | Array.<string> | <optional> | An optional array of keys to be included in the resulting object. |
- 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.
Name | Type | Description |
---|---|---|
path | string | The full path to be parsed |
- Type:
- string
(static) getBoolean(val, defaultValueopt) → {number}
Gets a boolean value from a textual expression
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
val | string | The value to be parsed ( | ||
defaultValue | boolean | <optional> | false | The default value to return when |
- Type:
- number
(static) getCaretCharacterOffsetWithin(element) → {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
Name | Type | Description |
---|---|---|
element | object | A DOM element |
- Type:
- number
(static) getDateTime(date) → {string}
Returns a formatted string with the provided date and time
Name | Type | Description |
---|---|---|
date | external:Date | The date to be formatted. When |
- Type:
- string
(static) getHMStime(millis) → {string}
Returns a given time in [00h 00'00"] format
Name | Type | Description |
---|---|---|
millis | number | Amount of milliseconds to be processed |
- Type:
- string
(static) getImgClipUrl(img, rect) → {string}
Gets a clip of the give image data, in a URL base64 encoded format
Name | Type | Description |
---|---|---|
img | object | The binary data of the realized image, usually obtained from a |
rect | module:AWT. | A rectangle containing the requested clip |
- 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.
Name | Type | Description |
---|---|---|
key | string | ID of the expression to be translated |
- The translated text
- Type:
- string
(static) getNumber(val, defaultValueopt) → {number}
Gets a number from a string or another number
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
val | any | The expression to parse | ||
defaultValue | number | <optional> | 0 | The default value |
- Type:
- number
(static) getPath(basePath, path) → {string}
Gets the complete path of a relative or absolute URL, using the provided basePath
Name | Type | Description |
---|---|---|
basePath | string | The base URL |
path | string | The filename |
- 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
Name | Type | Attributes | Description |
---|---|---|---|
basePath | string | The base URL | |
path | string | The filename | |
zip | external:JSZip | <optional> | An optional |
- Type:
- external:Promise
(static) getPercent(val) → {string}
Gets the plain percent expression (without decimals) of the given value
Name | Type | Description |
---|---|---|
val | number | The value to be expressed as a percentile |
- Type:
- string
(static) getRelativePath(file, pathopt) → {string}
Gets the full path of file
relative to basePath
Name | Type | Attributes | Description |
---|---|---|---|
file | string | The file name | |
path | string | <optional> | The base path |
- 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.
Name | Type | Attributes | Description |
---|---|---|---|
el | external:HTMLElement | <optional> | The element from which to start the search |
- 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
Name | Type | Attributes | Description |
---|---|---|---|
svg | string | The SVG image as XML string | |
width | string | <optional> | Optional setting for "width" property |
height | string | <optional> | Optional setting for "height" property |
fill | string | <optional> | Optional setting for "fill" property |
- The resulting svg code
- Type:
- string
(static) getTextNodesIn(node) → {Array.<object>}
Utility function called by module:Utils.getCaretCharacterOffsetWithin
Name | Type | Description |
---|---|---|
node | object | A text node |
- 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
.
Name | Type | Description |
---|---|---|
val | string | The text to be parsed |
def | any | An optional default value |
- Type:
- number
(static) getVal(val, defaultValueopt) → {any}
Gets a value from an given expression that can be null
, undefined
or empty string ('')
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
val | any | The expression to parse | ||
defaultValue | any | <optional> | null | The value to return when |
- Type:
- any
(static) getValue(value) → {any}
Gets the minimal representation of the given value (object, array, string, number...)
Name | Type | Description |
---|---|---|
value | any | The value to be processed |
- 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)
Name | Type | Description |
---|---|---|
xml | object | The XML element to parse |
- Type:
- string |
object
(static) getXmlText(xml) → {string}
Reads paragraphs, identified by <p></p>
elements, inside XML data
Name | Type | Description |
---|---|---|
xml | object | The DOM-XML element to be parsed |
- Type:
- string
(static) init(options, setLogopt, setLangopt) → {object}
Initializes the global settings
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
options | object | An object with global settings | ||
setLog | boolean | <optional> | true | When |
setLang | boolean | <optional> | true | When |
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
Name | Type | Description |
---|---|---|
v | any | The value to be checked |
true
ifv
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.
Name | Type | Description |
---|---|---|
a | any | |
b | any |
- Type:
- boolean
(static) isNullOrUndef(val) → {boolean}
Checks if the provided value is 'null' or 'undefined'.
Name | Type | Description |
---|---|---|
val | any | The value to be parsed |
- Type:
- boolean
(static) isSeparator(ch) → {boolean}
Check if the given char is a separator
Name | Type | Description |
---|---|---|
ch | string | A string with a single character |
- Type:
- boolean
(static) isURL(exp) → {boolean}
Checks if the given expression is an absolute URL
Name | Type | Description |
---|---|---|
exp | string | The expression to be checked |
- Type:
- boolean
(static) isWordDelimiter(ch) → {boolean}
Check if the given char is a word delimiter
Name | Type | Description |
---|---|---|
ch | string | A string with a single character |
- Type:
- boolean
(static) log(type, msg)
Reports a new message to the logging system
Name | Type | Description |
---|---|---|
type | string | The type of message. Mus be |
msg | string | The main message to be logged. Additional parameters can be added, like |
(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
Name | Type | Description |
---|---|---|
replacements | Array.<Object> | Array of pairs formed by an "expression" (regexp or string) and a "value" (string) to replace the fragments found |
str | String | The string to be checked for replacements |
- 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
Name | Type | Description |
---|---|---|
str | string | The string to be normalized |
- 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.
Name | Type | Description |
---|---|---|
locale | string | The locale expression to be normalized |
string - The normalized locale
(static) normalizeObject(obj) → {object}
Converts string values to number or boolean when needed
Name | Type | Description |
---|---|---|
obj | object | The object to be processed |
- 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.
Name | Type | Description |
---|---|---|
text | string | The old 'date' field |
- 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
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
xml | object | The root XML element to parse | ||
withText | boolean | <optional> | false | When |
- 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"}}
Name | Type | Description |
---|---|---|
obj | object | The object to explore |
- The same object, with text attributes reduced to strings
- Type:
- object
(static) roundTo(v, n) → {number}
Rounds v
to the nearest multiple of n
Name | Type | Description |
---|---|---|
v | number | |
n | number | Cannot be zero! |
- Type:
- number
(static) setAttr(obj, data, attr) → {object}
Fills an object with specific attributes from another data object
Name | Type | Description |
---|---|---|
obj | object | The target object |
data | object | The data object |
attr | Array.<string> | The list of attributes to be copied from |
- Always returns
obj
- Type:
- object
(static) setLogLevel(level)
Establishes the current verbosity level of the logging system
Name | Type | Description |
---|---|---|
level | string | One of the valid strings in |
(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.
Name | Type | Description |
---|---|---|
el | object | The DOM element where to set the cursor |
start | number | The start position of the selection (or cursor position) |
end | number | The end position of the selection. When null or identical to |
(static) startsWith(text, expr, trimopt) → {boolean}
Checks if the given string starts with the specified expression
Name | Type | Attributes | Description |
---|---|---|---|
text | string | The string where to find the expression | |
expr | string | The expression to search for. | |
trim | boolean | <optional> | When |
- 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.
Name | Type | Description |
---|---|---|
str | * | The text to be tokenized |
- Type:
- Array.<object>
<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>
(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.
Name | Type | Attributes | Description |
---|---|---|---|
svg | string | The SVG image as XML string | |
width | string | <optional> | Optional setting for "width" property |
height | string | <optional> | Optional setting for "height" property |
fill | string | <optional> | Optional setting for "fill" property |
- 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
Name | Type | Description |
---|---|---|
exp | string | | The expression to be evaluated. Can be a numeric value, |
css | object | An optional Object where the resulting expression (if any) will be saved |
key | string | The key under which the result will be stored in |
def | string | Default value to be used when |
- A valid CSS value, or
null
if it can't be found. Default units arepx
- 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
Name | Type | Description |
---|---|---|
val | number | The number to be processed |
- Type:
- string