Global

Members

fetchOptions

Description:
Source:
Example

make POST default method

fetchOptions.method = "POST"
await afetch("url.com")

Methods

$(selector, docopt) → {null|HTMLElement}

Description:
  • An alias to document.querySelector, doc can be an Element, empty or non-string selectors will return null

Source:
Parameters:
Name Type Attributes Description
selector string
doc HTMLElement <optional>
Returns:
Type Description
null | HTMLElement
Example
var el = app.$("#div")

$all(selector, docopt) → {null|Array.<HTMLElement>}

Description:
  • An alias for document.querySelectorAll

Source:
Parameters:
Name Type Attributes Description
selector string
doc HTMLElement <optional>
Returns:
Type Description
null | Array.<HTMLElement>
Example
Array.from(app.$all("input")).find((el) => !(el.readOnly || el.disabled || el.type == "hidden"));

$append(element, template, setupopt)

Description:
  • Append nodes from the template to the given element, call optional setup callback for each node.

Source:
Parameters:
Name Type Attributes Description
element string | HTMLElement
template string | HTMLElement

can be a string with HTML or a template element.

setup function <optional>
Example
app.$append(document, "<div>...</div>")

$attr(element, attr, valueopt) → {undefined|any}

Description:
  • Return or set attribute by name from the given element.

Source:
Parameters:
Name Type Attributes Description
element HTMLElement | string
attr string
value any <optional>
  • undefined - return the attribute value
  • null - remove attribute
  • any - assign new value
Returns:
Type Description
undefined | any

$data(element, levelopt) → {Proxy|undefined}

Description:
  • Return component data instance for the given element or the main component if omitted. This is for debugging purposes or cases when calling some known method is required.

Source:
Parameters:
Name Type Attributes Description
element string | HTMLElement
level number <optional>

if is not a number then the closest scope is returned otherwise only the requested scope at the level or undefined. This is useful for components to make sure they use only the parent's scope for example.

Returns:
Type Description
Proxy | undefined

to get the actual object pass it to Alpine.raw(app.$data())

$elem(name, optionsopt)

Description:
  • Create a DOM element with attributes, -name means style.name, .name means a property name, all other are attributes, functions are event listeners

Source:
Parameters:
Name Type Attributes Description
name string
...args any | object <optional>
options object <optional>
Examples
$elem("div", "id", "123", "-display", "none", "._x-prop", "value", "click", () => {})

Similar to above but all properties and attributes are taken from an object, in this form options can be passed, at the moment only options for addEventListener are supported.

$elem("div", { id: "123", "-display": "none", "._x-prop": "value", click: () => {} }, { signal })

$empty(element, cleanupopt) → {HTMLElement}

Description:
  • Remove all nodes from the given element, call the cleanup callback for each node if given

Source:
Parameters:
Name Type Attributes Description
element HTMLElement | string
cleanup functions <optional>
Returns:
Type Description
HTMLElement

$event(element, name, detailopt)

Description:
  • Send a CustomEvent using DispatchEvent to the given element, true is set to composed, cancelable and bubbles properties.

Source:
Parameters:
Name Type Attributes Description
element HTMLElement
name string
detail object <optional>

$off(element, event, callback)

Description:
  • An alias for element.removeEventListener

Source:
Parameters:
Name Type Attributes Description
element HTMLElement
event string
callback function
...args any <optional>

additional params to removeEventListener

$on(element, event, callback)

Description:
  • An alias for element.addEventListener

Source:
Parameters:
Name Type Attributes Description
element HTMLElement
event string
callback function
...args any <optional>

additional params to addEventListener

Example
app.$on(window, "popstate", () => { ... })

$param(name, dfltopt) → {string}

Description:
  • Returns a query parameter value from the current document location

Source:
Parameters:
Name Type Attributes Description
name string
dflt string <optional>
Returns:
Type Description
string

$parse(html, formatopt)

Description:
  • A shortcut to DOMParser, default is to return the .body.

Source:
Parameters:
Name Type Attributes Description
html string
format string <optional>

defines the result format:

  • list - the result will be an array with all body child nodes, i.e. simpler to feed it to Element.append()
  • doc - return the whole parsed document
Example
document.append(...$parse("<div>...</div>"), 'list'))

$ready(callback)

Description:
  • Run callback once the document is loaded and ready, it uses setTimeout to schedule callbacks

