JSLib is a collection of lightweight JavaScript/Typescript modules and scripts for web development.
Module | Description |
---|---|
bbcode | A BBCode parser. |
bbcode_tags | A collection of BBCode tags. |
bind | Function for creating Attr and Text nodes that update their textContent automatically. |
casefold | A single function module that provides unicode case folding. |
conn | Convenience wrappers around XMLHttpRequest and WebSocket. |
css | A simple CSS management library. |
datatable | Custom Element for filtering, sorting, and paging a tabular data. |
dom | Functions for manipulating the DOM. |
drag | Library for making browser Drag'n'Drop easier to use. |
events | Functions to simplify starting & stopping global keyboard and mouse events. |
fraction | An infinity precision fractional math type. |
html | Functions to create HTML elements. |
inter | Classes to provide different type of internal communication. |
load | Used for initialisation. |
markdown | A CommonMark Markdown parser with extensions. |
math | Functions to create MathML elements. |
menu | Library for creating right-click menus. |
misc | Miscellaneous, simple, dependency-free functions. |
multiselect | Custom element for selecting multiple items from a list. |
nodes | Classes for handling of collections of DOM Nodes. |
pagination | Custom element for handling pagination. |
parser | The parser module can be used to parse text into token or phrase streams. |
router | Router element for SPAs. |
router_transitions | Transition effects for the Router. |
rpc | JSONRPC implementation. |
settings | Type-safe wrappers around localStorage. |
storagestate | Bindings for localStorage and sessionStorage. |
svg | Functions to create SVG elements. |
typeguard | Functions to create TypeGuards. |
urlstate | Store and retrieve state from the URL. |
windows | Custom Elements that act as application Windows. |
windows_taskbar | Custom Element that lists Windows on a TaskBar. |
windows_taskmanager | Custom Element that allows minimisation of Windows. |
Thematically, the above modules can be grouped into a few packages:
Package | Description | Members |
---|---|---|
Decorum | A collection of DOM manipulation libs. | Bind, CSS, DOM, HTML, Math, Nodes, and SVG. |
Duct | Communication libraries. | Conn, Inter, RPC, StorageState, and URLState. |
Guise | Various modules to aid with UI and UX. | DataTable, Drag, Events, Menu, MultiSelect, Pagination, and the Windows (Taskbar, Taskmanager) modules. |
Sundry | Modules that do not yet form a larger package. | BBCode (& Tags), CaseFold, Fraction, Load, Markdown, Misc, Parser, Router, Transitions, Settings, and TypeGuard. |
Script | Description |
---|---|
casefold | The scripts generates the casefold module. |
circular | This script walks a javascript import tree to determine if there are any circular imports, which may cause initialisation problems. The first argument specifies the root script. |
html | This script generates the html module. |
math | This script generates the math module. |
svg | This script generates the svg module. |
This module contains a full BBCode parser, allowing for custom tags and text handling.
The current implementation requires tags be properly nested.
This module directly imports the parser module.
Export | Type | Description |
---|---|---|
(default) | Function | This function is the main BBCode parsing function. |
CloseTag | Type | The type represents a closing tag. |
isCloseTag | Function | Intended for tag parsers, this function determines if a token is a CloseTag. |
isOpenTag | Function | Intended for tag parsers, this function determines if a token is an OpenTag. |
isString | Function | Intended for tag parsers, this function determines if a token is a string. |
OpenTag | Type | The type represents an opening tag. |
Parsers | Type | This type is an object containing the handlers for various tag types. |
process | Function | Intended for tag parsers, appends parse BBCode to the passed Node. |
TagFn | Type | A type representing a tag handler. |
text | Symbol | A Symbol used to indicate the text processor in the Parsers type passed to the (default) parsing function. |
Tokeniser | Type | Intended for tag parsers, this type represents the token generator. |
import bbcode from './bbcode.js';
import {all} from './bbcode_tags.js';
bbcode(all, "[b]Hello[/b], [u]World[/u]")
The above will return a DocumentFragment containing the following:
<span style="font-weight: bold">Hello</span>, <span style="text-decoration: underline">World</span>
(parsers: Parsers, text: string) => DocumentFragment;
This function parses the given text according, handling the tags with the given parsers, and appending all generated Nodes to a DocumentFragment, which is returned.
{
tagName: string;
fullText: string;
}
The tagName is the simply the name of the tag being closed.
The fullText is the entire parsed text of the closing tag. This can be useful when skipping over tags and you just wish to print the unparsed text.
Example: [b]Text[/b]
will result in:
{
tagName: "b",
fullText: "[/b]"
}
(t: OpenTag | CloseTag | string) => t is CloseTag;
This function returns true when passed a CloseTag.
(t: OpenTag | CloseTag | string) => t is OpenTag;
This function returns true when passed an OpenTag.
(t: OpenTag | CloseTag | string) => t is string;
This function returns true when passed a string.
{
tagName: string;
attr: string;
fullText: string;
}
The tagName is the simply the name of the tag being opened.
The attr is any attribute that was supplied with the opening tag.
The fullText is the entire parsed text of the opening tag. This can be useful when skipping over tags and you just wish to print the unparsed text.
Example: [b]Text[/b]
will result in:
{
tagName: "b",
fullText: "[b]"
}
Example: [colour=#f00]Text[/colour]
will result in:
{
tagName: "colour",
attr: "#f00",
fullText: "[colour=#f00]"
}
{
[key: string]: TagFn;
[text]: (node: Node, t: string) => void;
}
This type represents an Object, which contains the tag parsers for specific tags and the text processor. This object must contain the text Symbol, specifying a text formatting function, which takes a Node to be appended to, and the string to be formatted. In addition, this object should contain string keys, which correspond to tag names, the values of which should be TagFns.
<T extends Node>(node: T, t: Tokeniser, p: Parsers, closeTag?: string) => T;
Intended for tag parsers, this function takes a Node, a Tokeniser, a Parsers object and a closing tag name. It will run the tokeniser, handling tags according to the Parsers object, attaching the results to the passed Node, until it reaches a CloseTag matching the name specified, when it will return the original Node passed.
(node: Node, t: Tokeniser, p: Parsers) => void;
A function that takes a Node, a Tokeniser, and a Parsers object. This function should process tokens from the Tokeniser, appending to the Node, until its tag data finishes. This function should return nothing.
Generator<OpenTag | CloseTag | string, void, true | 1 | undefined>;
This type is a generator that will yield a token, which will either be a CloseTag, OpenTag, or string. When calling next on this Generator, you can pass in true to the next method retrieve the last token generated. If you pass in 1
to the next
method, when it has just outputted an OpenTag, the processor will not move past the corresponding CloseTag until 1
is again passed to the next
method.
This module contains many standard BBCode tags parsers, and a default text processor.
This module directly imports the bbcode, dom, and html modules.
Export | Type | Description |
---|---|---|
all | Parsers | An object which contains all of the tag processors and the text processor. |
none | TagFn | A special tag processor that ignores the tag and continues processing the inner text. |
text | Function | A text processor that converts all line breaks into HTMLBRElements. |
* | TagFn | All remaining exports are tag processors |
Tags | Description |
---|---|
audio | The audio tag processes its inner text as a URL and creates an HTMLAudoElement. |
b | The b tag sets bold on the contained data. |
centre/center | The centre and center tags center the contained data. |
colour/color | The colour and color tags set the attribute of the tag as the font colour of the contained data. |
font | The font tag sets the font of the contained data. |
full/justify | The full and justify tags sets full alignment for the contained data. |
h1...h6 | Tags h1, h2, h3, h4, h5, and h6 create HTMLHeadingElements around the contained data. |
highlight | The highlight tag highlights the contained data. |
hr | The hr tag inserts a horizontal rule, and has no Closing Tag. |
i | The i tag sets italic on the contained data. |
img | The img tag processes the contained text as a URL for an HTMLImageElement, and can optionally use the attribute to set the width and height of the image. The format for the attribute is w xh where either w or h can be omitted. |
left | The left tag sets left alignment for the contained data. |
list | The list tag creates a new list. The attribute determines what type of list, with no attribute resulting in an HTMLUListElement, and any of a , A , i , I , and 1 resulting in an HTMLOListElement with the type set to the specified value. Any children of the list should be wrapped in [*] [/*] tags, though the closing tag can be omitted. |
quote | The quote tag creates a HTMLQuoteElement around the contained data. Any attribute is created as an HTMLLegendElement as the first child. |
right | The right tag sets right alignment for the contained data. |
s | The s tag sets strike-through on the contained data. |
size | The size tag must have an attribute, which must be a number (0<s<=100) and is used to determine the font-size (s/10em) on the contained data. |
table | The table tag is used to create an HTMLTableElement. This table allows thead, tbody, tfoot, tr, th, and td, all of which act like their HTML counterparts. |
u | The u tag sets underline on the contained data. |
url | The url tag creates an HTMLAnchorElement, with the href set to the attribute, wrapping the contained data. If no attribute is set, the URL is taken from the containing data. |
This modules contains a Function for creating DOM nodes (such as Attr and Text nodes) that update their content automatically.
This module directly imports the dom, inter, and misc modules.
Export | Type | Description |
---|---|---|
bind | Function | Creates bound text objects that can be used with amendNode/clearNode functions. |
Binding | Class | Objects that extend this class can be used with amendNode/clearNode to create Children and Attributes that can be updated just by setting a value. |
<T extends ToString = ToString>(t: T): Binding<T>;
(strings: TemplateStringsArray, ...bindings: (Binding | ToString)[]): ReadonlyBinding<T>;
<T, B extends unknown[]>(fn: (...v: {[K in keyof B]: B[K] extends Binding<infer S> ? S : B[K]}) => T, ...bindings: B): ReadOnlyBinding<T>;
This function can be used as a normal function, binding a single value, as a template tag function, or as a constructor for a MultiBinding.
When used normally, this function takes a single starting value and returns a Binding class with that value set.
When used as a tag function, this function will return a readonly Binding that is bound to all Bind expressions used within the template.
When used to create a multi-binding, it takes, as the first argument, the function which will combine the values of the passed bindings, and the remaining arguments will be the Bindings or static value.
Both returned types can be used as attributes or children in amendNode and clearNode calls.
export type Binding<T = string> {
value: T;
constructor(value: T);
toString(): string;
transform<U>(fn: (v: T) => U): Binding<U>;
onChange(fn: (v: T) => void);
toDOM(n: ParentNode, prefix?: Children, fn: (k, v) => (Children | null), suffix?: Children) => ParentNode;
}
Objects that extend this type can be used in place of both property values and Children in calls to amendNode and clearNode, as well as the bound element functions from the html.js and svg.js modules.
When the value on the class is changed, the values of the properties and the child nodes will update accordingly.
This class implements a function that can take a new value to set the binding value. This function can also be called with no argument to simply get the value of the binding.
The transform method returns a new Binding that transforms the result of the template according to the specified function.
The onChange method runs the provided callback whenever the value changes, passing the function the current value.
The toDOM method updates the given Node with children generated by the given function, which is called in different ways depending on the type of the bound value.
- For a bound Array, the function is passed each value of the Array.
- For a bound Set, the function is passed each value of the Set.
- For a bound Map, the function is passed each key/value pair.
- For other values, the function is simple passed the bound value.
The optional prefix and suffix params add child nodes before and after those generated by the fn function.
Nodes are cached based on the first param that is passed to the node generating function.
If the function returns a null value it will be skipped and not cached. Duplicated array values will also not be cached.
The casefold module provides a simple Unicode case-folding function.
Export | Type | Description |
---|---|---|
(default) | Function | The default export folds the case on the given string according to the following table of mappings: https://www.unicode.org/Public/UCD/latest/ucd/CaseFolding.txt |
The conn module contains some convenience wrappers around XMLHttpRequest and WebSocket.
This module directly imports the inter module.
Exports | Type | Description |
---|---|---|
HTTPRequest | Function | The function provides a promise base wrapper to XMLHttpRequest. |
Properties | Type | This object is passed to a HTTPRequest to modify its options. |
WS | Function | This function provides a Promise based initialiser for WSConn. |
WSConn | Class | This class extends the WebSocket class. |
interface {
(url: string, props?: Exclude<Properties, "checker"> & {"response"?: "text" | ""}): Promise<string>;
(url: string, props: Exclude<Properties, "checker"> & {"response": "xml" | "document"}): Promise<XMLDocument>;
(url: string, props: Exclude<Properties, "checker"> & {"response": "blob"}): Promise<Blob>;
(url: string, props: Exclude<Properties, "checker"> & {"response": "arraybuffer"}): Promise<ArrayBuffer>;
(url: string, props: Exclude<Properties, "checker"> & {"response": "xh"}): Promise<XMLHttpRequest>;
<T = any>(url: string, props: Properties & {"response": "json", "checker"?: (data: unknown) => data is T}): Promise<T>;
}
In its simplest incarnation, this function takes a URL and returns a Promise which will return the string response from that URL. However, the passed Properties object can modify both how the request is sent and the response interpreted.
import {HTTPRequest} from './conn.js';
HTTPRequest("conn.js").then(data => console.log(data));
In this example to source code of the conn.js library will be printed to the console.
import {HTTPRequest} from './conn.js';
HTTPRequest("conn.js", {method: "HEAD", response: "xh"}).then(xh => console.log(xh.getResponseHeader("Content-Length")));
In this example a HEAD request is used to get print the size of conn.js library to the console.
import {HTTPRequest} from './conn.js';
const data = new FormData();
data.append("search", "name");
HTTPRequest<{names: string; count: number}>("/postHandler", {method: "POST", response: "json", data}).then(data => console.log(data.count));
In this example data is sent to a post handler, returning a JSON response which is automatically parsed.
{
method?: string;
user?: string;
password?: string;
headers?: object;
type?: string;
response?: "" | "text" | "xml" | "json" | "blob" | "arraybuffer" | "document" | "xh";
onuploadprogress?: (event: ProgressEvent) => void;
ondownloadprogress?: (event: ProgressEvent) => void;
data?: XMLHttpRequestBodyInit;
signal?: AbortSignal;
}
This object modifies an HTTPRequest. It allows setting of the following:
Field | Description |
---|---|
method | Can change the request method. |
user | Allows the setting of a Basic Authorization username. |
password | Allows the settings of a Basic Authorization password. |
headers | An object to allow the setting or arbitrary headers. |
type | Sets the Content-Type of the request. |
response | This determines the expected return type of the promise. One of text , xml , json , blob , arraybuffer , document , or xh . The default is text and xh simply returns the XMLHTTPRequest object as a response. Response type json will parse the retrieved text as JSON and return the parsed object. |
checker | This function is used to check whether parsed JSON matches the expected data structure. It is recommended to use a checker function when receiving data, and the TypeGuard module can aid with that. |
onuploadprogress | This sets an event handler to monitor any upload progress. |
ondownloadprogress | This sets an event handler to monitor any download process. |
data | This is an XMLHttpRequestBodyInit and is send as the body of the request. |
signal | An AbortSignal to be used to cancel any request. |
(url: string, protocols?: string | string[]) => new Promise<WSConn>;
This function takes a url, and an options protocol string or protocol string array, and returns a Promise which will resolve with an initiated WSConn on a successful connection.
import {WS} from './conn.js';
WS("/socket").then(ws => {
ws.when(({data}) => console.log(JSON.parse(data)))
});
This example connects a websocket to some endpoint and prints all of the JSON objects sent over it to the console.
WSConn extends the WebSocket class, allowing for the passed URL to be relative to the current URL.
In addition, it adds a method:
when<T = any, U = any>(ssFn?: (data: MessageEvent) => T, eeFn?: (data: Error) => U) => Subscription<MessageEvent>;
This method acts like the when method of the Subscription class from the inter module, taking an optional success function, which will receive a MessageEvent object, and an optional error function, which will receive an error. The method returns a Subscription object with the success and error functions set to those provided.
This module contains an extension to the CSSStyleSheet class for simple generation of CSS style elements.
Export | Type | Description |
---|---|---|
(default) | Class | The CSS class handles a collection of CSS declarations to be rendered into a style element. |
add | Function | The add method of a default instance of the default CSS class. |
at | Function | The at method of a default instance of the default CSS class. |
id | Function | The id method of a default instance of the default CSS class. |
ids | Function | The ids attribute of a default instance of the default CSS class. |
mixin | Function | This function merges two Def objects. |
render | Function | The render method of a default instance of the default CSS class. |
import {add, id, render} from './css.js';
const title = id(),
titleElem = document.createElement("div"),
nowElem = document.createElement("span");
nowElem.append("NOW");
titleElem.setAttribute("class", title);
titleElem.append("Buy ", nowElem);
add(`.${title}`, {
"font-size": "2em",
">span": {
"color": "red"
}
});
document.head.append(render());
document.body.append(titleElem);
This simple example will produce the following page:
<html lang="en"><head>
<script type="module" src="script.js"></script>
<style type="text/css">._0 { font-size: 2em; }._0 > span { color: red; }</style></head>
<body>
<div class="_0">Buy <span>NOW</span></div>
</body>
</html>
The default export is a class that extends the CSSStyleSheet interface, with the following methods:
Method | Description |
---|---|
add | A method to add a CSS declaration. |
constructor | Used to create a new instance of the class. |
id | Creates a unique ID within this instance. |
ids | Creates multiple unique IDs within this instance. |
at | A method to add a CSS at rule sections. |
render | Compiles all of the CSS declarations into a style element. |
toString | Returns the CSS declarations as a compiled string. |
class CSS {
add(defs: Record<string, Def>): this;
add(selector: string, def: Def): this;
}
This method can either be called with a CSS selector string and a Def object containing all of the style information, or and object with selector keys and Def values. The CSS instance is returned for simple method chaining.
class CSS {
at(at: string, defs?: Record<string, Def>): this;
}
This method adds an At-rule section to the CSS object, filled with the styling generated by the defs object if one is provided (as per the add method). Does not currently support nested at-rule queries.
class CSS {
constructor(prefix = "", idStart = 0);
}
The constructor takes an optional prefix, which will be applied to all returns from the id method. It will default to the underscore character if it is not provided or if the prefix given is not allowed for classes or IDs.
The idStart param defines the starting ID for returns from the id method.
class CSS {
id(): string;
}
This method will return sequential unique ids to be used as either class names or element IDs. The prefix of the string will be as provided to the constructor and the suffix will be an increasing number starting at the value provided to the constructor.
class CSS {
ids: Iterable<string> & Iterator<string>;
ids(): Iterable<string> & Iterator<string>;
ids(n: number): string[];
}
This attribute can be used with array destructuring the generate IDs as with the id method.
Alternatively, it can be called with a number to generate an array of that many IDs.
class CSS {
render(): HTMLStyleElement;
}
This method generates a new HTMLStyleElement that contains all of the data currently supplied to the class.
interface Def {
[key: string]: Value | Def;
}
This unexported interface defines the structure of the CSS data provided to the add method.
The key can refer to property name or an extended selector.
When the key is a property name, the value will be a Value type.
When the key is an extended selector, it will be logically appended to the current selector and processed as in a call to the add method with the value Def. The logical appending splits both the parent and extended selectors at the ',' separator and concatenates all pairs together, separated by ',' separators.
(base: Def, add: Def) => Def;
This function deeply adds the add
values to the base
, and returns the merged base
Def Object.
type Value = string | number | ToString;
This unexported type represents a CSS value, as either a string, number or any object with the toString method.
The datatable module adds a custom element for handling tabular data that can be filtered, sorted, and paged.
This module relies directly on the [css]{#css}, [dom]{#dom}, [html]{#html}, and [misc]{#misc] modules.
Export | Type | Description |
---|---|---|
(default) | DOMBind](#dom_dombind) | A DOMBind to create a DataTable. |
DataTable | Class | Custom element to easily create a filterable, sortable, pageable table. |
setLanguage | Function | Sets the language used by the module. |
sortArrow | Function | Helper function to generate styles for a sort indicator. |
class DataTable extends HTMLElement {
get totalRows(): number;
get pageRows(): number;
export(title = false): string[][];
exportPage(title = flase): string[][];
}
The DataTable custom element can be used to easily create filterable, sortable and pageable tables.
The element registers with the name data-table
This element directly handles the following attributes:
Attribute | Type | Description |
---|---|---|
page | Number | The page of data to show (0 indexed, default: 0). |
perPage | Number | The number of items to show on a page (default: Infinity). |
To add headers to the table, add a thead
element containing a tr
element. Inside that tr
element you can add your th
or td
header elements. For example:
<data-table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
</data-table>
The follow data-* attributes have special meaning to header cells and determine how sorting and filtering take place:
Attribute | Type | Description |
---|---|---|
data-disallow-empty | Boolean | When set, disables the ability to filter out empty cells. |
data-disallow-not-empty | Boolean | When set, disables the ability to filter out non-empty cells. |
data-empty | Boolean | When set, filters out empty cells. |
data-filter | String | Filters the cells to those containing the value of the attribute. |
data-filter-disable | Boolean | When set, disables user filtering. |
data-is-case-insensitive | Boolean | When set, the text filter is case insensitive. |
data-is-prefix | Boolean | When set, the text filter is a prefix match. When set with data-is-suffix becomes an exact match filter. |
data-is-suffix | Boolean | When set, the text filter is a suffix match. When set with data-is-prefix becomes an exact match filter. |
data-max | Number | For columns of numbers, specifies a maximum value to filter by. |
data-min | Number | For columns of numbers, specifies a minimum value to filter by. |
data-not-empty | Boolean | When set, filters out non-empty cells. |
data-sort | asc, desc | When set, sorts by the column in either asc(ending) of desc(ending) order. |
data-sort-disable | Boolean | When set, disables user sorting. |
data-type | string, number, date, time, datetime | When set, will determine how filters and sorting are conducted. |
To add the table to the table, add successive tr
elements which contain the cells for the columns. For example:
<data-table>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td>Cell 3</td>
</tr>
<tr>
<td>Cell 4</td>
<td>Cell 5</td>
<td>Cell 6</td>
</tr>
</data-table>
The data-value attribute can be specified on a cell to supply a value other than its text content.
When no header is specified, one is generated with sequentially titled columns. If no header is wanted, add an empty tr
element in a thead
element:
<data-table>
<thead>
<tr></tr>
</thead>
</data-table>
The following helper methods are provided to get information about the data in the table:
Field | Type | Description |
---|---|---|
export | Method | This method returns the data of the filtered and sorted table. When the title attribute is set to true, will prepend titles as first row of output. |
exportPage | Method | This method returns the data of the visible portion of the table. When the title attribute is set to true, will prepend titles as first row of output. |
pageRows | Getter | This method returns the number of visible rows in the table, that is the number after filtering and paging. |
totalRows | Getter | This method returns the total number of rows in the table after filtering. |
(l: {STARTS_WITH?: string | Binding; ENDS_WIDTH?: string | Binding; CASE_SENSITIVITY?: string | Binding; REMOVE_BLANK?: string | Binding; ONLY_BLANK?: string | Binding;}) => void;
The setLanguage function sets the language items used by the [DataTable]{#datatable_datatable} class.
(asc = "#f00", desc = asc, stroke = "#000") => Object;
The function generates an object which can be used with the {@link module:css | CSS} module to style the headers of a DataTable to include an arrow indicating the direction of sorting.
The asc
param specifies the colour of the Asc sorting arrow, the desc
param specifies the colour of the Desc sorting arrow, and the stroke
param specifies the outline colour of the arrows.
The dom module can be used to manipulate DOM elements.
Export | Type | Description |
---|---|---|
amendNode | Function | This convenience function modifies a Node or EventTarget. |
attr | Symbol | This symbol is used to denote a method on an object that will take an attribute name and return a new Attr Node. |
bindCustomElement | Function | This function simplified the registering of Custom Element and creating a DomBind. |
child | Symbol | This symbol is used to denote a special Object that provides its own Children. |
Children | Type | This type is a string, Node, NodeList, HTMLCollection, Binding, or a recursive array of those. |
clearNode | Function | This function acts identically to amendNode except that it clears any children before amending. |
createDocumentFragment | Function | This convenience function creates a DocumentFragment. |
DOMBind | Type | This type represents a binding of either amendNode or clearNode with the first param bound. |
event | Function | This helper function helps with setting up events for amendNode. |
eventCapture | Number | Can be passed to the event function to set the capture property on an event. |
eventOnce | Number | Can be passed to the event function to set the once property on an event. |
eventPassive | Number | Can be passed to the event function to set the passive property on an event. |
eventRemove | Number | Can be passed to the event function to set the event to be removed. |
isChildren | Function | This function determines whether the passed in object can be used as a Children type. |
isEventListenerObject | Function | This function is a typeguard for objects that satisfies the EventListenObject interface. |
isEventObject | Function | This function is a typeguard for objects that are either EventArrays, Event Functions, or EventListenObjects. |
Props | Type | A PropsObject or NamedNodeMap. |
PropsObject | Type | This object is used to set attributes and events on a Node or EventTarget with the amendNode and clearNode functions. |
tags | Function | This function takes an XML namespace and returns a special object for which the keys are DOMBinds for that key and namespace. |
toggle | Function | Can be used directly to toggle an attribute, or accepts a callback to collect the state of the toggled attribute. |
interface {
<T extends EventTarget | BoundChild>(element: T, properties: Record<`on${string}`, EventListenerObject | EventArray | Function>): T;
<T extends Node | BoundChild>(element: T, properties?: Props, children?: Children): T;
<T extends Node | BoundChild>(element: T, children?: Children): T;
<T extends Node | BoundChild>(element?: T | null, properties?: Props | Children, children?: Children): T;
}
This function is used to set attributes and children on Nodes, and events on Nodes and other EventTargets.
If the element passed is a HTMLElement or SVGElement, then a properties param is processed, applying attributes as per the PropsObject type. Likewise, any events are set or unset on a passed EventTarget, as per the PropsObject type.
For any Node, the children are set according to the Children value.
This function returns the element passed to it.
NB: Due to how this function uses instanceof to determine what can be applied to it, it will fail in unexpected ways with types created from proxies of the DOM classes, such as those used with window.open().
<T extends HTMLElement>(name: string, constructor: {new (...params: any[]): T}, options?: ElementDefinitionOptions | undefined): T;
This function registers the custom element and then returns a DOMBind for the element.
string | Node | NodeList | HTMLCollection | Children[];
This type is a string, Node, NodeList, HTMLCollection, or a recursive array of those.
(children?: Children) => DocumentFragment;
This function creates a DocumentFragment that contains any Children passed to it, as with amendNode.
interface {
<T extends EventTarget | BoundChild>(element: T, properties: Record<`on${string}`, EventListenerObject | EventArray | Function>): T;
<T extends Node | BoundChild>(element: T, properties?: Props, children?: Children): T;
<T extends Node | BoundChild>(element: T, children?: Children): T;
<T extends Node | BoundChild>(element?: T | null, properties?: Props | Children, children?: Children): T;
}
This functions works similarly to amendNode except that it replaces the children as opposed to adding to them.
interface <T extends Node> {
(properties?: Props, children?: Children): T;
(children?: Children): T;
}
This utility type is useful for any function that wants to call amendNode or clearNode with the first param set by that function, as used in the html and svg modules.
(fn: Function | EventListenerObject, options: number, signal?: AbortSignal): EventArray;
This helper function is used to create EventArrays.
The options
param is a bitmask created by ORing together the eventOnce, eventCapture, eventPassive, and eventRemove constants, as per need.
The signal
param can be used to set a AbortSignal to the signal
option of the addEventListener call. This will be unused in a event removal context.
[EventListenerOrEventListenerObject, AddEventListenerOptions, boolean];
This type can be used to set events with amendNode and clearNode. The boolean is true if the event is to be removed.
Record<string, unknown>;
The keys of this type refer to the attribute names that are to be set. The key determines what type the value should be:
Key | Description |
---|---|
on* |
Used to set events. Can be a Function, EventListenerObject, or EventArray. |
class , part |
An array of strings, a DOMTokenList, or an object with string keys and boolean or undefined values, to be used to toggle classes or parts. For the array and DOMTokenList, if a class or part begins with a ! , the class/part will be removed, if the class or part begins with a ~ , the class/part will be toggled, otherwise the class or class will be set. For the object, a value that equates to true will set the class or part, and a value that equates to false (except nullables, which will toggle the class or part) will unset the class or part. |
style |
A CSSStyleDeclaration can be used to set the style directly, or an Object can be used to set individual style properties. |
* |
For any key, a string or any object with a toString method can be used to set the field explicitly, a number can be used and converted to a string, a boolean can be used to toggle an attribute, and a undefined value can be used to remove an attribute. If a null value is specified, no action will be taken. |
(fn: (v: boolean) => void) => (v: boolean) => void;
This function can be used directly in the params object of a amendNode call to toggle an attribute on or off (depending on its previous state); e.g.
amendNode(myNode, {"attr": toggle});
If a callback is provided, then it will be called with the eventual state of the toggle; e.g.
amendNode(myNode, {"attr": toggle(state => myState = state)});
The drag module aids with handling DragEvents, allowing the transfer of complex objects without having to resort to encoding as JSON.
Export | Type | Description |
---|---|---|
DragTransfer | Class | This class creates a management object for a particular class of dragged objects. |
DragFiles | Class | This class helps with dragged Files. |
[setDragEffect](#drag_setdrageffect | Function | This function creates a helper function with sets the drop effect icon in a dragover event. |
interface CheckedDragEvent extends DragEvent {
dataTransfer: DataTransfer;
}
This unexported type is used by DragFiles is method to mark the DataTransfer as existing on a DragEvent.
interface CheckedDT<T> extends DragTransfer<T> {
get(e: DragEvent): T;
}
This unexported type is used by DragTransfers is method to mark the DragTransfers get method as guaranteed to return a T.
The DragTransfer class is used to register and handle drag targets for drop targets to retrieve. It has the following methods:
Method | Description |
---|---|
constructor | The constructor takes a format string which uniquely identifies the drag type, as per the DataTransfers setData method. |
deregister | The method unregisters a Transfer type registered with the register method. |
get | The method is to be used during a DragOver or drop event to get a drag object. |
is | This method determines if the dragged object is registered with this object. |
register | This method is used to register objects for dragging. |
set | The method is used during a dragstart event to mark an object as being dragged. |
export class DragTransfer<T = any> {
deregister(key: string): void;
}
This method takes the key returned from the register method and stops it from being used as a drag target. Required for an item to be garbage collected.
export class DragTransfer<T = any> {
get(e: DragEvent): T | undefined;
}
The get method finds the key associated with this objects format and returns the object linked to it, if available. Returns undefined if the DragEvent has not got this objects format registered, or the key is invalid.
The preventDefault method of the DragEvent object is called during this method.
export class DragTransfer<T = any> {
is(e: DragEvent): this is CheckedDT<T>;
}
To be used in dragover and drop events, this method determines is the passed DragEvents DataTransfer.types array contains this objects format string, marking this object as a CheckedDT type.
export class DragTransfer<T = any> {
register(t: Transfer<T> | () => T): string;
}
This method registers a Transfer object, or a function that returns T, to this handler and returns a unique key for this objects format. The key can be used with both the set and deregister methods.
export class DragTransfer<T = any> {
set(e: DragEvent, key: string, icon?: HTMLDivElement, xOffset = -5, yOffset = -5): void;
}
This method is used during a dragstart to mark the object being dragged. Requires the DragEvent and the key returned from the register method, and optionally takes a drag icon div and x and y offsets from the cursor.
This class allows for easier use of the files property of the DataTransfer object.
Field | Type | Description |
---|---|---|
asForm | Method | This method creates a FormData with passed files attached. |
constructor | Constructor | Takes a spread of mime types that this object will match files against. |
is | Method | This method determines if a DragEvent contains files that match the allowed mime types. |
mimes | Array | This array is the list of mime types passed to the constructor. |
class DragFiles {
asForm(e: DragEvent, name: string): FormData;
}
This method attaches all files on the DragEvent to a returned FormData data object under the name provided.
The preventDefault method of the DragEvent object is called during this method.
class DragFiles {
is(e: DragEvent): e is CheckedDragEvent;
}
This method checks all items attached to the DragEvent, returning true is all items are files that match the mime types provided to the constructor, and false otherwise.
This method also marks the DragEvent as a CheckedDragEvent if it returns true.
(effects: Partial<Record<typeof DataTransfer.prototype.dropEffect, (DragTransfer | DragFiles)[]>>) => (e: DragEvent) => boolean;
This method takes an object of dropEffect keys to arrays of DragTransfer and DragFiles objects, and returns a function. The function is to be called during a dragover event to set the dropEffect on the passed DragEvent. The icon set is determined by the first DragTransfer or DragFiles object whose format is set on the event.
interface Transfer<T> {
transfer(): T;
}
The unexported Transfer interface describes an object that will transfer a T to a caller of DragTransfer.get.
The event module is used for easy creation of global events.
This module directly imports the misc module.
Export | Type | Description |
---|---|---|
hasKeyEvent | Method | This function returns true if any function is currently active for the passed key. |
keyEvent | Method | Used for setting up keyboard event handlers. |
mouseDragEvent | Method | Used to handle mouse drag events. |
mouseMoveEvent | Method | Used to handle mouse move events. |
mouseX | Number | The current X coordinate of the mouse. |
mouseY | Number | The current Y coordinate of the mouse. |
(key: string) => boolean;
This function returns true if any function is currently active for the passed key.
(key: string | string[], onkeydown?: (e: KeyboardEvent) => void, onkeyup?: (e: KeyboardEvent) => void, once = false) => [() => void, (now = true) => void, (newKey: string | string[], now = true) => void];
This function takes a key combination or array of key combinations, an optional KeyboardEvent function to act as the keydown event handler, an optional KeyboardEvent function to act as the keyup handler, and an optional boolean (default false) to determine if the event only runs one time per activation.
The key combinations are strings which can contain key names as determined by the KeyboardEvent.key value, and can be prefixed by any number of the following: Alt+
, Option+
, Control+
, Ctrl+
, Command+
, Meta+
, Super+
, Windows+
, and Shift+
.
The function returns an array of three functions, the first of which activates the event, the second of which deactivates the event and will run any keyup event handler unless false is passed into the function.
The last function returned allows the registered key(s) to be changed to the newKey string/array passed. The now
param will be passed to the stop function when cancelling the previously assigned keys.
NB: If the window loses focus, the module will generate a keyup event. This can be detected be checking the Event.isTrusted field.
(button: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15, onmousemove?: (e: MouseEvent) => void, onmouseup: (e: MouseEvent) => void = () => {}) => [() => void, (now = true) => void];
This function takes a mouse button (0..15), an optional MouseEvent function to act as the mousemove event handler, and an optional function to be run on mouseup.
The function returns an array of two functions, the first of which activates the event, the second of which deactivates the event and will run any mouseup event handler unless false is passed into the function.
NB: If the window loses focus, the module will generate a mouseup event. This can be detected be checking the Event.isTrusted field.
(onmousemove: (e: MouseEvent) => void, onend?: () => void) => [() => void, (now = true) => void];
This function takes a MouseEvent function and an optional function which will be run when the event deactivates.
The function returns an array of two functions, the first of which activates the event, the second of which deactivates the event and will run any mouseup event handler unless false is passed into the function.
NB: If the window loses focus, the module will run the onend function.
The fraction module exports a default class to act as a fractional, infinite precision number type.
Field | Type | Description |
---|---|---|
add | Method | Adds fractions together. |
cmp | Method | Compares two Fractions. |
constructor | Constructor | Creates new Fractions. |
div | Method | Divide one Fraction by another. |
isNaN | Method | Determines if a Fraction is NotANumber. |
max | Static Method | Get the larger of two Fractions. |
min | Static Method | Get the smaller of two Fractions. |
mul | Method | Multiply Fractions together. |
NaN | Static Fraction | A Fraction representing NaN. |
one | Static Fraction | A Fraction representing 1. |
sign | Method | Returns the sign of the Fraction. |
simplify | Fraction | Returns a simplified version of the Fraction. |
sub | Method | Subtract one Fraction from another. |
Symbol.toPrimitive | Method | Converts a Fraction to a Number or String, depending on usage. |
toFloat | Method | Converts a Fraction to a Number. |
toString | Method | Converts a Fraction to a string. |
zero | Static Fraction | A Fraction representing 0. |
import Fraction from './fraction.js';
const ten = new Fraction(10n),
two = new Fraction(2n);
console.log(+ten.mul(two).add(Fraction.one));
This example shows some basic Fraction manipulations, resulting in 21 being printed to the console.
class Fraction {
add(num: Fraction) => Fraction;
}
The add method creates a new Fraction with the values set as the result of the addition of the two Fraction values.
class Fraction {
cmp(num: Fraction) => number;
}
The cmp method compares the base Fractions (A) to the passed Fraction (B), resulting in the following:
Comparison | Return Value |
---|---|
A < B | -1 |
A == B | 0 |
A > B | 1 |
isNaN(A) | NaN |
isNaN(B) | NaN |
class Fraction {
constructor(numerator: bigint, denominator: bigint = 1n);
}
The constructor of Fraction takes a BigInt numerator and an optional BigInt denominator and returns a Fraction accordingly. A zero (0n) denominator would create a Fraction equivalent of NaN.
class Fraction {
div(num: Fraction) => Fraction;
}
The div method creates a new Fraction with the values set as the result of the base Fraction divided by the passed Fraction.
For example:
(new Fraction(2n)).div(new Fraction(3n) =~ new Fraction(2n, 3n);
class Fraction {
isNaN() => boolean;
}
The isNaN method returns true if the Fraction is equivalent to NaN, which is when the denominator is equal to zero.
class Fraction {
static max(a: Fraction, ...b: Fraction[]) => Fraction;
}
This static method returns the larger of the passed Fraction
s, or Fraction.NaN if any param is Fraction.NaN.
class Fraction {
static min(a: Fraction, ...b: Fraction[]) => Fraction;
}
This static method returns the smaller of the passed Fraction
s, or Fraction.NaN if any param is Fraction.NaN.
class Fraction {
mul(num: Fraction) => Fraction;
}
The mul method creates a new Fraction with the values set as the result of the base Fraction multiplied by the passed Fraction.
class Fraction {
sign() => number;
}
The sign method returns a number indicating the sign of the value:
Fraction Value | Return Value |
---|---|
< 0 | -1 |
= 0 | 0 |
> 0 | 1 |
NaN | NaN |
class Fraction {
sub(num: Fraction) => Fraction;
}
The sub method creates a new Fraction with the values set as the result of the passed Fraction subtracted from the base Fraction.
For example:
(new Fraction(3n)).sub(new Fraction(2n) =~ new Fraction(1n);
class Fraction {
[Symbol.toPrimitive](hint: string) => number | number;
}
When the hint is set to "number", this method returns a normal javascript number representation of the Fraction value, to 5 decimal places. Otherwise, it returns a string representation of the fraction.
See toPrimitive documentation for how to use this symbol.
The html module exports function for the creation of HTMLElements.
This module directly imports the dom module.
Export | Type | Description |
---|---|---|
ns | String | This constant contains the XMLNamespace of HTMLElements. |
a abbr address area article aside audio b base bdi bdo blockquote body br button canvas caption cite code col colgroup data datalist dd del details dfn dialog div dl dt em embed fieldset figcaption figure footer form h1 h2 h3 h4 h5 h6 head header hgroup hr html i iframe img input ins kbd label legend li link main map mark menu meta meter nav noscript object ol optgroup option output p picture pre progress q rp rt ruby s samp script search section select slot small source span strong style sub summary sup table tbody td template textarea tfoot th thead time title tr track u ul video wbr | DOMBind | Each of these exports is a function which can take either a Props param and a Children param, or just a Children param, both as defined in the dom module, returning an HTMLElement of the exported name, with the attributes and children set. |
vare | DOMBind | This function is as above, for the var HTMLElement. |
import {table, tbody, th, thead,tr, td} from './html.js';
console.log(table({"class": "myTable"}, [
thead(tr([
th({"style": "background-color: #ff0"}, "Title 1"),
th("Title 2"),
])),
tbody([
tr([
td({"id": "cell_1"}, "Cell 1"),
td("Cell 2"),
]),
tr([
td("Cell 3"),
td("Cell 4"),
])
])
]).outerHTML);
This example builds up an HTML table and the following is printed to the console:
<table class="myTable"><thead><tr><th style="background-color: #ff0">Title 1</th><th>Title 2</th></tr></thead><tbody><tr><td id="cell_1">Cell 1</td><td>Cell 2</td></tr><tr><td>Cell 3</td><td>Cell 4</td></tr></tbody></table>
The inter module provides classes to aid with communication between otherwise unrelated modules.
Export | Type | Description |
---|---|---|
Pickup | Class | A type that lets a setter 'drop of' a value for a getter to 'pick up', after which the value is removed. |
Pipe | Class | A simple communication class for sending data to multiple clients. |
Requester | Class | A simple communication class for multiple clients to request data from a server. |
Subscribed | Type | The Subscribed type returns the resolution type of the passed Subscription. Subscribed<Subscription> returns T. |
Subscription | Class | This class provides a multi-firing version of a Promise. |
WaitGroup | Class | This Class updates clients on the status of multiple threads of operation. |
WaitInfo | Type | This type is the info delivered to clients of WaitGroup. |
class Pickup<T> {
get(): T | undefined;
set(v: T): T;
}
The Pickup Class is used to pass a single value to a single recipient.
Method | Description |
---|---|
get | Used to retrieve the value if one has been set. It will return undefined if no value is currently set. Clears any data stored. |
set | Used to set the value on the class. |
The Pipe Class is used to pass values to multiple registered functions, and contains the following methods:
Method | Description |
---|---|
any | This static method can be used to combine the output of multiple pipes. |
bind | This method can create simple bound functions for the receive, remove, and send methods. |
length | The field contains the number of functions currently registered on the Pipe. |
receive | The method is used to register a function to receive data from the Pipe. |
remove | The method is used to unregister a function on the Pipe. |
send | This method sends data to all registered functions on the Pipe. |
import {Pipe} from './inter.js';
const pipe = new Pipe<number>();
pipe.receive(num => console.log(num));
pipe.receive(num => console.log(num+10));
pipe.send(0);
pipe.send(1);
pipe.send(2);
In this example, a Pipe is used to transmit values to two different receivers, resulting in the following being printed to the console:
0
10
1
11
2
12
class Pipe {
static any<const T extends readonly (Pipe<unknown> | [Pipe<unknown>, unknown>] | unknown)[] | []>(cb: (v: any[]) => void, ...pipes: T): () => void;
}
This method calls the passed function whenever a value from any of the pipes is received.
Initial values for the Pipes can be set by using the Pipe in a tuple with the default value.
The returned function can be used to cancel the updates.
class Pipe<T> {
bind(bindmask: 1) => [(data: T) => void, undefined, undefined];
bind(bindmask: 2) => [undefined, (fn: (data: T) => void) => void, undefined];
bind(bindmask: 3) => [(data: T) => void, (fn: (data: T) => void) => void, undefined];
bind(bindmask: 4) => [undefined, undefined, (fn: (data: T) => void) => void];
bind(bindmask: 5) => [(data: T) => void, undefined, (fn: (data: T) => void) => void];
bind(bindmask: 6) => [undefined, (fn: (data: T) => void) => void, (fn: (data: T) => void) => void];
bind(bindmask?: 7) => [(data: T) => void, (fn: (data: T) => void) => void, (fn: (data: T) => void) => void];
}
This method returns an Array of functions bound to the send, receive, and remove methods of the Pipe Class. The bindmask determines which methods are bound.
Mask Bit Value | Method |
---|---|
1 | send |
2 | receive |
4 | remove |
The return will return the following: [send bound function, receive bound function, remove bound function]
class Pipe<T> {
receive(fn: (data: T) => void) => void;
}
The passed function will be registered on the Pipe and will receive any future values sent along it. Exceptions thrown be any receivers are ignored.
NB: The same function can be set multiple times, and will be for each time it is set.
class Pipe<T> {
remove(fn: (data: T) => void) => boolean;
}
The passed function will be unregistered from the Pipe and will no longer receive values sent along it. Returns true if a function was unregistered, false otherwise.
NB: If the function is registered multiple times, only a single entry will be unregistered.
class Pipe<T> {
send(data: T) => void;
}
This function sends the data passed to any functions registered on the Pipe.
The Requester Class is used to allow a server to set a function or value for multiple clients to query and contains the following methods:
Method | Description |
---|---|
request | This method is used to request data from the Requester object. |
responder | This method is used to set either a responder function or value on the Requester object. |
import {Requester} from './inter.js';
const request = new Requester<number>();
let num = 0;
request.responder(n => n + num++);
console.log(request.request(0));
console.log(request.request(10));
console.log(request.request(0));
console.log(request.request(10));
console.log(request.request(0));
console.log(request.request(10));
This example shows how a function can respond to 'queries', with the following being printed to the console:
0
11
2
13
4
15
class Requester<T, U extends any[] = any[]> {
request(...data: U) => T;
}
The request method sends data to a set responder and receives a response. Will throw an error if no responder is set.
class Requester<T, U extends any[] = any[]> {
responder(f: ((...data: U) => T) | T) => void;
}
The responder method sets either the function that will respond to any request, or the value that will be the response to any request.
The Subscription Class is similar to the Promise class, but any success and error functions can be called multiple times.
Method | Type | Description |
---|---|---|
any | Static Method | This method creates a new Subscription that fires when any of the passed Subscriptions fire. |
bind | Static Method | This method binds the when, error, and cancel functions. |
cancel | Method | This method sends a cancel signal up the Subscription chain. |
catch | Method | This method acts like the Promise.catch method. |
constructor | Constructor | This constructs a new Subscription. |
finally | Method | This method acts like the Promise.finally method. |
merge | Static Method | This combines several Subscriptions into one. |
splitCancel | Method | This method set all child Subscription objects to remove themselves from this Subscription using the cancel method. |
when | Method | This method acts like the Promise.then method. |
type SubscriptionWithDefault<T> = [Subscription<T>, T];
class Subscription {
static any<T extends readonly (Subscription<T> | SubscriptionWithDefault<T>)[]>(...subs: T): Subscription<Subscribed<T>[]>;
}
This method combines the passed in Subscriptions into a single Subscription that fires whenever any of the passed Subscriptions do. The data passed to the success function is an array of the latest value from each of the Subscriptions.
Initial data for a Subscription can be set by putting the Subscription in a tuple with the default value as the second element (SubscriptionWithDefault).
If no default is specified, the default is undefined.
NB: The combined Subscription will fire in the next event loop, in order to collect all simultaneous changes.
class Subscription<T> {
static bind<T>(bindmask: 1) => [Subscription<T>, (data: T) => void, undefined, undefined];
static bind<T>(bindmask: 2) => [Subscription<T>, undefined, (data: any) => void, undefined];
static bind<T>(bindmask: 3) => [Subscription<T>, (data: T) => void, (data: any) => void, undefined];
static bind<T>(bindmask: 4) => [Subscription<T>, undefined, undefined, (data: () => void) => void];
static bind<T>(bindmask: 5) => [Subscription<T>, (data: T) => void, undefined, (data: () => void) => void];
static bind<T>(bindmask: 6) => [Subscription<T>, undefined, (data: any) => void, (data: () => void) => void];
static bind<T>(bindmask?: 7) => [Subscription<T>, (data: T) => void, (data: any) => void, (data: () => void) => void];
}
This method returns an Array of functions bound to the when, error, and cancel methods of the Subscription Class. The bindmask determines which methods are bound.
Mask Bit Value | Method |
---|---|
1 | when |
2 | error |
4 | cancel |
The return will return the following: [when bound function, error bound function, cancel bound function]
class Subscription<T> {
cancel() => void;
}
This method sends a signal up the Subscription chain to the cancel function set during the construction of the original Subscription.
class Subscription<T> {
catch<TResult = never>(errorFn: (data: any) => TResult) => Subscription<T | TResult>;
}
The catch method act similarly to the catch method of the Promise class, except that it can be activated multiple times.
class Subscription<T> {
constructor(fn: (successFn: (data: T) => void, errorFn: (data: any) => void, cancelFn: (data: () => void) => void) => void)
}
The constructor of the Subscription class takes a function that receives success, error, and cancel functions.
The success function can be called multiple times and will send any params in the call on to any 'when' functions.
The error function can be called multiple times and will send any params in the call on to any 'catch' functions.
The cancel function can be called at any time with a function to deal with any cancel signals generated by this Subscription object, or any child Subscription objects.
class Subscription<T> {
finally(afterFn: () => void) => Subscription<T>
}
The finally method act similarly to the finally method of the Promise class, except that it can be activated multiple times.
class Subscription<T> {
static merge<T>(...subs: Subscription<T>[]) => Subscription<T>;
}
The merge static method combines any number of Subscription objects into a single subscription, so that all parent success and catch calls are combined, and any cancel signal will be sent to all parents.
class Subscription<T> {
splitCancel(cancelOnEmpty = false) => () => Subscription<T>;
}
This method creates a break in the cancel signal chain, so that any cancel signal simply removes that Subscription from its parent.
The cancelOnEmpty flag, when true, will send an actual cancel signal all the way up the chain when called on the last split child.
class Subscription<T> {
when<TResult1 = T, TResult2 = never>(successFn?: ((data: T) => TResult1) | null, errorFn?: ((data: any) => TResult2) | null) => Subscription<TResult1 | TResult2>;
}
The when method act similarly to the then method of the Promise class, except that it can be activated multiple times.
The WaitGroup Class is used to wait for multiple asynchronous tasks to complete.
Method | Type | Description |
---|---|---|
add | Method | Adds to the number of tasks. |
done | Method | Adds to the number of complete tasks. |
error | Method | Adds to the number of failed tasks. |
onComplete | Method | Callback method to be run on completion of all tasks. |
onupdate | Method | Callback method to be run on any change. |
class WaitGroup {
add() => void;
}
This method adds to the number of registered tasks.
class WaitGroup {
done() => void;
}
This method adds to the number of complete tasks.
class WaitGroup {
error() => void;
}
This method adds to the number of failed tasks.
class WaitGroup {
onComplete(fn: (wi: WaitInfo) => void) => () => void;
}
This method registers a function to run when all registered tasks are complete, successfully or otherwise.
This method returns a function to unregister the supplied function.
class WaitGroup {
onUpdate(fn: (wi: WaitInfo) => void) => () => void;
}
This method registers a function to run whenever a task is added, completed, or failed.
This method returns a function to unregister the supplied function.
The WaitInfo type contains the following data:
Field | Type | Description |
---|---|---|
done | number | The number of complete tasks. |
errors | number | The number of failed tasks. |
waits | number | The total number of registered tasks. |
The load module contains a single default export, a Promise which is resolved when the page finished loading.
The markdown module contains a full CommonMark parser with several optional (enabled by default) extensions.
This module directly imports the casefold, misc, and parser modules.
This module provides a single, default export with the following signature:
(markdown: string, tgs?: Partial<UserTags>): DocumentFragment;
This function is a markdown parser, that takes a markdown string, and an optional object that provides configuration; returns a DocumentFragment containing the result of the parsed code.
The tgs
object allow for the overriding of default processing behaviour; most of the fields simply allow for alternate Node creation behaviour and custom processing.
type Tags = {
allowedHTML: null | [keyof HTMLElementTagNameMap, ...string[]][];
blockquote: (c: DocumentFragment) => Element | DocumentFragment;
code: (info: string, text: string) => Element | DocumentFragment;
heading1: (c: DocumentFragment) => Element | DocumentFragment;
heading2: (c: DocumentFragment) => Element | DocumentFragment;
heading3: (c: DocumentFragment) => Element | DocumentFragment;
heading4: (c: DocumentFragment) => Element | DocumentFragment;
heading5: (c: DocumentFragment) => Element | DocumentFragment;
heading6: (c: DocumentFragment) => Element | DocumentFragment;
paragraphs: (c: DocumentFragment) => Element | DocumentFragment;
unorderedList: (c: DocumentFragment) => Element | DocumentFragment;
orderedList: (start: string, c: DocumentFragment) => Element | DocumentFragment;
listItem: (c: DocumentFragment) => Element | DocumentFragment;
checkbox: null | ((checked: boolean) => Element | DocumentFragment);
thematicBreaks: () => Element | DocumentFragment;
link: (href: string, title: string, c: DocumentFragment) => Element | DocumentFragment;
image: (src: string, title: string, alt: string) => Element | DocumentFragment;
inlineCode: (c: DocumentFragment) => Element | DocumentFragment;
italic: (c: DocumentFragment) => Element | DocumentFragment;
bold: (c: DocumentFragment) => Element | DocumentFragment;
underline: null | ((c: DocumentFragment) => Element | DocumentFragment);
subscript: null | ((c: DocumentFragment) => Element | DocumentFragment);
superscript: null | ((c: DocumentFragment) => Element | DocumentFragment);
strikethrough: null | ((c: DocumentFragment) => Element | DocumentFragment);
insert: null | ((c: DocumentFragment) => Element | DocumentFragment);
highlight: null | ((c: DocumentFragment) => Element | DocumentFragment);
table: null | ((c: DocumentFragment) => Element | DocumentFragment);
thead: (c: DocumentFragment) => Element | DocumentFragment;
tbody: (c: DocumentFragment) => Element | DocumentFragment;
tr: (c: DocumentFragment) => Element | DocumentFragment;
th: (alignment: string, c: DocumentFragment) => Element | DocumentFragment;
td: (alignment: string, c: DocumentFragment) => Element | DocumentFragment;
break: () => Element | DocumentFragment;
}
The allowedHTML
field allows the whitelisting of raw HTML elements. Takes an array of tuples, of which the first element is the HTML element name, and the remaining elements are allowed attributes names.
The checkbox, underline, subscript, superscript, strikethrough, insert, highlight, and table fields can be set to null to disable that Markdown extension.
NB: When the underline extension is disabled, the single underscore emphasis is parsed as italic (<em>
).
The math module exports function for the creation of MathMLElements.
This module directly imports the dom module.
Export | Type | Description |
---|---|---|
ns | String | This constant contains the XMLNamespace of MathMLElements. |
annotation maction math menclose merror mfenced mfrac mi mmultiscripts mn mo mover mpadded mphantom mprescripts mroot mrow ms mspace msqrt mstyle msub msubsup msup mtable mtd mtext mtr munder munderover semantics | DOMBind | Each of these exports is a function which can take either a Props param and a Children param, or just a Children param, both as defined in the dom module, returning a MathMLElement, with the attributes and children set. |
annotationXML | DOMBind | This function is as above, for the annotation-xml MathMLElement. |
The menu module adds custom elements to create context-menus.
This module directly imports the css, dom and html modules.
Export | Type | Description |
---|---|---|
item | Function | A DOMBind that creates an ItemElement. |
ItemElement | Class | Defines a menu item. |
menu | Function | A DOMBind that creates a MenuElement. |
MenuElement | Class | Defines a menu. |
MenuItems | Type | Type of children applicable to a MenuElement. Allows ItemElement, SubMenuElement, and recursive arrays of both. |
submenu | Function | A DOMBind that creates a SubMenuElement. |
SubMenuElement | Defines a submenu. | |
SubMenuItems | Type | Type of children applicable to a SubMenuElement. Allows ItemElement, MenuElement, and recursive arrays of both. |
The ItemElement class represents items within a menu. It can be used either directly in a MenuElement, or in a SubMenuElement as its representative element. It can contain any structure, which will be what appears in the menu.
The action of the element is defined with a custom 'select' event, which is called when the element is selected. Unless the 'select' event cancels the event (preventDefault) the menu will close after the event is executed.
When used directly in a MenuElement, the 'key' attribute sets a possible quick access key, values of which should be one of the Keyboard event key values.
When used directly in a MenuElement, the 'disable' attribute makes the item unselectable and unfocusable.
The MenuElement class represents a context-menu that is displayed as a hovering list on the page. It can contain any number of ItemElements and SubMenuElements, which will be the elements of the list.
When the MenuElement is attached to the DOM (non-SubMenuElement) is will use any 'x' and 'y' attributes on the element to determine the location of the menu on screen. It will attempt to place, within the offsetParent, the top-left corner of the menu at the 'x' and 'y' coordinates specified, but will try the right corners if there is not enough space to the left and the bottom corners if there is not enough space below. If there is not enough space for the menu, the fallback coordinates for both attributes is 0, 0
.
The SubMenuElement class defines an element which is a MenuItem. It It should contain a single ItemElement and a single MenuElement.
The ItemElement will be displayed in the parent MenuElement and the child MenuElement will be the menu that is displayed when this element is selected. The placement works similarly to that of MenuElement, in that it will attempt to put the top-left corner of the new menu at the top-right of the SubMenuElement selected, moving up as necessary, and will move to the left of the SubMenuElement is there is not enough space to the right.
The 'key' attribute sets a possible quick access key, values of which should be one of the Keyboard event key values.
The 'disable' attribute makes the item unselectable and unfocusable.
The misc module contains various simple, dependency-free exports.
Export | Type | Description |
---|---|---|
addAndReturn | Function | This function adds a value to a Set and returns the value. |
autoFocus | Function | This function queues a focus method call to the passed element. |
Callable | Class | This class provides a convenient way to extend a Function with class attributes and methods. |
checkInt | Function | This function determines whether the value passed is an integer, within a given range, returning either the valid integer or a default value. |
debounce | Function | This function prevents a updates from happening too often by limiting how often they can run. |
isInt | Function | This function determines whether the value passed is an integer, within a given range. |
mod | Function | This function performs the modulo operation on the two given numbers. |
pushAndReturn | Function | This function adds a value to an Array and returns the value. |
queue | Function | The function allows the simple queueing of functions that require a definite order. |
setAndReturn | Function | This function sets a value on a map and returns the value. |
stringSort | Function | A simple function to be passed into a 'sort' function that will order elements lexically. |
text2DOM | Function | This function converts valid HTML/SVG/MathML text into DOM Nodes. |
<V>(s: {add: (m: V) => void}, v: V) => V;
This function takes a Set-like object and calls the add
method with the given value, before returning the value v
.
This functions is useful for one-liners where you need to store a value in a Set and still work on that value.
<T extends FocusElement>(node: T, inputSelect = true) => T;
This queues a focus method call to the passed element, and will call select on any HTMLInputElement or HTMLTextAreaElement, unless false is passed as the second param.
class Callable<Fn extends Function> extends Function {
constructor(fn: Fn);
}
This class provides a convenient way to extend a Function (Fn) with class attributes and methods.
The child class will need appropriate typing to make it correctly appear as the type of the passed function as well as the child class.
(n: unknown, min = -Infinity, max = Infinity, def = Math.max(min, 0)) => number;
This function determines whether n
is a valid integer, as determined by the isInt function, and returns n
if it is, or def
(cast to an integer) otherwise.
(timer = 0, first = false) => (fn: Function) => void;
This function prevents a updates from happening too often by limiting how often they can run.
The first param is a timeout in milliseconds before another update can run.
The second param is a flag to determine whether or not the first or last update function should be run.
The function returns a function which takes the update function that will be debounced.
(v: unknown, min = -Infinity, max = Infinity): v is number;
This function determines whether v
is a valid integer in the range provided (min <= v <= max).
NB: Infinity is not a valid integer.
(n: number, m: number) => number;
Javascript does not have a built-in modulo operator, and as such this function is useful to perform it. It does the following:
((n % m) + m) % m;
<V>(a: {push: (m: V) => void}, v: V) => V;
This function takes an Array-like object and calls the push
method with the given value, before returning the value v
.
This functions is useful for one-liners where you need to store a value in an Array and still work on that value.
(fn: () => Promise<any>) => Promise<void>;
This function takes a function that will run after all functions that were previously passed to the queue function.
setAndReturn = <K, V>(m: {set: (k: K, v: V) => void}, k: K, v: V) => V;
This function takes a map-like object and calls the set
method with the given key and value, before returning the value v
.
This functions is useful for one-liners where you need to store a value in a map and still work on that value.
(text: string) => DocumentFragment
This function converts valid HTML/SVG/MathML text into DOM Nodes, stored within a DocumentFragment.
The multiselect module adds a custom element that implements a Select-like input element allowing multiple options to be selected and removed.
This module directly imports the css, dom, and html modules.
This module exports the following:
Export | Type | Description |
---|---|---|
MultiOption | Class | Used to specify selectable options in a MultiSelect. |
MultiSelect | Class | Used to create a set of options that can be selected. |
multioption | DOMBind | A DOMBind for MultiOption. |
multiselect | DOMBind | A DOMBind for MultiSelect. |
The MultiOption class is a Custom Element that is used to specify options on the MultiSelect.
This element registers with the name multi-option
.
This element is used much like the Option element, except it can contain arbitrary HTML that is shows once the option is selected; specifically, it handles the following attributes:
Attribute | Type | Description |
---|---|---|
value | String | When selected, this value will be appended to the MultiSelect.value attribute and be removed when deselected. |
label | String | The text to show in the options list for this option. |
The MultiSelect class is a CustomElement that can contain many MultiOption elements. This element registers with the name multi-select
.
This element handles the following attributes:
Attribute | Type | Description |
---|---|---|
filter-type | String | Can be set to one of 'contain', 'prefix', or 'both', which changes the filter type. Both will promote the prefix matches to the top. |
toggle | Boolean | When set, selected options will be hidden in the options list until they are deselected. |
placeholder | String | When set, sets the placeholder text on the input element. |
value | Array | An array containing the values of the selected options. Can be set to programmatically select options. |
In addition, the following CSS vars control various aspects of styling for the element.
Variable | Default | Description |
---|---|---|
--arrowColor | #000 | Sets the colour of the 'dropdown' arrow. |
--backgroundColor | #fff | Sets the background colours of the main element. |
--optionDisabledBackground | #fff | Sets the background colour of disabled options. |
--optionDisabledColor | #888 | Sets the font colour of disabled options. |
--optionHoverBackground | #000 | Sets the background colour of non-disabled elements when hovered over. |
--optionHoverColor | #fff | Sets the font colour of non-disabled elements when hovered over. |
--optionSelectedBackground | #888 | Sets the background colour of selected elements. |
--optionSelectedColor | #fff | Sets the font colour of selected elements. |
--optionsBackground | #fff | Sets the background colour of the options list. |
--optionsBorder | 1px solid #000 | Sets the border of the options list. |
--optionsColor | #000 | Sets the font colour of the options list. |
--optionsMaxHeight | 100% | Sets the maximum height of the options list. |
--removeBackgroundColor | #fff | Sets the background colour of the remove icon. |
--removeBorderColor | #f00 | Sets the border colour of the remove icon. |
--removeHoverBackgroundColor | #fff | Sets the background colour of the remove icon when hovered over. |
--removeHoverBorderColor | #000 | Sets the border colour of the remove icon when hovered over. |
--removeHoverXColor | #000 | Sets the colour of the X in the remove icon when hovered over. |
--removeXColor | #f00 | Sets the colour of the X in the remove icon. |
--selectedBackground | None | Sets the colour of the selected options wrapper element. |
--selectedBorder | None | Sets the border of the selected options wrapper element. |
--selectedBorderRadius | 0 | Sets the border radius of the selected options wrapper element. |
--selectedHoverBackground | None | Sets the colour of the selected options wrapper element when it is hovered over. |
--selectedHoverBorder | None | Sets the border of the selected options wrapper element when it is hovered over. |
--selectedPadding | 0 | Sets the padding of the selected options wrapper element. |
The nodes module contains Classes for aiding in the accessing of DOM Nodes.
This module directly imports the dom, and misc modules.
Export | Type | Description |
---|---|---|
node | Symbol | This Symbol is used to specify the Node of an Item type. This symbol is the child symbol imported from the dom library. |
NodeArray | Class | This Class provides Array-like access to DOM Nodes. |
NodeMap | Class | This Class provides Map-like access to DOM Nodes. |
noSort | Function | A sorting function that does no sorting. |
stringSort | Function | A function to sort strings. |
This class provides Array-like access to DOM Nodes, allowing them to be sorted and accessed via position-based indexes.
This type implements all fields and methods of the Array interface, except for the following changes:
Field | Type | Differences |
---|---|---|
[node] | Node | New field to access base Node. |
concat | Method | Returns a normal Array, not a NodeArray. |
constructor | Constructor | Takes very different params to initialise a NodeArray. |
copyWithin | Method | Not applicable and throws an error. |
fill | Method | Not applicable and throws an error. |
filterRemove | Method | New method that works like filter but also removes the filtered items. |
from | Static Method | Takes very different params to initialise a NodeArray. |
reverse | Method | Reverses the sorting of the Items. |
slice | Method | Returns a normal Array, not a NodeArray. |
sort | Method | Sorts the Items. |
class NodeArray<T extends Item, H extends Node = Node> implements Array<T> {
constructor(parent: H, sort: (a: T, b: T) => number = noSort, elements: Iterable<T> = []);
constructor(parent: H, elements: Iterable<T> = []);
}
The NodeArray constructor takes a parent element, onto which all Item elements will be attached, an optional starting sort function, and an optional set of starting elements of type T
.
The sorting function is used to order Items as they are inserted.
The NodeArray type is wrapped with a Proxy to implement Array-like indexing.
class NodeArray<T extends Item, H extends Node = Node> implements Array<T> {
static from<_, H extends Node = Node>(parent: H) => NodeArray<Item, H>;
static from<T extends Item, H extends Node = Node>(parent: H, itemFn: (node: Node) => T|undefined) => NodeArray<T, H>;
static from<T extends Item = Item, H extends Node = Node>(parent: H, itemFn = (n: Node) => n)) => NodeArray<T, H>;
}
This function will create a NodeArray from the given parent Node, iterating over every child and running the itemFn to generate an Item to be append to the NodeArray.
class NodeArray<T extends Item, H extends Node = Node> implements Array<T> {
reverse() => void;
}
The reverse method reverse the position of each Item and reverses the sorting algorithm.
class NodeArray<T extends Item, H extends Node = Node> implements Array<T> {
sort(compareFunction?: (a: T, b: T) => number) => NodeArray<T>;
}
The sort method works much like the Array.sort method, but new items will be inserted according to the sorting function provided.
Running this function with no param will result in the NodeArray being re-sorted according to the existing sorting function.
This class provides Map-like access to DOM Nodes, allowing them to be sorted and accessed via keys.
This type implements all fields and methods of the Map interface, except for the following changes:
Field | Type | Differences |
---|---|---|
[node] | Node | New field to access base Node. |
constructor | Constructor | Takes very different params to initialise a NodeMap. |
insertAfter | Method | Inserts an Item after another. |
insertBefore | Method | Inserts an Item before another. |
keyAt | Method | Returns the key of the Item at the specified position. |
position | Method | Returns the position of the Item specified by the key. |
reSet | Method | Changes the key for an item. |
reverse | Method | Reverses the sorting of the Items. |
sort | Method | Sorts the Items. |
class NodeMap<K, T extends Item, H extends Node = Node> implements Map<K, T> {
constructor(parent: H, sort: (a: T, b: T) => number = noSort, entries: Iterable<[K, T]> = []);
constructor(parent: H, elements: Iterable<[T, K]> = []);
}
The NodeMap constructor takes a parent element, onto which all Item elements will be attached, an optional starting sort function, and an optional set of starting elements of type T
.
The sorting function is used to order Items as they are inserted.
class NodeMap<K, T extends Item, H extends Node = Node> implements Map<K, T> {
insertAfter(k: K, item: T, after: K) => boolean;
}
The insertAfter method will insert a new Item after the Item denoted by the after
key.
The method will return true unless the after
key cannot be found, in which case it will return false.
class NodeMap<K, T extends Item, H extends Node = Node> implements Map<K, T> {
insertBefore(k: K, item: T, before: K) => boolean;
}
The insertBefore method will insert a new Item before the Item denoted by the before
key.
The method will return true unless the before
key cannot be found, in which case it will return false.
class NodeMap<K, T extends Item, H extends Node = Node> implements Map<K, T> {
keyAt(pos: number) => T | undefined;
}
The keyAt method returns the position of the key in within the sorted Item. It returns undefined if there is nothing at the specified position.
class NodeMap<K, T extends Item, H extends Node = Node> implements Map<K, T> {
position(key: K) => number;
}
The position method returns the current sorted position of the Item described by the key.
class NodeMap<K, T extends Item, H extends Node = Node> implements Map<K, T> {
reSet(k: K, j: K) => void;
}
The reset method changes the key assigned to an Item without performing any sorting.
class NodeMap<K, T extends Item, H extends Node = Node> implements Map<K, T> {
reverse() => void;
}
The reverse method reverse the position of each Item and reverses the sorting algorithm.
class NodeMap<K, T extends Item, H extends Node = Node> implements Map<K, T> {
sort(compareFunction?: (a: T, b: T) => number) => NodeMap<T>;
}
The sort method sorts the Items, and new items will be inserted according to the sorting function provided.
Running this function with no param will result in the NodeMap being re-sorted according to the existing sorting function.
interface {
[node]: Node;
}
This unexported type satisfies any type has used the node Symbol to delegate a Node element, or is a Text Node or Element.
The pagination module defines a simple pagination creator.
This module directly imports the dom, and html modules.
Export | Type | Description |
---|---|---|
(default) | Function | A DOMBind that creates a Pagination. |
Pagination | Class | This class represents the pagination custom element. |
setLanguage | Function | Used to set language entries used for Pagination. |
CSS part attributes have been set on the various elements of Pagination to make styling simple.
Part | Description |
---|---|
active | A 'page' element that can be clicked to change the page number. |
base | The base HTMLUListElement. |
current | The currently selected page. Will also be a 'page'. |
page | An HTMLLIElement that contains the link and/or text for a page. |
prev | The 'Prev' element. Will also be a 'page'. |
next | The 'Next' element. Will also be a 'page'. |
separator | An empty HTMLLIElement that sits between beginning/end pages and the current page. |
class Pagination extends HTMLElement {
getPageNumberFromEvent(e: Event): number;
static getPageNumberFromEvent(e: Event) : number;
}
Pagination accepts the following attributes:
Attribute | Description |
---|---|
end | This number will determine how many page elements are created at the ends of the list. (default: 3) |
href | This string will be prefixed to the page number in any created links. If attribute not set, will not create links. A function of the type (page: number) => string can be used to create more complex links; this should be set using amendNode/clearNode. |
page | This number will determine the current page number. 0 indexed. (default: 0) |
surround | This number will determine how many pages surround the current page in the list. (default: 3) |
total | This number will determine how many pages there are in total. (default: 1) |
In addition to the control attributes, the class provides both static and non-static method named getPageNumberFromEvent which, when passed the Event object from a mouse event on the Pagination element, will return the page number associated with the child element that triggered the event. NB: If a non-page element triggered the event, will return -1.
setLanguage = (l: Partial<{
NEXT: string | Binding,
PREV: string | Binding,
}) => void;
This function is used to set the language used for the Next
and Previous
page elements.
The parse module can be used to parse text into token or phrase streams.
Export | Type | Description |
---|---|---|
(default) | Function | The default function can parse a text stream into either a stream of tokens or a stream of phrases, depending on whether a phrase parsing function is provided. |
Phrase | Type | Phrase represents a parsed phrase, which is a collection of successive tokens. |
PhraseDone | Constant | Set to -1, this constant is a PhraseType used by the Phraser.done() method to indicate that their are no more Phrases. |
PhraseError | Constant | Set to -2, this constant is a PhraseType used by the Phraser.error() method to indicate that an error has occurred in the token stream, and that there are no more Phrases. |
PhraseFn | Type | PhraseFn is used by the parsing function to parse a Phrase from a token stream. |
Phraser | Class | A Phraser is a collection of methods that allow the easy parsing of a token stream. |
PhraseType | Type | PhraseType is used to ID a particular class of Phrases. Negative numbers represent built-in states, so only positive numbers should be used by implementing functions. |
PhraseWithNumbers | Type | PhraseWithNumbers represents a Phrase where the tokens are TokenWithNumbers. |
processToEnd | Function | This function converts the infinite Generator, returned from the default fn, into a finite Generator only yielding non-Done and non-Error tokens and phrases. |
Token | Type | A Token represents a parsed token. |
TokenDone | Constant | Set to -1, this constant is a TokenType used by the Tokeniser.done() method to indicate that their are no more Tokens. |
TokenError | Constant | Set to -2, this constant is a TokenType used by the Tokeniser.error() method to indicate that an error has occurred in the token stream, and that there are no more Tokens. |
TokenFn | Type | TokenFn is used by the parsing function to parse a Token from a text stream. |
Tokeniser | Class | Tokeniser is a collection of methods that allow the easy parsing of a text stream. |
TokenType | Type | TokenType is used to ID a particular class of Tokens. Negative numbers represent built-in states, so only positive numbers should be used by implementing functions. |
TokenWithNumbers | Type | TokenWithNumbers represents a token which has its position within the text stream as an absolute position (pos), a zero-indexed line number (line), and the position on that line (linePos). |
withNumbers | Function | withNumbers adds positional information to the tokens, either in the token stream or phrase stream. |
(text: string, parserFn: TokenFn): Generator<Token, never>;
(text: string, parserFn: TokenFn, phraserFn: PhraserFn): Generator<Phrase, never>;
The default function can parse a text stream into either a stream of tokens or a stream of phrases, depending on whether a phrase parsing function is provided.
type Phrase = {
/** The type of Phrase parsed. */
type: PhraseType;
/** The parsed tokens. */
data: Token[];
}
Phrase represents a parsed phrase, which is a collection of successive tokens.
type PhraserFn = (p: Phraser) => [Phrase, PhraserFn]
PhraseFn is used by the parsing function to parse a Phrase from a token stream. Takes a Phraser, and returns the parsed Phrase and the next PhraseFn with which to parse the next phrase.
A Phraser is a collection of methods that allow the easy parsing of a token stream.
Method | Description |
---|---|
accept | Adds the next token in the stream to the buffer if its TokenID is in the tokenTypes array provided. Returns true if a token was added. |
acceptRun | Successively adds tokens in the stream to the buffer as long they are their TokenID is in the tokenTypes array provided. Returns the TokenID of the last token added. |
backup | Restores the state to before the last call to next() (either directly, or via accept, acceptRun, except, or exceptRun). |
constructor | Takes either a string or an iterator returning characters, and an initial TokenFn to construct a new Phraser. |
done | Returns a Done phrase, optionally with a Done token with a done message, and a recursive PhraseFn which continually returns the same done Phrase. |
error | Returns an Error phrase, optionally with an Error token with an error message, and a recursive PhraseFn which continually returns the same error Phrase. |
except | Adds the next token in the stream to the buffer as long as its TokenID is not in the tokenTypes array provided. Returns true if a token was added. |
exceptRun | Successively adds tokens in the stream to the buffer as long as their TokenID is not in the tokenTypes array provided. Returns the TokenID of the last token added. |
get | Returns all of the tokens processed, clearing the buffer. |
length | Returns the number of tokens in the buffer. |
peek | Looks ahead at the next token in the stream without adding it to the buffer, and returns the TokenID. |
reset | Restores the state to after the last get() call (or init, if get() has not been called). |
return | Creates the [Phrase, PhraseFn] tuple, using the parsed tokens as the data. If no PhraseFn is supplied, Phraser.done() is used. |
export type Token = {
/** The type of Token parsed. */
type: TokenType;
/** The text parsed. */
data: string;
}
A Token represents a parsed token.
export type TokenFn = (p: Tokeniser) => [Token, TokenFn];
TokenFn is used by the parsing function to parse a Token from the text stream. Takes a Tokeniser, and returns the parsed Token and the next TokenFn with which to parse the next token.
A Tokeniser is a collection of methods that allow the easy parsing of a text stream.
Method | Description |
---|---|
accept | Adds the next character in the stream to the buffer if it is in the string provided. Returns true if a character was added. |
acceptRun | Successively adds characters in the stream to the buffer as long as are in the string provided. Returns the character that stopped the run. |
acceptString | Attempts to accept each character from the given string, in order, returning the number of characters accepted before a failure. Second param is a boolean that determines if the string is accepted in a case senstive manner, which defaults to true. |
acceptWord | Attempts to parse one of the words (string of characters) provided in the array. Second param is a boolean that determines if the string is accepted in a case senstive manner, which defaults to true. |
backup | Restores the state to before the last call to next() (either directly, or via accept, acceptWord, acceptRun, except, or exceptRun). |
constructor | Takes either a string or an iterator returning characters to construct a new Tokeniser. |
done | Returns a Done token, with optional done message, and a recursive TokenFn which continually returns the same done Token. |
error | Returns an Error token, with optional error message, and a recursive TokenFn which continually returns the same error Token. |
except | Adds the next character in the stream to the buffer as long as they are not in the string provided. Returns true if a character was added. |
exceptRun | Successively adds characters in the stream to the buffer as long as they are not in the string provided. Returns the character that stopped the run. |
get | Returns all of the characters processed, clearing the buffer. |
length | Returns the number of characters in the buffer that would be returned by a call to get(). |
peek | Looks ahead at the next character in the stream without adding it to the buffer. |
reset | Restores the state to after the last get() call (or init, if get() has not been called). |
return | Creates the [Token, TokenFn] tuple, using the parsed characters as the data. If no TokenFn is supplied, Tokeniser.done() is used. |
The router module allows for easy use of the History API, updating the page according to the rules given to the router.
This library implements a global click-handler to intercept the uses of both HTMLAnchorElement and HTMLAreaElement elements, looking for URLs that match what the routers can handle.
Export | Type | Description |
---|---|---|
goto | Function | Used to update the routers to a new location. This function is added to the Window object in order to allow easy calling from HTML event handlers. |
registerTransition | Function | Used to register a transition effect to be used by HTML router. |
router | Function | Used to create a new router. |
(href: string, attrs?: Record<string, ToString>) => boolean;
This function will update all routers to the provided href
location, overriding any resolved attributes from the URL with those specified in the attrs
object.
It will return true if any Router has a route that matches the location, and false otherwise.
This function may be called directly from HTML event handlers, as it is granted global scope in the page.
(name: string, fn: (current: ChildNode, next: ChildNode) => void) => boolean;
This function will register a transition function with the specified name, allowing for transition effects and animation. This function will return true on a successful registration, and false if it fails, which will most likely be because of a name collision.
For the passed function, it is expected that the next
node will replace the current
node in the document immediately.
The router
function creates a new router, which should be added to the DOM in the place that you wish the matched routes to be placed.
Method | Description |
---|---|
add | Used to add routes to the Router. |
remove | Used to remove the Router from the DOM and disable its routing. It can be added to the DOM later to reactivate it. |
setTransition | Used to set a transition function. |
In addition to being able to be used from javascript, the Router can be added directly with HTML using the x-router
tag. When used in this way, routes can be added by adding children to the Router with the route-match
attribute set to the matching route, as per the add method.
The x-router
can take a router-transition
attribute, the name of which can be set to a name/function combo that is registered with the registerTransition function to allow an animated transition between routes.
For example, the following creates two path routes and a catch-all route:
<x-router>
<div route-match="/a">Route A</div>
<div route-match="/b"><span>Route B</span></div>
<div route-match="">404</div>
</x-router>
In addition to the x-router
tag, there is also the x-route
tag which can be used in HTML to set route-title
, route-class
, and route-id
attributes which, when the route is selected, are set as the window title, html class, and html ID, respectively. An example is the following:
<x-router>
<x-route route-title="Route A" route-id="route_a" route-class="dark" route-match="/a">Route A</x-route>
<x-route route-title="Route B" route-class="light" route-match="/b"><span>Route B</span></x-route>
<x-route route-title="Unknown Route" route-match="">404</x-route>
</x-router>
When the first route is matched, the title of the document will be set to "Route A", the class of the root html
element will be set to "dark", and the ID of the root html
element will be set to "route_a". Likewise, when the second route is matched, the title of the document will be set to "Route B", and the class will be set to "light". Lastly, the catch-all third route will just set the document title to "Unknown Route".
When a route is unmatched, any class and ID set is removed.
NB: It is recommended to either set the style attribute on all x-router elements to "display: none", or to add the following to CSS on the page:
x-router {
display: none;
}
This will hide the flash of elements that will appear of the page before the x-router element is registered.
NB: You can retrieve the number of routes added with the Router.count field.
class Router {
add(match: string, nodeFn: (attrs: Record<string, ToString>) => Exclude<ChildNode, Router>): this;
}
This method adds routes to a Router, specifying both a path to be matched and the function that is used to generate the HTML for that route. Note that the nodeFn can be a DOMBind function.
This method returns the Router for easy chaining.
The match string can consist of three parts, the path, the query, and the fragment; like an ordinary URL, but without the origin (scheme, user info, host, and port).
Both the path and query sections of the match string can contain variable bindings, which are attribute names, prepended with a ':'. For the path section, the binding can be anywhere in the string and the attribute name will end with either a '/' or the end of the string. For the query section bindings, the value of a parameter must start with ':' and the rest of the value will be the attribute name. The 'attrs' object will contain these bindings with the key set to the name of the binding and the value set to the value passed, if any.
For the path, if it starts with '/' then the match path will parsed as absolute, and when not starting with a '/' the match path can start anywhere after a '/' in the actual path. If the match path ends with '/', then the match path will be parsed as a prefix, whereas with no following '/', the match path will accept nothing beyond the end of it.
For the query, any non-binding params must match the URL param values for the route to match. Bound params are considered optional.
For the fragment, if the match string has one then it must match the URL fragment exactly. If the match string does not have one, the fragment will not be checked.
Some examples:
URL | Match | Success | Params |
---|---|---|---|
/a | /a /b a |
true false true |
|
/a-112 | /a /a-112 /a-:id |
false true true |
id = 112 |
/search?mode=list&id=123&q=keyword | /no-search?mode=list /search?mode=list /search?id=:id&mode=list /search?q=:query&mode=list&id=:id |
false true true true |
id = 123 id = 123 & query=keyword |
/some-page#content | /some-page /some-page#otherContent /some-page#content |
true false true |
class Router {
setTransition(fn: (current: ChildNode, next: ChildNode) => void): this;
}
The method is used to set the routers transition method. By default the router simply swaps the nodes, but this method allows for other effects and animations.
It is expected that the next
node will be placed in the document immediately, and adjacent to the current
node.
This library defines some simple transitional effects for the router library.
This module directly imports the router module.
Export | Type | Description |
---|---|---|
createTransition | Function | This function is used to create Transition Functions. |
fade | Function | A simple fade transition. Can be used with the x-router tag by setting the router-transition attribute to fade . |
wipeLeft | Function | A transition that reveals the new element beneath the first while wiping left. Can be used with the x-router tag by setting the router-transition attribute to wipe-left . |
wipeRight | Function | A transition that reveals the new element beneath the first while wiping right. Can be used with the x-router tag by setting the router-transition attribute to wipe-right . |
zoom | Function | A transition that scales out the first element before zooming in on the new element. Can be used with the x-router tag by setting the router-transition attribute to zoom . |
(currentKeyframes: Keyframe[], nextKeyframes?: Keyframe[], duration = 500) => (current: ChildNode, next: ChildNode) => void;
This function creates simple transition function (as used with the registerTransition function and the Router setTransition method of the router module.
If nextKeyframes
is not specified, then it will be determined by reversing the currentKeyframes
array.
The rpc module implements a JSON RPC class.
This module directly imports the inter module.
Export | Type | Description |
---|---|---|
RPC | Class | A connection neutral JSON RPC class. |
RPCError | Class | This class is the error type for RPC, and contains a code number, message string, and a data field for any addition information of the error. |
interface {
close: () => void;
send: (data: string) => void;
when: (sFn: (data: {data: string}) => void, eFn: (error: string) => void) => void;
}
This unexported type is the interface used by RPC to send and receive data. This is implemented by WSConn.
Method | Description |
---|---|
await | Used to wait for a specific message. |
close | Closes the RPC connection. |
constructor | Creates an RPC object with a Conn. If a Conn is not provided the requests will be queued until one is provided via reconnect. |
reconnect | Reuses the RPC object with a new Conn. |
register | Allows the registration of endpoints for clients of the connection to call. |
request | Calls a remote procedure and waits for a response. |
subscribe | Returns data each time a message with a specific ID is received. |
class RPC {
await<T = any>(id: number, typeCheck?: (a: unknown) => a is T): Promise<T>;
}
The await method will wait for a message with a matching ID, which must be negative, and resolve the promise with the data that message contains.
The typeCheck function can be specified to check that the data returned matches the format expected.
It is recommended to use a checker function, and the TypeGuard module can aid with that.
class RPC {
register<T>(endpoint: string, fn?: (t: T) => unknown, typeguard?: (v: T) => v is T);
}
The register method allows the registration of endpoints for clients of the connection to call.
The function will be passed params and return values will be returned to the caller. If the function returns an RPCError type, or throws an exception, it will be returned as an error to the caller. Setting this to null or undefined will unregister the endpoint.
class RPC {
request<T = any>(method: string, typeCheck?: (a: unknown) => a is T): Promise<T>;
request<T = any>(method: string, params: any, typeCheck?: (a: unknown) => a is T): Promise<T>;
}
The request method calls the remote procedure named by the method
param, and sends any params
data, JSON encoded, to it.
The typeCheck function can be specified to check that the data returned matches the format expected.
It is recommended to use a checker function, and the TypeGuard module can aid with that.
The Promise will resolve with the returned data from the remote procedure call.
class RPC {
subscribe<T = any>(id: number, typeCheck?: (a: unknown) => a is T): Subscription<T>;
}
The subscribe method will wait for a message with a matching ID, which must be negative, and resolve the Subscription with the data that message contains for each message with that ID.
The typeCheck function can be specified to check that the data returned matches the format expected.
It is recommended to use a checker function, and the TypeGuard module can aid with that.
The settings module exports convenience classes around the window.localStorage API.
Export | Description |
---|---|
BoolSetting | Class for storing Boolean values, which simply applies typing to the unexported base Setting class. |
IntSetting | Class for storing Integer values. |
JSONSetting | Class for storing JSON values. |
NumberSetting | Class for storing Number values. |
StringSetting | Class for storing String values. |
class BoolSetting extends Setting<boolean> {
constructor(name: string);
}
The BoolSetting class constructor
just takes a name, and otherwise just extends the base Setting class with the boolean
type.
class IntSetting extends Setting<number> {
constructor(name: string, starting = 0, min = -Infinity, max = Infinity);
}
The IntSetting class extends the constructor
of Setting to, in addition to the string name and optional number starting value, take optional min and max numbers to be used for validation.
In addition, the set
method will validate any values passed to it, making sure they value is an integer and satisfies the follow inequality:
min <= value <= max
Otherwise this class just extends the base Setting class with the number
type.
class JSONSetting<T> extends Setting<T> {
constructor(name: string, starting: T, validator: (v: unknown) => v is T);
save(): void;
}
The JSONSetting class extends the constructor
of Setting to, in addition to the string name and default starting value, takes a required validator function to confirm the retrieved value is of type T
.
In addition, this class adds a save
method which will save any changes made to the stored value
object, without having to re-set it.
Otherwise this class just extends the base Setting class with the T
type.
class NumberSetting extends Setting<number> {
constructor(name: string, starting = 0, min = -Infinity, max = Infinity);
}
The NumberSetting class extends the constructor
of Setting to, in addition to the string name and optional number starting value, take optional min and max numbers to be used for validation.
In addition, the set
method will validate any values passed to it, making sure the value satisfies the follow inequality:
min <= value <= max
Otherwise this class just extends the base Setting class with the number
type.
The unexported Setting class is extended by the various typed child Setting classes.
All methods return this
to allow for method chaining.
Field | Type | Description |
---|---|---|
constructor | Constructor | Takes a setting string name and a starting value of a type defined by the child class. |
name | String | The name of the setting. |
remove | Method | Removes the setting from localStorage. |
set | Method | Sets a new value to a Setting. |
value | T | The value of the setting, type defined by the child class. |
wait | Method | Registers a function to receive updated values. |
class Setting<T> {
wait(fn: (value: T) => void) => Setting<T>;
}
The wait method takes a function to be called on every setting value change. It will be immediately called with the current value.
The StringSetting class simply extends the Setting class with a default of empty string ("").
The storagestate module is used to create Bindings that bind to Storage objects.
This module directly imports the bind and misc modules.
Export | Description |
---|---|
bindLocalStorage | This function creates a Binding that retrieves its value from localStorage, and stores its value in localStorage when set. |
bindSessionStorage | This function creates a Binding that retrieves its value from sessionStorage, and stores its value in sessionStorage when set. |
<T>(name: string, value: NoInfer<T>, typeguard: (v: unknown) => v is T = (_: unknown): _ is any => true): Binding<T>;
This function creates a Binding that retrieves its value from localStorage, and stores its value in localStorage when set.
The value automatically updates when another localStorage Binding Object with the same name is updated, or when the localStorage is set from another browsing context.
The value given is used when a value retrieved from localStorage doesn't succeed the TypeGuard check.
<T>(name: string, value: NoInfer<T>, typeguard: (v: unknown) => v is T = (_: unknown): _ is any => true): Binding<T>;
This function creates a Binding that retrieves its value from sessionStorage, and stores its value in sessionStorage when set.
The value automatically updates when another sessionStorage Binding Object with the same name is updated, or when the sessionStorage is set from another browsing context.
The value given is used when a value retrieved from sessionStorage doesn't succeed the TypeGuard check.
The svg module exports function for the create of SVGElements.
This module directly imports the dom module.
import {defs, radialGradient, path, stop, svg} from './svg.js';
console.log(svg({"viewBox": "0 0 100 100"}, [
defs(radialGradient({"id": "burning", "cy": 0.55, "fy": 1}, [
stop({"offset": "0%", "stop-color": "#fff"}),
stop({"offset": "20%", "stop-color": "#ff0"}),
stop({"offset": "100%", "stop-color": "#f00"})
])),
path({"d": "M43,99 c-20,0 -60,-30 -30,-70 q0,20 10,30 c0,-20 25,-40 20,-58 q20,30 20,58 q10,-10 5,-30 q10,15 15,35 q5,-10 0,-25 c40,50 -10,62 -40,60 z M25,20 c-15,30 5,30 0,0 z M60,20 c0,20 10,20 0,0 z", "stroke": "#000", "fill": "url(#burning)", "stroke-linejoin": "round"})
]).outerHTML);
This example creates an SVG image of a flame, printing the source of it to the console:
<svg viewBox="0 0 100 100"><defs><radialGradient id="burning" cy="0.55" fy="1"><stop offset="0%" stop-color="#fff"></stop><stop offset="20%" stop-color="#ff0"></stop><stop offset="100%" stop-color="#f00"></stop></radialGradient></defs><path d="M43,99 c-20,0 -60,-30 -30,-70 q0,20 10,30 c0,-20 25,-40 20,-58 q20,30 20,58 q10,-10 5,-30 q10,15 15,35 q5,-10 0,-25 c40,50 -10,62 -40,60 z M25,20 c-15,30 5,30 0,0 z M60,20 c0,20 10,20 0,0 z" stroke="#000" fill="url(#burning)" stroke-linejoin="round"></path></svg>
The typeguard module provides the building blocks for creating type-safe typeguards.
The intent is to be able to create your types from the typeguards, instead of creating typeguards for a type.
This module directly imports the misc module.
The module exports the following functions:
Export | Description |
---|---|
And | The And function returns a TypeGuard that checks a value matches against all of the given TypeGuards. |
Any | The Any function returns a TypeGuard that allows any value. |
Arr | The Arr function returns a TypeGuard that checks for an Array, running the given TypeGuard on each element. |
asTypeGuard | This function gives a custom typeguard additional functionality, such as being able to optionally throw errors, and be spreadable. |
BigInt | The BigInt function returns a TypeGuard that checks for bigints, and takes optional min and max (inclusive) values to range check. |
Bool | The Bool function returns a TypeGuard that checks for boolean values, and takes an optional, specific boolean value to check against. |
BoolStr | The BoolStr function returns a TypeGuard that checks for a string value that represents an boolean. |
Class | The Class function returns a TypeGuard that checks a value is of the class specified. |
Forbid | The Forbid function returns a TypeGuard that disallows certain types from an existing type. |
Func | The Func function returns a TypeGuard that checks a value is a function. An optional number of arguments can be specified as an additional check. |
Int | The Int function returns a TypeGuard that checks for integers, and takes optional min and max (inclusive) values to range check. |
IntStr | The IntStr function returns a TypeGuard that checks for a string value that represents an integer. Intended to be used with Rec for integer key types. |
MapType | The MapType function returns a TypeGuard that checks for an Map type where the keys and values are of the types specified. |
Null | The Null function returns a TypeGuard that checks for null . |
Num | The Num function returns a TypeGuard that checks for numbers, and takes optional min and max (inclusive) values to range check. |
NumStr | The NumStr function returns a TypeGuard that checks for a string value that represents an number. |
Obj | The Obj function returns a TypeGuard that checks for an object type defined by the passed object of TypeGuards. |
Opt | The Opt function returns a TypeGuard that checks for both the passed TypeGuard while allowing for it to be undefined. Equivalent to Or(T, Undefined()). |
Or | The Or function returns a TypeGuard that checks a value matches against any of the given TypeGuards. |
Part | The Part function takes an existing TypeGuard created by the Obj function and transforms it to allow any of the defined keys to not exist (or to be 'undefined'). |
Rec | The Rec function returns a TypeGuard that checks for an Object type where the keys and values are of the types specified. |
Recur | The Recur function wraps an existing TypeGuard so it can be used recursively within within itself during TypeGuard creation. The base TypeGuard will need to have its type specified manually when used this way. |
Req | The Req function takes an existing TypeGuard created by the Obj function and transforms it to require all of the defined keys to exist and to not be undefined. |
SetType | The SetType function returns a TypeGuard that checks for an Set type where the values are of the type specified. |
Skip | The Skip function takes an existing TypeGuard create by the Obj function and transforms it to not check the keys passed into this function. |
Str | The Str function returns a TypeGuard that checks for string values, and takes an optional regex to confirm string format against. |
Sym | The Sym function returns a TypeGuard that checks for symbols. |
Take | The Take function takes an existing TypeGuard create by the Obj function and transforms it to only check the keys passed into this function. |
Tmpl | The Tmpl function returns a TypeGuard that checks for template values. |
Tuple | The Tuple function returns a TypeGuard that checks for the given types in an array. TypeGuards can be spread to allow for and unknown number of that type (follow the typescript rules for spreads). |
Undefined | The Undefined function returns a TypeGuard that checks for undefined . |
Unknown | The Unknown function returns a TypeGuard that allows any value, but types to unknown . |
Val | The Val function returns a TypeGuard that checks for a specific, primitive value. |
Void | The Void function returns a TypeGuard that performs no check as the value is not intended to be used. |
To determine the type that a TypeGuard guards, you can use the TypeGuardOf<TypeGuard<any>>
type.
The urlstate module provides classes to create Bindings that store and retrieve data from the URL query string.
This module directly imports the bind module.
Export | Type | Description |
---|---|---|
(default) | Create a new object that binds a URL param to a value. | |
Codec | Allows for custom encoding/decoding of values to/from the URL. | |
goto | Process the parsed URL for state to be set and read. | |
setParam | Set a single param value. | |
toURL | Generate a URL from the current state. | |
urlChanged | A Subscription that fires whenever the URL changes. Produces the current history.state value, which should be the timestamp of when that URL was generated. |
<T>(name: string, value: T, checker?: (v: unknown) => v is T): Binding<T>;
This default export creates a new StateBound object, bound to the given name, that uses JSON for encoding an decoding.
It takes a name for the URL param, and a default value, which will not be encoded to the URL. Lastly, it takes an optional checker function to confirm that the value decoded is a valid value.
It is recommended to use a checker function, and the TypeGuard module can aid with that.
Returns a special binding that encoded and decodes its values to and from the URL.
To encode and decode, this function uses the built-in JSON object, extended to support the undefined
value.
class Codec {
constructor(encoder: (v: any) => string, decoder: (v: string) => any);
bind<T>(name: string, value: T, checker?: (v: unknown) => v is T): Binding<T>;
}
This class allows for custom encoding and decoding to state in the URL query.
The bind method matches the call for the [(default][#urlstate_default] export, but replaces the default codec with this one.
(href: string) => boolean;
This function processes the passed URL and, if it matches the current path, process the state from the query string
Returns true if href matches current path, false otherwise
(name: string, value: string) => void;
This function sets the named state to the given value, which will be decoded by the codec associated with that state, if one exists.
(withVals?: Record<String, string>, without?: string[]) => string;
This function is used to generate a search query from the current state, with the ability to add to or filter the state.
The withVals
object, if supplied, will add to and replace the state for the generation of the query string.
The without
array, if supplied, will filter the keys pulled out of the state and not add them to the query string.
The windows module adds custom elements to implement a windowing system.
This module directly imports the css, dom, html, misc, and svg modules.
Export | Type | Description |
---|---|---|
defaultIcon | String | The current default window icon. |
desktop | Function | A DOMBind that creates a DesktopElement. Registered with customElements as windows-desktop . |
DesktopElement | Class | This class creates a desktop-like space with a ShellElement. |
setDefaultIcon | Function | This function sets the defaultIcon variable. |
setLanguage | Function | Sets the language items used by the ShellElement and WindowElement classes. |
shell | Function | A DOMBind that creates a ShellElement. |
ShellElement | Class | A class to create a shell for WindowElements to exist within. Extends BaseElement. Registered with customElements as windows-shell . |
WindowElement | Class | This class represents a movable window with user specified contents. Extends BaseElement. Registered with customElements as windows-window . |
windows | Function | A DOMBind that creates a WindowElement. |
This unexported class provides some methods for both WindowElement and ShellElement.
Method | Description |
---|---|
alert | Creates a popup message window. |
confirm | Creates a popup confirmation window. |
prompt | Creates a popup window that asks for input. |
class BaseElement extends HTMLElement {
alert(title: string, message: string, icon?: string) => Promise<boolean>;
}
The alert method adds an alert-like window to the WindowElement or ShellElement it was called upon.
The button text is set to the OK
field of the language object, which can be set with setLanguage.
The returned Promise will resolve to true if the button is clicked, and false if the dialogue window was closed.
class BaseElement extends HTMLElement {
confirm(title: string, message: string, icon?: string) => Promise<boolean>;
}
The confirm method adds a confirm-like window to the WindowElement or ShellElement it was called upon.
The text of the two buttons is set to the OK
and CANCEL
fields of the language object, which can be set with setLanguage.
The returned Promise will resolve to true if the OK
button is clicked, and false if the CANCEL
button was clicked or the dialogue window was closed.
class BaseElement extends HTMLElement {
prompt(title: string, message: string, defaultValue = "", icon?: string) => Promise<string | null>;
}
The prompt method adds a prompt-like window to the WindowElement or ShellElement it was called upon.
The button text is set to the OK
field of the language object, which can be set with setLanguage.
The returned Promise will resolve to the text entered if the OK
button is clicked, or null if the dialogue window was closed.
(language: {
CANCEL?: string | Binding;
CLOSE?: string | Binding;
MAXIMISE?: string | Binding;
MINIMISE?: string | Binding;
OK?: string | Binding;
RESTORE?: string | Binding;
}) => void;
The setLanguage function sets the language items used by the ShellElement and WindowElement classes.
The ShellElement class is a CustomElement that can contain a single DesktopElement and any number of WindowElements.
This element registers with the name windows-shell
.
This element handles the following attributes.
Attribute | Type | Description |
---|---|---|
--shell-height | Number | Used to specify the internal height of the Shell . |
--shell-width | Number | Used to specify the internal width of the Shell . |
In addition to the methods provided by BaseElement, the following methods are provided:
Method | Description |
---|---|
addWindow | Adds a WindowElement to the Shell and focuses it. |
realignWindows | Repositions all WindowElements within the Shell to make sure they are all visible. |
The WindowElement class is a CustomElement that can be added to a ShellElement to provide a window-like interface to the contents of the element.
The ShellElement will determine whether Windows
can be minimised and how they are handled when they are. The ShellElement of this module disables minimising. It can be enabled by using the ShellElement of either the windows_taskbar or windows_taskmanager modules.
This element registers with the name windows-windows
.
This element handles the following attributes:
Attribute | Type | Description |
---|---|---|
hide-close | Toggle | Hides the Close button. |
hide-maximise | Toggle | Hides the Maximise button. |
hide-minimise | Toggle | Hides the Minimise button. |
hide-titlebar | Toggle | Hides the titlebar. |
maximised | Toggle | The window will expand to the size of the ShellElement. |
minimised | Toggle | The window will be hidden and it will be up to the shell to allow restoring it. |
resizable | Toggle | Allows the Window to be resized. |
window-icon | String | Sets the window icon. |
window-title | String | Sets the window title. |
In addition, the following CSS variables can be set to modify the dimensions of the Window.
Attribute | Description |
---|---|
--window-height | Number |
--window-left | Number |
--window-top | Number |
--window-width | Number |
Hover text on the default buttons can be modified via the setLanguage function.
The following entries affect this element:
Entry | Default Value | Description |
---|---|---|
CLOSE |
"Close" | Hover text on the 'Close Window' button. |
MAXIMISE |
"Maximise" | Hover text on the 'Maximise Window' button. |
MINIMISE |
"Minimise" | Hover text on the 'Minimise Window' button. |
RESTORE |
"Restore" | Hover text on the 'Restore Window' button. |
The following customs events can be dispatched:
Event | Description |
---|---|
close | Dispatched when either the Close button is clicked or the close method is called. |
moved | Dispatched when the Window is dragged around within the shell. |
remove | Dispatched when the Window is removed from the DOM. |
resized | Dispatched when the Window is resized. |
In addition to the methods provided by BaseElement, the following methods are provided:
Method | Description |
---|---|
addControlButton | Adds an additional, custom control button to the titlebar. |
addWindow | Adds a WindowElement to the Window as a child window. |
close | Closes the Window . |
focus | Brings the Window to the top of the window stack on the ShellElement. |
class WindowElement extends BaseElement {
addControlButton(icon: string, onclick: (this: WindowElement) => void, title?: string) => () => void;
}
The addControlButton method adds additional buttons to the titlebar of the Window
.
The returned function can be called to remove the button.
class WindowElement extends BaseElement {
addWindow(w: WindowElement) => boolean;
}
The addWindow method adds a Window
as a child. If there is already a child, it is added as a child of that Window
.
Returns true if the Window
was added, false otherwise.
class WindowElement extends BaseElement {
close() => boolean;
}
The close method will attempt to close the Window
. If the Window
has a child, that will be focussed instead.
When attempting to close, a cancellable close
event is dispatched to the WindowElement. If the event is cancelled, the Window
will remain open.
Returns true if the Window
was closed, false otherwise.
class WindowElement extends BaseElement {
focus() => void;
}
The focus method will unset a set minimise
attribute and bring the deepest child to the top of the window stack.
The windows_taskbar module provides a replacement for the windows module ShellElement that provides a taskbar for Windows
to be managed from and allows the Windows
to be minimised. The exports are the same as the windows module, except for the changes below.
This module directly imports the css, dom,html, menu and windows modules.
Export | Type | Description |
---|---|---|
setLanguage | Function | A replacement for the setLanguage function, which in addition to calling the original, sets the language entries used for the context menu for the items on the taskbar. The menu access keys are set to the first character of the entry. |
shell | Function | A DOMBind that creates a ShellElement. |
ShellElement | Class | A drop-in replacement for the windows module ShellElement. Registered with customElements as windows-shell-taskbar . |
The ShellElement class can accept the following attributes:
Attribute | Description |
---|---|
autohide | When set this attribute will hide the taskbar when it is not being hovered over. |
side | When set to one of left, right, or top, is used to change the side on which the taskbar will reside. It defaults to the bottom. |
hide | This attribute can be set to one of icon or title, which will hide either the icon or the text title of the window on the taskbar. |
In addition the taskbar-size style var can be used to set the width (or height, if vertical) of the taskbar.
The windows_taskmanager module provides a replacement for the windows module ShellElement that allows Windows
to be minimised within the shell, appearing as just the title-bar at the bottom of the shell. The exports are the same as the windows module, except for the changes below.
This module directly imports the css, dom,html, and windows modules.
Export | Type | Description |
---|---|---|
shell | Function | A DOMBind that creates a ShellElement. |
ShellElement | Class | A drop-in replacement for the windows module ShellElement. Registered with customElements as windows-shell-taskmanager . |
NB: Any custom control buttons will not be displayed on the title-bar while minimised.