Source:
Parameters:
Name Type Description
callback function
Example
app.$ready(() => {

})

__(…args) → {string}

Description:
  • Empty locale translator

Source:
Parameters:
Name Type Attributes Description
args any <repeatable>
Returns:
Type Description
string

(async) afetch(url, optionsopt)

Description:
  • Promisified fetch which returns a Promise, all exceptions are passed to the reject handler, no need to use try..catch Return everything in an object { ok, status, err, data, info }.

Source:
Parameters:
Name Type Attributes Description
url string
options object <optional>
Example
const { err, data } = await afetch("https://localhost:8000")

const { ok, err, status, data } = await afetch("https://localhost:8000")
if (!ok) console.log(status, err);

call(obj, methodopt)

Description:
  • Call a function safely with context and arguments:

Source:
Parameters:
Name Type Attributes Description
obj object | function
method string | function <optional>
...args any <optional>
Example
app.call(func,..)
app.call(obj, func, ...)
app.call(obj, method, ...)

emit(event, …args)

Description:
  • Send an event to all listeners at once, one by one.

    If the event ends with :* it means notify all listeners that match the beginning of the given pattern, for example:

Source:
Parameters:
Name Type Attributes Description
event string
args any <repeatable>
Example

notify topic:event1, topic:event2, ...

app.emit("topic:*",....)

escape(str) → {string}

Description:
  • Convert common special symbols into xml entities

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

fetch(url, optionsopt, callbackopt)

Description:
  • Fetch remote content, wrapper around Fetch API

    NOTE: Saves X-CSRF-Token header and sends it back with subsequent requests

Source:
Parameters:
Name Type Attributes Description
url string

URL to fetch

options object <optional>
Properties
Name Type Attributes Description
method string <optional>

GET, POST,...GET is default or from app.fetchOptions.method

post boolean <optional>

set method to POST

body string | object | FormData <optional>

a body accepted by window.fetch

dataType string <optional>

explicit return type: text, blob, default is auto detected between text or json

headers object <optional>

an object with additional headers to send, all global headers from app.fetchOptions.headers also are merged

request object <optional>

properties to pass to fetch options according to Web API RequestInit

callback function <optional>

callback as (err, data, info) where info is an object { status, headers, type }

Example
fetch("http://api.host.com/user/123", (err, data, info) => {
   if (info.status == 200) console.log(data, info);
});

forEach(list, iterator, callback, direct)

Description:
  • Apply an iterator function to each item in an array in parallel. Execute a callback when all items have been completed or immediately if there is an error provided.

Source:
Parameters:
Name Type Description
list Array.<any>
iterator function
callback function
direct boolean

controls how the final callback is called, if true it is called directly otherwisde via setImmediate

Example
forEach([ 1, 2, 3 ], function (i, next) {
  console.log(i);
  next();
}, (err) => {
  console.log('done');
});

forEachSeries(list, iterator, callbackopt, directopt)

Description:
  • Apply an iterator function to each item in an array serially. Execute a callback when all items have been completed or immediately if there is is an error provided.

Source:
Parameters:
Name Type Attributes Default Description
list Array.<any>
iterator function
callback function <optional>
direct boolean <optional>
true
Example
forEachSeries([ 1, 2, 3 ], function (i, next, data) {
   console.log(i, data);
   next(null, data);
}, (err, data) => {
   console.log('done', data);
});

hideAlert(container, optionsopt)

Description:
  • Hide active Bootstrap alert

Source:
Parameters:
Name Type Attributes Description
container HTMLElement
options Object <optional>

hideToast()

Description:
  • Hide active toasts inside first .toast-container

Source:

isArray(val) → {any|Array.<any>}

Description:
  • Returns the array if the value is non empty array or dflt value if given or undefined

Source:
Parameters:
Name Type Description
val any
Returns:
Type Description
any | Array.<any>

isElement(element) → {HTMLElement|undefined}

Description:
  • Returns the element itself if it is a HTMLElement

Source:
Parameters:
Name Type Description
element any
Returns:
Type Description
HTMLElement | undefined

isFlag(list, item) → {boolean}

Source:
Parameters:
Name Type Description
list Array.<any>
item any | Array.<any>
Returns:
Type Description
boolean

true if item exists in the array list, search is case sensitive. if item is an array it will return true if any element in the array exists in the list.

isFunction(callback) → {function|undefined}

Description:
  • Returns the callback is it is a function

Source:
Parameters:
Name Type Description
callback any
Returns:
Type Description
function | undefined

isNumber(num) → {number|undefined}

Description:
  • Returns the num itself if it is a number

Source:
Parameters:
Name Type Description
num any
Returns:
Type Description
number | undefined

isObject(obj) → {object|undefined}

Description:
  • Returns the obj itself if it is a not null object

Source:
Parameters:
Name Type Description
obj any
Returns:
Type Description
object | undefined

isString(str) → {string}

Description:
  • Returns the str itself if it is not empty or ""

Source:
Parameters:
Name Type Description
str any
Returns:
Type Description
string

loadResources(urls, optionsopt)

Description:
  • Inject CSS/Script resources into the current page, all urls are loaded at the same time by default.

Source:
Parameters:
Name Type Attributes Description
urls Array.<string> | string

list of urls to load

options object <optional>
Properties
Name Type Attributes Description
series boolean <optional>

load urls one after another

callback function <optional>

will be called with (el, opts) args for customizations after loading each url or on error

attrs object <optional>

is an object with attributes to set like nonce, ...

timeout int <optional>

call the callback after timeout

log()

Description:
  • Alias to console.log

Source:

noop()

Description:
  • Empty function

Source:

off(event|namespace, callbackopt)

Description:
  • Remove all event listeners for the event name and exact callback or namespace

Source:
Parameters:
Name Type Attributes Description
event|namespace string
  • event name if callback is not empty
  • namespace if no callback
callback function | string <optional>
  • function - exact callback to remove for the event
  • string - namespace for the event
Example
app.on("component:*", (ev) => { ... }, "myapp")
...
app.off("myapp")

on(event, callback, namespaceopt)

Description:
  • Listen on event, the callback is called synchronously, optional namespace allows deleting callbacks later easier by not providing exact function by just namespace.

Source:
Parameters:
Name Type Attributes Description
event string
callback function
namespace string <optional>

once(event, callback, namespaceopt)

Description:
  • Listen on event, the callback is called only once

Source:
Parameters:
Name Type Attributes Description
event string
callback function
namespace string <optional>

only(event, callback, namespaceopt)

Description:
  • Remove all current listeners for the given event, if a callback is given make it the only listener.

Source:
Parameters:
Name Type Attributes Description
event string
callback function
namespace string <optional>

parallel(tasks, callbackopt, directopt)

Description:
  • Execute a list of functions in parallel and execute a callback upon completion or occurance of an error. Each function will be passed a callback to signal completion. The callback accepts an error for the first argument. The iterator and callback will be called via setImmediate function to allow the main loop to process I/O unless the direct argument is true

Source:
Parameters:
Name Type Attributes Default Description
tasks Array.<function()>
callback function <optional>
direct boolean <optional>
true

parsePath(path) → {Object}

Description:
  • Parses component path and returns an object with at least { name, params } ready for rendering. External urls are ignored.

    Passing an object will retun a shallow copy of it with name and params properties possibly set if not provided.

    The path can be:

    • component name
    • relative path: name/param1/param2/param3/....
    • absolute path: /app/name/param1/param2/...
    • URL: https://host/app/name/param1/...

    All parts from the path and query parameters will be placed in the params object.

    The .html extention will be stripped to support extrernal loading but other exts will be kept as is.

Source:
Parameters:
Name Type Description
path string | object
Returns:
Type Description
Object

in format { name, params }

register(name, options, render, cleanup, data)

Description:
  • Register a render plugin, at least 2 functions must be defined in the options object:

Source:
Parameters:
Name Type Attributes Description
name string
options object
render function

(element, options) to show a component, called by render

cleanup function

(element) - optional, run additional cleanups before destroying a component

data function

(element) - return the component class instance for the given element or the main

options.default boolean <optional>

if not empty make this plugin default

options.Component class <optional>

optional base component constructor, it will be registered as app.{Type}Component, like AlpineComponent, KoComponent,... to easy create custom components in CDN mode

The reason for plugins is that while this is designed for Alpine.js, the idea originated by using Knockout.js with this system, the plugin can be found at app.ko.js.

There is a simple plugin in examples/simple.js to show how to use it without any rendering engine with vanillla HTML, not very useful though.

render(options, dfltopt) → {object|undefined}

Description:
  • Show a component, options can be a string to be parsed by parsePath or an object with { name, params } properties. if no params.$target provided a component will be shown inside the main element defined by $target.

    It returns the resolved component as described in resolve method after rendering or nothing if nothing was shown.

    When showing main app the current component is asked to be deleted first by sending an event prepare:delete, a component that is not ready to be deleted yet must set the property event.stop in the event handler onPrepareDelete(event) in order to prevent rendering new component.

    To explicitly disable history pass options.$nohistory or params.$nohistory otherwise main components are saved automatically by sending the path:save event.

    A component can globally disable history by creating a static property $nohistory in the class definition.

    To disable history all together set app.$nohistory = true.

Source:
Parameters:
Name Type Attributes Description
options string | object
dflt string <optional>
Returns:
Type Description
object | undefined

resolve(path, dfltopt) → {object}

Description:
  • Returns an object with template and component properties.

    Calls parsePath first to resolve component name and params.

    Passing an object with 'template' set will reuse it, for case when template is already resolved.

    The template property is set as:

    • try app.templates[.name]
    • try an element with ID name and use innerHTML
    • if not found and dflt is given try the same with it
    • if template texts starts with # it means it is a reference to another element's innerHTML, otemplate is set with the original template before replacing the template property
    • if template text starts with $ it means it is a reference to another template in app.templates, otemplate is set with the original template before replacing the template property

    The component property is set as:

    • try app.components[.name]
    • try app.components[dflt]
    • if resolved to a function return
    • if resolved to a string it refers to another component, try app.templates[component], ocomponent is set with the original component string before replacing the component property

    if the component property is empty then this component is HTML template.

Source:
Parameters:
Name Type Attributes Description
path string
dflt string <optional>
Returns:
Type Description
object

in format { name, params, template, component }

restorePath(path)

Description:
  • Show a component by path, it is called on path:restore event by default from start and is used to show first component on initial page load. If the path is not recognized or no component is found then the default index component is shown.

Source:
Parameters:
Name Type Description
path string

sanitizer(html, list) → {Array.<Node>|string}

Description:
  • HTML sanitizer, based on Bootstrap internal sanitizer

Source:
Parameters:
Name Type Description
html strings
list boolean

if true return a list of Nodes

Returns:
Type Description
Array.<Node> | string

savePath(options)

Description:
  • Saves the given component in the history as ** /name/param1/param2/param3/.. **

    It is called on every component:create event for main components as a microtask, meaning immediate callbacks have a chance to modify the behaviour.

Source:
Parameters:
Name Type Description
options Object

sendFile(url, options, callbackopt)

Description:
  • Send file(s) and forms

Source:
Parameters:
Name Type Attributes Description
url string
options object
Properties
Name Type Attributes Description
files object <optional>

name/File pairs to be sent as multi-part

body object <optional>

simple form properties

json object <optional>

send as JSON blobs

callback function <optional>

series(tasks, callbackopt, directopt)

Description:
  • Execute a list of functions serially and execute a callback upon completion or occurance of an error. Each function will be passed a callback to signal completion. The callback accepts either an error for the first argument in which case the flow will be aborted and the final callback will be called immediately or some optional data to be passed to thr next iterator function as a second argument.

    The iterator and callback will be called via setImmediate function to allow the main loop to process I/O unless the direct argument is true

Source:
Parameters:
Name Type Attributes Description
tasks Array.<function()>
callback function <optional>
direct boolean <optional>
Example
series([
   function(next) {
       next(null, "data");
   },
   function(next, data) {
      setTimeout(function () { next(null, data); }, 100);
   },
], (err, data) => {
   console.log(err, data);
});

showAlert(containeropt, type, text, optionsopt)

Description:
  • Show Bootstrap alert

Source:
Parameters:
Name Type Attributes Description
container HTMLElement <optional>

show inside container or document.body

type string

type of alert: error, danger, warning, info, success, primary

text string

text to show

options Object <optional>

showToast(containeropt, type, text, optionsopt)

Source:
Parameters:
Name Type Attributes Description
container HTMLElement <optional>

show inside container or document.body

type string

type of alert: error, danger, warning, info, success, primary

text string

text to show

options Object <optional>

split(str, sepopt, optionsopt) → {Array.<string>}

Description:
  • Split string into array, ignore empty items by default

Source:
Parameters:
Name Type Attributes Default Description
str string

If str is an array and type is not specified then all non-string items will be returned as is.

sep RegExp | string <optional>
,|

separator

options object <optional>
Properties
Name Type Attributes Description
keepempty boolean <optional>

will preserve empty items, by default empty strings are ignored

notrim boolean <optional>

will skip trimming strings, trim is the default

max int <optional>

will skip strings over the specificed size if no trunc

trunc boolean <optional>

will truncate strings longer than max

regexp regexp <optional>

will skip string if not matching

noregexp regexp <optional>

will skip string if matching

number boolean <optional>

convert into a number

cap boolean <optional>

capitalize

camel boolean <optional>

camelize

lower boolean <optional>

lowercase

upper boolean <optional>

uppercase

strip string | regexp <optional>

remove occurences

replace object <optional>

an object map which characters to replace with new values

range boolean <optional>

will parse numeric ranges in the format NUM-NUM and add all numbers in between, invalid ranges are skipped

unique boolean <optional>

remove duplicate entries

Returns:
Type Description
Array.<string>

start()

Description:
  • Setup default handlers:

    • on path:restore event call restorePath to render a component from the history
    • on path:save call savePath to save the current component in the history
    • on page ready call restorePath to render the initial page

    If not called then no browser history will not be handled, up to the app to do it some other way.. One good reason is to create your own handlers to build different path and then save/restore.

Source:

stylePlugin(callback)

Description:
  • Add a callback to process classes for new components, all registered callbacks will be called on component:create event with top HTMLElement as parameter. This is for UI frameworks intergation to apply logic to added elements

Source:
Parameters:
Name Type Description
callback function
Example
app.stylePlugin((el) => {
    app.$all(".carousel", element).forEach(el => (bootstrap.Carousel.getOrCreateInstance(el)));
})

toCamel(str) → {string}

Description:
  • Convert a string into camelized format

Source:
Parameters:
Name Type Description
str string
Returns:
Type Description
string

toDate(val, dfltopt, invalidopt) → {Date}

Description:
  • Return Date object for given text or numeric date representation, for invalid date returns 1969 unless invalid parameter is given, in this case invalid date returned as null. If dflt is NaN, null or 0 returns null as well.

Source:
Parameters:
Name Type Attributes Description
val string | Date | number
dflt any <optional>
invalid boolean <optional>
Returns:
Type Description
Date

toDuration(mtime, ageopt) → {string}

Description:
  • Return duration in human format, mtime is msecs

Source:
Parameters:
Name Type Attributes Description
mtime number
age boolean <optional>

if true duration from now, as age

Returns:
Type Description
string

toNumber(val, optionsopt) → {number}

Description:
  • Safe convertion to a number, no expections, uses 0 instead of NaN, handle booleans, if float specified, returns as float.

Source:
Parameters:
Name Type Attributes Description
val any

to be converted to a number

options object <optional>
Properties
Name Type Attributes Description
dflt int <optional>

default value

float int <optional>

treat as floating number

min int <optional>

minimal value, clip

max int <optional>

maximum value, clip

incr int <optional>

a number to add before checking for other conditions

mult int <optional>

a number to multiply before checking for other conditions

novalue int <optional>

replace this number with default

zero int <optional>

replace with this number if result is 0

digits int <optional>

how many digits to keep after the floating point

bigint int <optional>

return BigInt if not a safe integer

Returns:
Type Description
number
Example
toNumber("123")
123
toNumber("1.23", { float: 1, dflt: 0, min: 0, max: 2 })
1.23

toPrice(num, optionsopt)

Description:
  • Return a test representation of a number according to the money formatting rules,

Source:
Parameters:
Name Type Attributes Description
num number
options object <optional>
Properties
Name Type Attributes Default Description
locale string <optional>
en-US
currency string <optional>
USD
display string <optional>
symbol
sign string <optional>
standard
min int <optional>
2
max int <optional>
3

toSize(size, decimalsopt)

Description:
  • Return size human readable format

Source:
Parameters:
Name Type Attributes Default Description
size number
decimals boolean <optional>
2

toTitle(name, minlenopt) → {string}

Description:
  • Convert text into capitalized words, if it is less or equal than minlen leave it as is

Source:
Parameters:
Name Type Attributes Description
name string
minlen int <optional>
Returns:
Type Description
string

trace(…args)

Description:
  • if app.debug is set then it will log arguments in the console otherwise it is no-op

Source:
Parameters:
Name Type Attributes Description
args any <repeatable>