Skip to content

dom ​

原文: https://finproducts.atlassian.net/wiki/spaces/JIDD3/pages/34793521247/FIN+5.3.1+dom 中文整理基于 FIN 5.3.1

导读: dom pod 提供了一个与浏览器 DOM 及相关浏览器 API 交互的框架。在大多数情况下,这些是逐一对应的:

以下为 API 参考,保留英文以便对照源码;目录已列出(英文标题便于检索);概述已尽量中译。


目录(导读) ​

  • classes
  • docs
  • Overview
  • Win
  • Doc
  • Elem
  • XmlHttpRequest
  • Observers
  • Slot Details
    • dropEffect
    • effectAllowed
    • files
    • getData
    • setData
    • setDragImage
    • types
    • activeElem
    • addCookie
    • body
    • cookies
    • createElem
    • elemById
    • elemFromPos
    • elemsFromPos
    • exec
    • hasFocus
    • head
    • onEvent
    • out
    • querySelector
    • querySelectorAll
    • removeEvent
    • title
    • accuracy
    • altitude
    • altitudeAccuracy
    • heading
    • lat
    • lng
    • speed
    • toStr
    • ts
    • ext
    • name
    • readAsDataUri
    • readAsText
    • size
    • type
    • add
    • addAll
    • animateStart
    • animateStop
    • attr
    • attrs
    • blur
    • children
    • clone
    • closest
    • containsChild
    • enabled
    • firstChild
    • focus
    • fromHtml
    • fromNative
    • get
    • hasChildren
    • html
    • id
    • insertBefore
    • invoke
    • lastChild
    • make
    • nextSibling
    • ns
    • pagePos
    • parent
    • pos
    • prevSibling
    • prop
    • relPos
    • remove
    • removeAll
    • removeAttr
    • renderCanvas
    • replace
    • scrollIntoView
    • scrollPos
    • scrollSize
    • set
    • setAttr
    • setProp
    • style
    • tagName
    • text
    • transition
    • trap
    • alt
    • button
    • ctrl
    • data
    • dataTransfer
    • delta
    • err
    • key
    • keyChar
    • meta
    • relatedTarget
    • shift
    • stash
    • stop
    • target
    • toNative
    • async
    • headers
    • onProgress
    • post
    • postForm
    • postFormMultipart
    • resType
    • send
  • …(其余标题见英文正文)

API 正文(英文) ​

Overview ​

The dom pod provides a framework for interoperating with the browser DOM and related browser APIs. For the most part, these map one-to-one:

Browser           Fantom
--------------    ---------------
Window            Win
Document          Doc
Element           Elem
Event             Event
XmlHttpRequest    HttpReq/HttpRes

Win ​

// basics
win := Win.cur       // get current Win instance
win.alert("Hello!")  // display a modal dialog
win.uri              // the URI for this page
win.hyperlink(uri)   // hyperlink to new page
win.viewport         // get size of window viewport

// event handlers
win.onEvent("hashchange", false) |e| { Win.cur.alert("hashchanged!") }

// storage
win.localStorage["bar"]         // return value for bar from local storage
win.localStorage["foo"] = 25    // store foo:25 in local storage
win.localStorage.remove("foo")  // remove foo from local storage
win.localStorage.clear          // clear all contents from local storage

Doc ​

doc := Win.cur.doc                // get doc instance for this window
doc.elem("someId")                // return the Elem with id='someId'
doc.createElem("div")             // create a new <div> element
doc.querySelector("div.foo")      // find first <div> element where class='foo'
doc.querySelectorAll("div.bar")   // find all <div> elements where class='bar'

Elem ​

// create Elems
Elem("div")   // create new unattached <div> element
Elem("img")   // create new unattached <img> element

// attributes
elem.id                          // 'id' attribute
elem.tagName                     // tag name of this element
elem.attr("alt")                 // get an attribute value
elem.setAttr("alt", "Alt text")  // set an attribute value
elem.removeAttr("alt")           // remove an attribute
elem["alt"]                      // get operator is a convenience for elem.attr
elem["alt"] = "Alt text"         // set operator is a convenience for elem.setAttr

// properties
elem.prop("value")               // get a DOM property value
elem.setProp("value", "foo")     // set a DOM property value
elem->value                      // trap getter is a convenience for elem.prop
elem->value = "foo"              // trap setter is a convenience for elem.setProp

// CSS classes
elem.style.classes               // return the current class name(s)
elem.style.hasClass("alpha")     // does this element have the given class name?
elem.style.addClass("beta")      // add a new class name to any current class names
elem.style.removeClass("gamma")  // remove a class name, leaving any others remaining
elem.style.toggleClass("beta")   // add class if not present, or remove if already exists

// CSS properties
elem.style["background-color"] = "#f00"  // set style background-color: #f00
elem.style->backgroundColor = "#f00"     // set style background-color: #f00
elem.style["color"]                      // get color property value
elem.style->color                        // get color property value
elem.style.computed("color")             // get the computed color property value
elem.style.setAll(["color":"#f00", "background:"#eee"])  // set list of style properties
elem.style.setCss("color: #f00; background: #eee")       // set style with CSS grammar

// tree
elem.parent             // parent element
elem.prevSibling        // prev sibling
elem.nextSibling        // next sibling
elem.children           // List of child elements
elem.firstChild         // first child, or null if no children
elem.lastChild          // last child, or null if no children
elem.add(child)         // add a new child element
elem.remove(child)      // remove a child element

// forms
elem->name              // the 'name' attribute
elem->checked           // true/false for checkboxes
elem->checked = true    // set 'checked' attribute
elem->value             // the 'value' attribute
elem->value = "foo"     // set 'value' attribute

// position and size
elem.bounds             // pos and size of element
elem.pos                // pos of element in pixels
elem.size               // size of element in pixels
elem.scrollPos          // scroll pos of element
elem.scrollSize         // scroll size of elemen

// event handlers
elem.focus              // focus element
elem.onEvent("click", false) |e| { Win.cur.alert("$e.target clicked!") }

// query
elem.querySelector("img")                  // find first <img> descendant
elem.querySelectorAll("img")               // find all <img> descendants
elem.querySelector("input[name='email']")  // find the <input> where name is "email"

// animation

XmlHttpRequest ​

The HttpReq object is used to make background HTTP requests from the browser. For both sync and async requests, the response is passed to you in the callback closure:

HttpReq { uri=`/foo` }.send("POST", "some content") |res|
{
  Win.cur.alert(res.content)
}

Convenience methods are availabe for the common request methods:

HttpReq { uri=`/foo` }.get |res| {...}
HttpReq { uri=`/foo` }.post("some content") |res| {...}
HttpReq { uri=`/foo` }.postForm(["name":"Barney Stinson"]) |res| {...}

The postForm will automatically encode the request to look like a normal HTML form submission.

Observers ​

ResizeObserver provides a callback when the size of a given element or list of elements is modified:

ResizeObserver {
  it.observe(elem)
  it.onResize |e| { echo("new size: ${e.first.size}") }
}

DataTransfer ​

@Js class DataTransfer : Obj

The DataTransfer object is used to hold the data that is being dragged during a drag and drop operation.

Fields

dropEffectThe effect used for drop targets.
effectAllowedThe effects that are allowed for this drag.

Methods

filesList of local files available on the data transfer, or empty list if this drag operation doesn't involve dragging files.
getDataGet data for given MIME type, or an empty string if data for that type does not exist or the data transfer contains no data.
setDataSet data for given MIME type.
setDragImageSet a custom image to be used for dragging, where x and y are offsets from the mouse cursor position.
typesList of the format types of data, in the same order the data was added.

Slot Details ​


dropEffect ​

Str dropEffect

The effect used for drop targets.


effectAllowed ​

Str effectAllowed

The effects that are allowed for this drag.


files ​

DomFile[] files()

List of local files available on the data transfer, or empty list if this drag operation doesn't involve dragging files.


getData ​

Str getData(Str type)

Get data for given MIME type, or an empty string if data for that type does not exist or the data transfer contains no data.


setData ​

This setData(Str type, Str val)

Set data for given MIME type.


setDragImage ​

This setDragImage(Elem image, Int x, Int y)

Set a custom image to be used for dragging, where x and y are offsets from the mouse cursor position.


types ​

Str[] types()

List of the format types of data, in the same order the data was added.


Doc ​

@Js class Doc : Obj

Doc models the DOM document object.

See pod doc for details.

Fields

titleThe title of this document.

Methods

activeElemGet the currently focused element, or null for none.
addCookieAdd a cookie to this session.
bodyGet the body element.
cookiesMap of cookie values keyed by cookie name.
createElemCreate a new element with the given tag name.
elemByIdGet the element with this id, or null if no element is found with this id.
elemFromPosGet the topmost element at the specified coordinates (relative to the viewport), or null if none found.
elemsFromPosGet a list of all elements at the specified coordinates (relative to the viewport).
execWhen a HTML document has been switched to designMode, the document object exposes the exec method which allows one to run commands to manipulate the contents of the editable region.
hasFocusReturn true if this document or any element inside the document has focus.
headGet the head element.
onEventAttach an event handler for the given event on this document.
outReturn a WebOutStream for writing content into this document.
querySelectorReturns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors, or null if none found.
querySelectorAllReturns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors.
removeEventRemove the given event handler from this document.

Slot Details ​


activeElem ​

Elem? activeElem()

Get the currently focused element, or null for none.


addCookie ​

Void addCookie(Cookie c)

Add a cookie to this session.


body ​

Elem body()

Get the body element.


cookies ​

Str:Str cookies()

Map of cookie values keyed by cookie name. The cookies map is readonly and case insensitive.


createElem ​

Elem createElem(Str tagName, [Str:Str]? attrib := null, Uri? ns := null)

Create a new element with the given tag name. If the attrib map is specified, set the new elements attributes to the given values. Optionally a namespace for the element can be specified with ns.


elemById ​

Elem? elemById(Str id)

Get the element with this id, or null if no element is found with this id.


elemFromPos ​

Elem? elemFromPos(Point p)

Get the topmost element at the specified coordinates (relative to the viewport), or null if none found.


elemsFromPos ​

Elem[] elemsFromPos(Point p)

Get a list of all elements at the specified coordinates (relative to the viewport). The elements are ordered from the topmost to the bottommost box of the viewport.


exec ​

Bool exec(Str name, Bool defUi := false, Obj? val := null)

When a HTML document has been switched to designMode, the document object exposes the exec method which allows one to run commands to manipulate the contents of the editable region.

  • name: the command name to execute
  • defUi: flag to indicate if default user interface is shown
  • val: optional value for commands that take an argument

hasFocus ​

Bool hasFocus()

Return true if this document or any element inside the document has focus.


Elem head()

Get the head element.


onEvent ​

Func onEvent(Str type, Bool useCapture, |Event| handler)

Attach an event handler for the given event on this document. Returns callback function instance.


out ​

WebOutStream out()

Return a WebOutStream for writing content into this document. You should call close on the stream when done writing to notify browser load is complete.


querySelector ​

Elem? querySelector(Str selectors)

Returns the first element within the document (using depth-first pre-order traversal of the document's nodes) that matches the specified group of selectors, or null if none found.


querySelectorAll ​

Elem[] querySelectorAll(Str selectors)

Returns a list of the elements within the document (using depth-first pre-order traversal of the document's nodes) that match the specified group of selectors.


removeEvent ​

Void removeEvent(Str type, Bool useCapture, Func handler)

Remove the given event handler from this document. If this handler was not registered, this method does nothing.


title ​

Str title

The title of this document.


DomCoord ​

@Js const class DomCoord : Obj

DomCoord models a DOM Coordinate object.

Methods

accuracyReturns a float representing the accuracy of the latitude and longitude properties, expressed in meters.
altitudeReturns a float representing the position's altitude in meters, relative to sea level.
altitudeAccuracyReturns a float representing the accuracy of the altitude expressed in meters.
headingReturns a float representing the direction in which the device is traveling.
latReturns a float representing the position's latitude in decimal degrees.
lngReturns a float representing the position's longitude in decimal degrees.
speedReturns a double representing the velocity of the device in meters per second.
toStr
tsOptional timestamp of when this location was retrieved.

Slot Details ​


accuracy ​

Float accuracy()

Returns a float representing the accuracy of the latitude and longitude properties, expressed in meters.


altitude ​

Float? altitude()

Returns a float representing the position's altitude in meters, relative to sea level. This value can be null if the implementation cannot provide the data.


altitudeAccuracy ​

Float? altitudeAccuracy()

Returns a float representing the accuracy of the altitude expressed in meters. This value can be null.


heading ​

Float? heading()

Returns a float representing the direction in which the device is traveling. This value, specified in degrees, indicates how far off from heading true north the device is. 0 degrees represents true north, and the direction is determined clockwise (which means that east is 90 degrees and west is 270 degrees). If speed is 0, heading is NaN. If the device is unable to provide heading information, this value is null.


lat ​

Float lat()

Returns a float representing the position's latitude in decimal degrees.


lng ​

Float lng()

Returns a float representing the position's longitude in decimal degrees.


speed ​

Float? speed()

Returns a double representing the velocity of the device in meters per second. This value can be null.


toStr ​

virtual override Str toStr()


ts ​

Duration? ts()

Optional timestamp of when this location was retrieved.


DomFile ​

@Js class DomFile : Obj

DomFile models a DOM File object.

Methods

extReturn file name extension (everything after the last dot) or null name has no dot.
nameName of file.
readAsDataUriAsynchronously load file contents as a data: URI representing the file's contents.
readAsTextAsynchronously load file contents as text and invoke the callback function with results.
sizeSize of file in bytes.
typeMIME type of the file as a read-only string or "" if the type could not be determined.

Slot Details ​


ext ​

Str? ext()

Return file name extension (everything after the last dot) or null name has no dot.


name ​

Str name()

Name of file. This is just the file name, and does not include any path information.


readAsDataUri ​

Void readAsDataUri(|Uri| f)

Asynchronously load file contents as a data: URI representing the file's contents.


readAsText ​

Void readAsText(|Str| f)

Asynchronously load file contents as text and invoke the callback function with results.


size ​

Int size()

Size of file in bytes.


type ​

Str type()

MIME type of the file as a read-only string or "" if the type could not be determined.


Elem ​

@Js class Elem : Obj

Elem models a DOM element object.

See pod doc for details.

Constructors

makeCreate a new Elem in the current Doc.

Fields

enabledThe enabled attribute for this element, or null if one not applicable.
htmlThe HTML markup contained in this element.
idThe id for this element.
posPosition of element relative to its parent in pixels.
scrollPosTop left scroll position of element.
sizeSize of element in pixels.
textText content contained in this element.

Methods

addAdd a new element as a child to this element.
addAllAdd all elements to this element.
animateStartStart an animation on this element using the given key frames.
animateStopStop the current animation on this element, or do nothing if no animation in progress.
attrGet the given HTML attribute value for this element.
attrsGet name:value map of all attributes.
blurRemove focus from this elem.
childrenGet the child nodes of this element.
cloneReturn a duplicate of this node.
closestTraverses this element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
containsChildReturn true if given element is a descendant of this node, or false if not.
firstChildGet the first child node of this element, or null if this element has no children.
focusRequest keyboard focus on this elem.
fromHtmlCreate an Elem instance from a HTML string.
fromNativeCreate an Elem instance from a native JavaScript DOM object.
getConvenience for attr.
hasChildrenReturn true if children is non-zero, false otherwise.
hasFocusReturn true if this elem has focus.
insertBeforeInsert a new element as a child to this element before the specified reference element.
invokeInvoke the given native DOM function with optional arguments.
lastChildGet the last child node of this element, or null if this element has no children.
nextSiblingGet the next sibling to this element, or null if this is the last element under its parent.
nsThe namespace URI of this element.
onEventAttach an event handler for the given event on this element.
pagePosPosition of element relative to the whole document.
parentGet the parent Elem of this element, or null if this element has no parent.
prevSiblingGet the previous sibling to this element, or null if this is the first element under its parent.
propGet the given DOM property value for this element.
querySelectorReturns the first element that is a descendant of this element on which it is invoked that matches the specified group of selectors.
querySelectorAllReturns a list of all elements descended from this element on which it is invoked that match the specified group of CSS selectors.
relPosGiven a page position, return p relative to this element.
removeRemove a child element from this element.
removeAllRemove all children from this element.
removeAttrRemove the given HTML attribute from this element.
removeEventRemove the given event handler from this element.
renderCanvasPaint a <canvas> element.
replaceReplace existing child node with a new child.
scrollIntoViewScroll parent container so this Elem is visible to user.
scrollSizeScrollable size of element.
setConveneince for setAttr.
setAttrSet the given HTML attribute value for this element.
setPropSet the given DOM properity value for this element.
styleGet the Style instance for this element.
tagNameGet the tag name for this element.
transitionTransition a set of CSS properties.
trapThe trap operator will behave slightly differently based on the namespace of the element.

Slot Details ​


add ​

@Operator virtual This add(Elem child)

Add a new element as a child to this element. Return this.


addAll ​

This addAll(Elem[] elems)

Add all elements to this element. Returns this.


animateStart ​

Void animateStart(KeyFrames frames, [Str:Obj]? opts, Duration dur)

Start an animation on this element using the given key frames.

frames := KeyFrames([
  KeyFrame("0%",   ["transform": "scale(1)"]),
  KeyFrame("50%",  ["transform": "scale(1.1)"]),
  KeyFrame("100%", ["transform": "scale(1)"]),
])

animate(frames, null, 5sec)
animate(frames, ["animation-iteration-count":"infinite"], 1sec)

animateStop ​

Void animateStop()

Stop the current animation on this element, or do nothing if no animation in progress.


attr ​

Str? attr(Str name)

Get the given HTML attribute value for this element. Returns null if attribute not defined.


attrs ​

Str:Str attrs()

Get name:value map of all attributes.


blur ​

virtual Void blur()

Remove focus from this elem.


children ​

Elem[] children()

Get the child nodes of this element.


clone ​

Elem clone(Bool deep := true)

Return a duplicate of this node.


closest ​

Elem? closest(Str selectors)

Traverses this element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector. Returns null if none found.


containsChild ​

Bool containsChild(Elem elem)

Return true if given element is a descendant of this node, or false if not.


enabled ​

virtual Bool? enabled

The enabled attribute for this element, or null if one not applicable. This is typically only valid for form elements.


firstChild ​

Elem? firstChild()

Get the first child node of this element, or null if this element has no children.


focus ​

virtual Void focus()

Request keyboard focus on this elem.


fromHtml ​

static Elem fromHtml(Str html)

Create an Elem instance from a HTML string. This is equivlaent

elem := Elem { it.html=html }.firstChild

fromNative ​

@Js static Elem fromNative(Obj elem, Type type := dom::Elem#)

Create an Elem instance from a native JavaScript DOM object. The type may be specified to create a subclass instance of Elem. Note if the native instance has already been mapped to Fantom, the existing instance is returned and type will have no effect.


get ​

@Operator Obj? get(Str name)

Convenience for attr.


hasChildren ​

Bool hasChildren()

Return true if children is non-zero, false otherwise.


hasFocus ​

virtual Bool hasFocus()

Return true if this elem has focus.


html ​

Str html

The HTML markup contained in this element.


id ​

Str? id

The id for this element. Returns null if id is not defined.


insertBefore ​

virtual This insertBefore(Elem child, Elem ref)

Insert a new element as a child to this element before the specified reference element. The reference element must be a child of this element. Returns this.


invoke ​

Obj? invoke(Str name, Obj?[]? args := null)

Invoke the given native DOM function with optional arguments.


lastChild ​

Elem? lastChild()

Get the last child node of this element, or null if this element has no children.


make ​

new make(Str tagName := "div", Uri? ns := null)

Create a new Elem in the current Doc. Optionally a namespace can be specified with ns.


nextSibling ​

Elem? nextSibling()

Get the next sibling to this element, or null if this is the last element under its parent.


ns ​

Uri ns()

The namespace URI of this element.


onEvent ​

Func onEvent(Str type, Bool useCapture, |Event| handler)

Attach an event handler for the given event on this element. Returns callback function instance.


pagePos ​

Point pagePos()

Position of element relative to the whole document.


parent ​

Elem? parent()

Get the parent Elem of this element, or null if this element has no parent.


pos ​

Point pos

Position of element relative to its parent in pixels.


prevSibling ​

Elem? prevSibling()

Get the previous sibling to this element, or null if this is the first element under its parent.


prop ​

Obj? prop(Str name)

Get the given DOM property value for this element. Returns null if property does not exist.


querySelector ​

Elem? querySelector(Str selectors)

Returns the first element that is a descendant of this element on which it is invoked that matches the specified group of selectors.


querySelectorAll ​

Elem[] querySelectorAll(Str selectors)

Returns a list of all elements descended from this element on which it is invoked that match the specified group of CSS selectors.


relPos ​

Point relPos(Point p)

Given a page position, return p relative to this element.


remove ​

virtual This remove(Elem child)

Remove a child element from this element. Return this.


removeAll ​

This removeAll()

Remove all children from this element. Returns this.


removeAttr ​

This removeAttr(Str name)

Remove the given HTML attribute from this element.


removeEvent ​

Void removeEvent(Str type, Bool useCapture, Func handler)

Remove the given event handler from this element. If this handler was not registered, this method does nothing.


renderCanvas ​

Void renderCanvas(|Graphics| f)

Paint a <canvas> element. The given callback is invoked with a graphics context to perform the rendering operation. Before calling this code, you should set the canvas width/height attributes to match the element size (typically as a ratio of the Win.devicePixelRatio).


replace ​

virtual This replace(Elem oldChild, Elem newChild)

Replace existing child node with a new child. Returns this.


scrollIntoView ​

This scrollIntoView(Bool alignToTop := true)

Scroll parent container so this Elem is visible to user. If alignToTop is true (the default value), the top of Elem is aligned to top of the visible area. If false, the bottom of Elem is aligned to bottom of the visible area.


scrollPos ​

Point scrollPos

Top left scroll position of element.


scrollSize ​

Size scrollSize()

Scrollable size of element.


set ​

@Operator Void set(Str name, Str? val)

Conveneince for setAttr.


setAttr ​

This setAttr(Str name, Str? val, Uri? ns := null)

Set the given HTML attribute value for this element. If val is null the attribute is removed (see removeAttr). Optionally a namespace can be specified with ns.


setProp ​

This setProp(Str name, Obj? val)

Set the given DOM properity value for this element.


size ​

Size size

Size of element in pixels.


style ​

Style style()

Get the Style instance for this element.


tagName ​

Str tagName()

Get the tag name for this element.


text ​

Str text

Text content contained in this element.


transition ​

Void transition(Str:Obj props, [Str:Obj]? opts, Duration dur, |Elem|? onComplete := null)

Transition a set of CSS properties.

transition(["opacity": "0.5"], null, 1sec) { echo("done!") }
transition(["opacity": "0.5"], ["transition-delay": 500ms], 1sec) { echo("done!") }

trap ​

virtual override Obj? trap(Str name, Obj?[]? args := null)

The trap operator will behave slightly differently based on the namespace of the element.

For HTML elements, trap works as a convenience for prop and setProp:

div := Elem("div")
div->tabIndex = 0   // equivalent to div.setProp("tabIndex", 0)

For SVG elements (where ns is `http://www.w3.org/2000/svg`), trap routes to attr and setAttr:

svg := Svg.line(0, 0, 10, 10)
svg->x1 = 5      // equivalent to svg.setAttr("x1", "5")
svg->y1 = 5      // equivalent to svg.setAttr("y1", "5")
svg->x2 == "10"  // equivalent to svg.attr("x2")

Event ​

@Js class Event : Obj

Event models the DOM event object.

Common event types:

"mousedown"   Fired when a mouse button is pressed on an element.

"mouseup"     Fired when a mouse button is released over an element.

"click"       Fired when a mouse button is pressed and released on a
              single element.

"dblclick"    Fired when a mouse button is clicked twice on a single element.

"mousemove"   Fired when a mouse is moved while over an element.

"mouseover"   Fired when mouse is moved onto the element that has the
              listener attached or onto one of its children.

"mouseout"    Fired when mouse is moved off the element that has the
              listener attached or off one of its children.

"mouseenter"  Fired when mouse is moved over the element that has the
              listener attached. Similar to '"mouseover"', it differs in
              that it doesn't bubble and that it isn't sent when the mouse
              is moved from one of its descendants' physical space to its
              own physical space.

              With deep hierarchies, the amount of mouseenter events sent
              can be quite huge and cause significant performance problems.
              In such cases, it is better to listen for "mouseover" events.

"mouseleave"  Fired when mouse is moved off the element that has the
              listener attached. Similar to "mouseout", it differs in that
              it doesn't bubble and that it isn't sent until the pointer
              has moved from its physical space and the one of all its
              descendants.

              With deep hierarchies, the amount of mouseleave events sent
              can be quite huge and cause significant performance problems.
              In such cases, it is better to listen for "mouseout" events.

"contextmenu" Fired when the right button of the mouse is clicked (before
              the context menu is displayed), or when the context menu key
              is pressed (in which case the context menu is displayed at the
              bottom left of the focused element, unless the element is a
              tree, in which case the context menu is displayed at the
              bottom left of the current row).

"focus"       The focus event is fired when an element has received focus

"blur"        The blur event is fired when an element has lost focus.

"keydown"     Fired when a key is pressed down.

"keyup"       Fired when a key is released.

"keypress"    Fired when a key is pressed down and that key normally
              produces a character value (use "input" instead).

"input"       Fired synchronously when the value of an <input> or
              <textarea> element is changed.

"dragstart"   Fired on an element when a drag is started. The user is
              requesting to drag the element where the dragstart event is
              fired. During this event, a listener would set information
              such as the drag data and image to be associated with the drag.
              This event is not fired when dragging a file into the browser
              from the OS.

"dragenter"   Fired when the mouse enters an element while a drag is
              occurring. A listener for this event should indicate whether
              a drop is allowed over this location. If there are no listeners,
              or the listeners perform no operations, then a drop is not
              allowed by default. This is also the event to listen for in
              order to provide feedback that a drop is allowed, such as
              displaying a highlight or insertion marker.

"dragover"    This event is fired as the mouse is moving over an element
              when a drag is occurring. Much of the time, the operation that
              occurs during a listener will be the same as the "dragenter"
              event.

"dragleave"   This event is fired when the mouse leaves an element while a
              drag is occurring. Listeners should remove any highlighting
              or insertion markers used for drop feedback.

"drag"        This event is fired at the source of the drag and is the element
              where "dragstart" was fired during the drag operation.

"drop"        The drop event is fired on the element where the drop
              occurred at the end of the drag operation. A listener would
              be responsible for retrieving the data being dragged and
              inserting it at the drop location. This event will only fire
              if a drop is desired. It will not fire if the user cancelled
              the drag operation, for example by pressing the Escape key,
              or if the mouse button was released while the mouse was not
              over a valid drop target.

"dragend"     The source of the drag will receive a "dragend" event when the
              drag operation is complete, whether it was successful or not.
              This event is not fired when dragging a file into the browser
              from the OS.

Fields

stashMeta-data for this event instance.

Methods

altReturn true if the ALT key was pressed during the event.
buttonMouse button number pressed.
ctrlReturn true if the CTRL key was pressed during the event.
dataData message used with HttpSocket.onReceive
dataTransferThe DataTransfer object for this event.
deltaScroll amount for wheel events.
errErr instance if available for window.onerror.
fromNativeCreate an Event instance from a native JavaScript Event object.
getGet an attribute by name.
keyKey instance for key pressed.
keyCharCharacter string for key event that represents text typed.
metaReturn true if the Meta key was pressed during the event.
pagePosThe mouse position of this event relative to page.
relatedTargetOptional secondary target depending on event type
setSet an attribute to the given value.
shiftReturn true if the SHIFT key was pressed during the event.
stopStop further propagation of this event.
targetThe target to which the event was dispatched.
toNativeGet the native JavaScript Event object
toStr
trapGet or set an attribute.
typeThe type of this event.

Slot Details ​


alt ​

Bool alt()

Return true if the ALT key was pressed during the event.


button ​

Int? button()

Mouse button number pressed.


ctrl ​

Bool ctrl()

Return true if the CTRL key was pressed during the event.


data ​

Obj data()

Data message used with HttpSocket.onReceive


dataTransfer ​

DataTransfer dataTransfer()

The DataTransfer object for this event.


delta ​

Point? delta()

Scroll amount for wheel events.


err ​

Err? err()

Err instance if available for window.onerror.


fromNative ​

@Js static Event fromNative(Obj event)

Create an Event instance from a native JavaScript Event object.


get ​

@Operator Obj? get(Str name, Obj? def := null)

Get an attribute by name. If not found return the specified default value.


key ​

Key? key()

Key instance for key pressed.


keyChar ​

Str? keyChar()

Character string for key event that represents text typed. For example Shift + Key.b would return "B".


meta ​

Bool meta()

Return true if the Meta key was pressed during the event. On Macs this maps to "command" key. On Windows this maps to "Windows" key.


pagePos ​

Point pagePos()

The mouse position of this event relative to page.


relatedTarget ​

Elem? relatedTarget()

Optional secondary target depending on event type:

event     target                relatedTarget
--------  --------------------  -----------------------------
blur      elem losing focus     elem receiving focus (if any)
focus     elem receiving focus  elem losing focus (if any)
focusin   elem receiving focus  elem losing focus (if any)
focusout  elem losing focus     elem receiving focus (if any)

set ​

@Operator Void set(Str name, Obj? val)

Set an attribute to the given value.


shift ​

Bool shift()

Return true if the SHIFT key was pressed during the event.


stash ​

Str:Obj? stash := [Str:Obj?][:]

Meta-data for this event instance.


stop ​

Void stop()

Stop further propagation of this event.


target ​

Elem target()

The target to which the event was dispatched.


toNative ​

@Js Obj toNative()

Get the native JavaScript Event object


toStr ​

virtual override Str toStr()


trap ​

virtual override Obj? trap(Str name, Obj?[]? args := null)

Get or set an attribute.


type ​

Str type()

The type of this event.


HttpReq ​

@Js class HttpReq : Obj

HttpReq models the request side of an XMLHttpRequest instance.

See pod doc for details.

Constructors

makeCreate a new HttpReq instance.

Fields

asyncIf true then perform this request asynchronously.
headersThe request headers to send.
resTypeThe type of data contained in the response.
uriThe Uri to send the request.
withCredentialsIndicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates.

Methods

getConvenience for send("GET", "", c).
onProgressOptional callback to track progress of request transfers, where loaded is the number of bytes that have been transferred, and total is the total number of bytes to be transferred.
postConvenience for send("POST", content, c).
postFormPost the form map as a HTML form submission.
postFormMultipartPost the form as a multipart/form-data submission.
sendSend a request with the given content using the given HTTP method (case does not matter).

Slot Details ​


async ​

Bool async := true

If true then perform this request asynchronously. Defaults to true


get ​

Void get(|HttpRes| c)

Convenience for send("GET", "", c).


headers ​

Str:Str headers := [Str:Str][:]

The request headers to send.


make ​

new make(|This|? f := null)

Create a new HttpReq instance.


onProgress ​

Void onProgress(|Int,Int| f)

Optional callback to track progress of request transfers, where loaded is the number of bytes that have been transferred, and total is the total number of bytes to be transferred.

For GET requests, the progress will track the response being downloaded to the browser. For PUT and POST requests, the progress will track the content being uploaded to the server.

Note this callback is only invoked when lengthComputable is true on the underlying progress events.


post ​

Void post(Obj content, |HttpRes| c)

Convenience for send("POST", content, c).


postForm ​

Void postForm(Str:Str form, |HttpRes| c)

Post the form map as a HTML form submission. Formats the map into a valid url-encoded content string, and sets Content-Type header to application/x-www-form-urlencoded.


postFormMultipart ​

Void postFormMultipart(Str:Obj form, |HttpRes| c)

Post the form as a multipart/form-data submission. Formats map into multipart key value pairs, where DomFile values will be encoded with file contents.


resType ​

Str resType := ""

The type of data contained in the response. It also lets the author change the response type. If an empty string is set as the value, the default value of "text" is used. Set this field to "arraybuffer" to access response as Buf.


send ​

Void send(Str method, Obj? content, |HttpRes| c)

Send a request with the given content using the given HTTP method (case does not matter). After receiving the response, call the given closure with the resulting HttpRes object.


uri ​

Uri uri := `#`

The Uri to send the request.


withCredentials ​

Bool withCredentials := false

Indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. Setting withCredentials has no effect on same-site requests. The default is false.

Requests from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request. The third-party cookies obtained by setting withCredentials to true will still honor same-origin policy and hence can not be accessed by the requesting script through Doc.cookies or from response headers.


HttpRes ​

@Js class HttpRes : Obj

HttpRes models the response side of an XMLHttpRequest instance.

See pod doc for details.

Fields

contentThe text content of the response when the XMLHttpRequest HttpReq.resType is "text"
contentBufThe binary content of the response when the XMLHttpRequest HttpReq.resType is "arraybuffer"
headersThe response headers.
statusThe HTTP status code of the response.

Slot Details ​


content ​

Str content := ""

The text content of the response when the XMLHttpRequest HttpReq.resType is "text"


contentBuf ​

Buf contentBuf := Buf.<ctor>(0)

The binary content of the response when the XMLHttpRequest HttpReq.resType is "arraybuffer"


headers ​

Str:Str headers := ...

The response headers.


status ​

Int status

The HTTP status code of the response.


HttpSocket ​

@Js class HttpSocket : Obj

HttpSocket implements an async WebSocket client

Methods

closeClose the web socket.
onCloseEvent fired when the web socket is closed
onErrorEvent fired when the web socket is closed due to an error
onOpenEvent fired when the web socket is opened
onReceiveEvent fired when the web socket receives a message.
openOpen a web socket to given URI with sub-protocol list
sendSend the data as a message - data must be a Str or in-memory Buf
uriUri passed to the open method

Slot Details ​


close ​

This close()

Close the web socket.


onClose ​

Void onClose(|Event| f)

Event fired when the web socket is closed


onError ​

Void onError(|Event| f)

Event fired when the web socket is closed due to an error


onOpen ​

Void onOpen(|Event| f)

Event fired when the web socket is opened


onReceive ​

Void onReceive(|Event| f)

Event fired when the web socket receives a message. The message payload is available as a Str or Buf via Event.data


open ​

static HttpSocket open(Uri uri, Str[]? protocols)

Open a web socket to given URI with sub-protocol list


send ​

This send(Obj data)

Send the data as a message - data must be a Str or in-memory Buf


uri ​

Uri uri()

Uri passed to the open method


Key ​

@Js @Serializable { simple=true } const class Key : Obj

Key models a key code

Constructors

fromStrLookup by string name or symbol

Fields

a
alt
b
backSlash
backspace
backtick
c
capsLock
closeBracket
codeKey code
comma
ctrl
d
dash
delete
down
e
end
enter
equal
esc
f
f1
f10
f2
f3
f4
f5
f6
f7
f8
f9
g
h
home
i
insert
j
k
l
left
m
meta
n
nameKey name
num0
num1
num2
num3
num4
num5
num6
num7
num8
num9
o
openBracket
p
pageDown
pageUp
period
q
quote
r
right
s
semicolon
shift
slash
space
symbolIf this a char symbol such as OpenBracket this is its symbol "[".
t
tab
u
up
v
w
x
y
z

Methods

equalsEquality is based on name.
fromCodeLookup by key code.
hashHash code is based on name.
isModifierIs this one of the modifier keys alt, shift, ctrl, meta
toStrReturn name.

Slot Details ​


a ​

const static Key a := ...


alt ​

const static Key alt := ...


b ​

const static Key b := ...


backSlash ​

const static Key backSlash := ...


backspace ​

const static Key backspace := ...


backtick ​

const static Key backtick := ...


c ​

const static Key c := ...


capsLock ​

const static Key capsLock := ...


closeBracket ​

const static Key closeBracket := ...


code ​

const Int code

Key code


comma ​

const static Key comma := ...


ctrl ​

const static Key ctrl := ...


d ​

const static Key d := ...


dash ​

const static Key dash := ...


delete ​

const static Key delete := ...


down ​

const static Key down := ...


e ​

const static Key e := ...


end ​

const static Key end := ...


enter ​

const static Key enter := ...


equal ​

const static Key equal := ...


equals ​

virtual override Bool equals(Obj? that)

Equality is based on name.


esc ​

const static Key esc := ...


f ​

const static Key f := ...


f1 ​

const static Key f1 := ...


f10 ​

const static Key f10 := ...


f2 ​

const static Key f2 := ...


f3 ​

const static Key f3 := ...


f4 ​

const static Key f4 := ...


f5 ​

const static Key f5 := ...


f6 ​

const static Key f6 := ...


f7 ​

const static Key f7 := ...


f8 ​

const static Key f8 := ...


f9 ​

const static Key f9 := ...


fromCode ​

static Key fromCode(Int code)

Lookup by key code.


fromStr ​

static new fromStr(Str s, Bool checked := true)

Lookup by string name or symbol


g ​

const static Key g := ...


h ​

const static Key h := ...


hash ​

virtual override Int hash()

Hash code is based on name.


home ​

const static Key home := ...


i ​

const static Key i := ...


insert ​

const static Key insert := ...


isModifier ​

Bool isModifier()

Is this one of the modifier keys alt, shift, ctrl, meta


j ​

const static Key j := ...


k ​

const static Key k := ...


l ​

const static Key l := ...


left ​

const static Key left := ...


m ​

const static Key m := ...


meta ​

const static Key meta := ...


n ​

const static Key n := ...


name ​

const Str name

Key name


num0 ​

const static Key num0 := ...


num1 ​

const static Key num1 := ...


num2 ​

const static Key num2 := ...


num3 ​

const static Key num3 := ...


num4 ​

const static Key num4 := ...


num5 ​

const static Key num5 := ...


num6 ​

const static Key num6 := ...


num7 ​

const static Key num7 := ...


num8 ​

const static Key num8 := ...


num9 ​

const static Key num9 := ...


o ​

const static Key o := ...


openBracket ​

const static Key openBracket := ...


p ​

const static Key p := ...


pageDown ​

const static Key pageDown := ...


pageUp ​

const static Key pageUp := ...


period ​

const static Key period := ...


q ​

const static Key q := ...


quote ​

const static Key quote := ...


r ​

const static Key r := ...


const static Key right := ...


s ​

const static Key s := ...


semicolon ​

const static Key semicolon := ...


shift ​

const static Key shift := ...


slash ​

const static Key slash := ...


space ​

const static Key space := ...


symbol ​

const Str? symbol

If this a char symbol such as OpenBracket this is its symbol "[". The arrow keys will return their respective Unicode arrow char.


t ​

const static Key t := ...


tab ​

const static Key tab := ...


toStr ​

virtual override Str toStr()

Return name.


u ​

const static Key u := ...


up ​

const static Key up := ...


v ​

const static Key v := ...


w ​

const static Key w := ...


x ​

const static Key x := ...


y ​

const static Key y := ...


z ​

const static Key z := ...


KeyFrame ​

@Js const class KeyFrame : Obj

KeyFrame defines a frame of a CSS animation.

Constructors

makeConstruct new KeyFrame for given step and props.

Fields

propsProperies for this keyframe.
stepPosition of this keyframe.

Slot Details ​


make ​

new make(Str step, Str:Obj props)

Construct new KeyFrame for given step and props.


props ​

const Str:Obj props

Properies for this keyframe.


step ​

const Str step

Position of this keyframe.


KeyFrames ​

@Js const class KeyFrames : Obj

KeyFrames defines a CSS animation from a list of KeyFrames.

Constructors

makeConstruct new animation with given frames.

Fields

framesFrames for this animation.

Methods

toStr

Slot Details ​


frames ​

const KeyFrame[] frames

Frames for this animation.


make ​

new make(KeyFrame[] frames)

Construct new animation with given frames.


toStr ​

virtual override Str toStr()


MutationObserver ​

@Js class MutationObserver : Obj

MutationObserver invokes a callback when DOM modifications occur.

Constructors

makeConstructor.

Methods

disconnectDisconnect this observer from receiving DOM mutation events.
observeRegister to receive DOM mutation events for given node.
takeRecsEmpties this observers's record queue and returns what was in there.

Slot Details ​


disconnect ​

This disconnect()

Disconnect this observer from receiving DOM mutation events.


make ​

new make(|MutationRec[]| callback)

Constructor.


observe ​

This observe(Elem target, Str:Obj opts)

Register to receive DOM mutation events for given node. At least one option is required:

  • "childList": true to observe node additions and removals on target (including text nodes)
  • "attrs": true to observe target attribute mutations
  • "charData": true to observe target data mutation
  • "subtree": true to observe target and target's descendant mutations
  • "attrOldVal": true to capture attribute value before mutation (requires "attrs":'true')
  • "charDataOldVal": true to capture target's data before mutation (requires "charData":'true')
  • "attrFilter": Str[] whitelist of attribute names to observe (requires "attrs":'true')

takeRecs ​

MutationRec[] takeRecs()

Empties this observers's record queue and returns what was in there.


MutationRec ​

@Js class MutationRec : Obj

MutationRec represents an individual DOM mutation.

Fields

addedList of nodes added, or empyt list if no nodes added.
attrName of the changed attribute, or null if no attribute was changed.
attrNsNamespace of the changed attribute, or null if no attribute was changed.
nextSiblingNext sibling of the added or removed nodes, or null if no nodes added or removed.
oldValOld value, depending on type
prevSiblingPrevious sibling of the added or removed nodes, or null if not nodes added or removed.
removedList of nodes removed, or empty list if no nodes removed.
targetTarget node that mutation affected, depending on the type
typeMutation type

Slot Details ​


added ​

Elem[] added

List of nodes added, or empyt list if no nodes added.


attr ​

Str? attr

Name of the changed attribute, or null if no attribute was changed.


attrNs ​

Str? attrNs

Namespace of the changed attribute, or null if no attribute was changed.


nextSibling ​

Elem? nextSibling

Next sibling of the added or removed nodes, or null if no nodes added or removed.


oldVal ​

Str? oldVal

Old value, depending on type:

  • For "attrs", it is the value of the changed attribute before the change
  • For "charData", it is the data of the changed node before the change
  • For "childList", it is null

prevSibling ​

Elem? prevSibling

Previous sibling of the added or removed nodes, or null if not nodes added or removed.


removed ​

Elem[] removed

List of nodes removed, or empty list if no nodes removed.


target ​

Elem target

Target node that mutation affected, depending on the type:

  • For "attrs", it is the element whose attribute changed
  • For "charData", it is the CharacterData node
  • For "childList", it is the node whose children changed

type ​

Str type

Mutation type:

  • "attrs" if the mutation was an attribute mutation
  • "charData" if it was a mutation to a CharacterData node
  • "childList" if it was a mutation to the tree of nodes

ResizeObserver ​

@Js class ResizeObserver : Obj

ResizeObserver invokes a callback when Elem size is changed.

Constructors

makeCreate a new ResizeObserver instance.

Methods

disconnectDisconnect this observer from all resize events for all nodes.
observeRegister to receive resize events for given node.
onResizeCallback when an observed target size has been modified.
unobserveStop receiving resize events for given node.

Slot Details ​


disconnect ​

This disconnect()

Disconnect this observer from all resize events for all nodes.


make ​

new make()

Create a new ResizeObserver instance.


observe ​

This observe(Elem target)

Register to receive resize events for given node.


onResize ​

Void onResize(|ResizeObserverEntry[]| callback)

Callback when an observed target size has been modified.


unobserve ​

This unobserve(Elem target)

Stop receiving resize events for given node.


ResizeObserverEntry ​

@Js class ResizeObserverEntry : Obj

ResizeObserverEntry models a resize event for ResizeObserver.

Fields

sizeNew size of target element.
targetElem that has been resized.

Methods

toStr

Slot Details ​


size ​

const Size size

New size of target element.


target ​

Elem target { private set }

Elem that has been resized.


toStr ​

virtual override Str toStr()


Storage ​

@Js class Storage : Obj

Storage models a DOM Storage.

See pod doc for details.

Methods

clearRemove all items from storage.
getReturn Obj stored under this key, or null if key does not exist.
keyReturn the key value for this index.
keysReturn a list of all keys for this index.
removeRemove value for this key.
setStore value under this key.
sizeReturn the number of items in storage.

Slot Details ​


clear ​

Void clear()

Remove all items from storage. If store was empty, this method does nothing.


get ​

@Operator Obj? get(Str key)

Return Obj stored under this key, or null if key does not exist.


key ​

Str? key(Int index)

Return the key value for this index. If the index is greater than or equal to size returns null.


keys ​

Str[] keys()

Return a list of all keys for this index.


remove ​

Void remove(Str key)

Remove value for this key. If no value for this key exists, this method does nothing.


set ​

@Operator Void set(Str key, Obj val)

Store value under this key.


size ​

Int size()

Return the number of items in storage.


Style ​

@Js class Style : Obj

Style models CSS style properties for an Elem.

Fields

classesThe CSS classes for this element.

Methods

addClassAdd the given CSS class name to this element.
addPseudoClassAdd a psuedo-class CSS definietion to this element.
clearClear all style declarations.
computedGet the computed property value.
effectiveGet the effetive style property value, which is the most specific style or CSS rule in effect on this node.
getGet the given property value.
hasClassReturn true if this element has the given CSS class name, or false if it does not.
removeClassRemove the given CSS class name to this element.
setSet the given propery value.
setAllSet all the given property values.
setCssSet properties via CSS text.
toggleClassToggle the presence of the given CSS class name based on the cond argument
trapGet or set an attribute.

Slot Details ​


addClass ​

This addClass(Str name)

Add the given CSS class name to this element. If this element already contains the given class name, then this method does nothing. Returns this.


addPseudoClass ​

Str addPseudoClass(Str name, Str css)

Add a psuedo-class CSS definietion to this element. A new class name is auto-generated and used to prefix name, name must start with the : character. Returns the generated class name.

style.addPseudoClass(":hover", "background: #eee")

classes ​

Str[] classes

The CSS classes for this element.


clear ​

This clear()

Clear all style declarations.


computed ​

Obj? computed(Str name)

Get the computed property value.


effective ​

Obj? effective(Str name)

Get the effetive style property value, which is the most specific style or CSS rule in effect on this node. Returns null if no rule in effect for given property.

This method is restricted to stylesheets that have originated from the same domain as the document. Any rules that may be applied from an external sheet will not be included.


get ​

@Operator Obj? get(Str name)

Get the given property value.

color := style["color"]

hasClass ​

Bool hasClass(Str name)

Return true if this element has the given CSS class name, or false if it does not.


removeClass ​

This removeClass(Str name)

Remove the given CSS class name to this element. If this element does not have the given class name, this method does nothing. Returns this.


set ​

@Operator This set(Str name, Obj? val)

Set the given propery value. If val is null this property is removed.

style["color"] = "#f00"

setAll ​

This setAll(Str:Obj? map)

Set all the given property values.

style.setAll(["color":"#f00", "font-weight":"bold"])

setCss ​

This setCss(Str css)

Set properties via CSS text.

style.setCss("color: #f00; font-weight: bold;")

toggleClass ​

This toggleClass(Str name, Bool? cond := null)

Toggle the presence of the given CSS class name based on the cond argument:

  • null: remove class if present, or add if missing
  • true: always add class (see addClass)
  • false: always remove class(see removeClass)

trap ​

virtual override Obj? trap(Str name, Obj?[]? args := null)

Get or set an attribute. Attribute names should be specifed in camel case:

style->backgroundColor == style["background-color"]

Svg ​

@Js const class Svg : Obj

SVG (Scalar Vector Graphics) utilities

Fields

nsSVG XML namesapce
nsXLinkXLink XML namespace

Methods

defAuto-generate an id for the def element and mount it into the svg document's defs section.
defUrlMount a definition element using def and return a CSS URL to the fragment identifier such as "url(#def-d)".
elemCreate element with proper namespace
imageConvenience to create a image element
lineConvenience to create line element
rectConvenience to create rect element
textConvenience to create text element

Slot Details ​


def ​

static Str def(Elem svgElem, Elem defElem)

Auto-generate an id for the def element and mount it into the svg document's defs section. This method will automatically generate a <defs> child in the svg document as needed. If defs already has an id or is already mounted, then no action is taken.


defUrl ​

static Str defUrl(Elem svgElem, Elem defElem)

Mount a definition element using def and return a CSS URL to the fragment identifier such as "url(#def-d)". This is used to reference gradient and clip definitions.


elem ​

static Elem elem(Str tagName)

Create element with proper namespace


image ​

static Elem image(Uri href, Float x, Float y, Float w, Float h)

Convenience to create a image element


line ​

static Elem line(Num x1, Num y1, Num x2, Num y2)

Convenience to create line element


ns ​

const static Uri ns := `http://www.w3.org/2000/svg`

SVG XML namesapce


const static Uri nsXLink := `http://www.w3.org/1999/xlink`

XLink XML namespace


rect ​

static Elem rect(Num x, Num y, Num w, Num h)

Convenience to create rect element


text ​

static Elem text(Str text, Num x, Num y)

Convenience to create text element


WeakMap ​

@Js class WeakMap : Obj

WeakMap is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.

Methods

deleteRemoves any value associated to the key.
getReturns the value associated to the key, or null if there is none.
hasReturn true if key exists in this map.
setSets value for given key in this map.

Slot Details ​


delete ​

Bool delete(Obj key)

Removes any value associated to the key. Returns true if an element has been removed successfully.


get ​

@Operator Obj? get(Obj key)

Returns the value associated to the key, or null if there is none.


has ​

Bool has(Obj key)

Return true if key exists in this map.


set ​

@Operator This set(Obj key, Obj val)

Sets value for given key in this map. Returns this.


Win ​

@Js class Win : Obj

Win models the DOM window object.

See pod doc for details.

Methods

addStyleRulesAdd new CSS style rules to this page.
alertDisplay a modal message box with the given text.
clearIntervalCancels a repeated action which was set up using setInterval.
clearTimeoutClears the delay set by setTimeout.
clipboardReadTextRead textual contents of the system clipboard.
clipboardWriteTextWrite given text to the system clipboard.
closeClose this window.
confirmDisplay a confirmation dialog box with the given text.
curReturn the current window instance.
devicePixelRatioRatio of physical pixels to the resolution in CSS pixels
docReturn the Doc instance for this window.
evalEvaluate given JavaScript code.
geoClearWatchUnregister location/error monitoring handlers previously installed using geoWatchPosition.
geoCurPositionGet the the current position of this device.
geoWatchPositionRegister a handler function that will be called automatically each time the position of the device changes.
hisBackGo to previous page in session history.
hisForwardGo to next page in the session history.
hisPushStatePush a new history item onto the history stack.
hisReplaceStateModify the current history item.
hisStateState at the top of the history stack
hyperlinkHyperlink to the given Uri in this window.
localStorageReturn local storage instance for window.
logLog object to console.
onEventAttach an event handler for the given event on this window.
openOpen a new window.
parentReturns a reference to the parent of the current window or subframe, or null if this is the top-most window.
reloadReload the current page.
removeEventRemove the given event handler from this window.
reqAnimationFrameRequest the browser to perform an animation before the next repaint.
screenSizeReturn the size of the screen in pixels.
scrollByScrolls the document in the window by the given amount.
scrollPosReturn current scroll position of document in this window.
scrollToScrolls to a particular set of coordinates in the document.
sessionStorageReturn session storage instance for window.
setIntervalCalls a function repeatedly, with a fixed time delay between each call to that function.
setTimeoutCall the specified function after a specified delay.
topReturns a reference to the topmost window in the window hierarchy.
uriGet the Uri for this window.
viewportReturn the size of the window viewport in pixels.

Slot Details ​


addStyleRules ​

Void addStyleRules(Str rules)

Add new CSS style rules to this page.


alert ​

Void alert(Obj obj)

Display a modal message box with the given text.


clearInterval ​

Void clearInterval(Int intervalId)

Cancels a repeated action which was set up using setInterval.


clearTimeout ​

Void clearTimeout(Int timeoutId)

Clears the delay set by setTimeout.


clipboardReadText ​

Void clipboardReadText(|Str| f)

Read textual contents of the system clipboard. Returns an empty string if the clipboard is empty, does not contain text, or does not include a textual representation of clipboard's contents.

The user has to interact with the page or a UI element in order for this feature to work.


clipboardWriteText ​

Void clipboardWriteText(Str text)

Write given text to the system clipboard.

The user has to interact with the page or a UI element in order for this feature to work.


close ​

Win close()

Close this window. Only applicable to windows created with open. Otherwise method has no effect. Returns this.


confirm ​

Bool confirm(Obj obj)

Display a confirmation dialog box with the given text. Returns true if ok was selected, false othterwise.


cur ​

static Win cur()

Return the current window instance.


devicePixelRatio ​

Float devicePixelRatio()

Ratio of physical pixels to the resolution in CSS pixels


doc ​

Doc doc()

Return the Doc instance for this window.


eval ​

static Obj eval(Str js)

Evaluate given JavaScript code.


geoClearWatch ​

Void geoClearWatch(Int id)

Unregister location/error monitoring handlers previously installed using geoWatchPosition. This feature is only available in secure contexts (HTTPS).


geoCurPosition ​

Void geoCurPosition(|DomCoord| onSuccess, |Err|? onErr := null, [Str:Obj]? opts := null)

Get the the current position of this device. This feature is only available in secure contexts (HTTPS).


geoWatchPosition ​

Int geoWatchPosition(|DomCoord| onSuccess, |Err|? onErr := null, [Str:Obj]? opts := null)

Register a handler function that will be called automatically each time the position of the device changes. This method returns a watch ID value that then can be used to unregister the handler with the geoClearWatch method. This feature is only available in secure contexts (HTTPS).


hisBack ​

Void hisBack()

Go to previous page in session history.


hisForward ​

Void hisForward()

Go to next page in the session history.


hisPushState ​

Void hisPushState(Str title, Uri uri, Str:Obj map)

Push a new history item onto the history stack. Use onpopstate to listen for changes:

// Event.stash contains state map passed into pushState
Win.cur.onEvent("popstate", false) |e| { echo("# state: $e.stash") }

hisReplaceState ​

Void hisReplaceState(Str title, Uri uri, Str:Obj map)

Modify the current history item.


hisState ​

Str:Obj hisState()

State at the top of the history stack


Void hyperlink(Uri uri)

Hyperlink to the given Uri in this window.


localStorage ​

Storage localStorage()

Return local storage instance for window.


log ​

Void log(Obj? obj)

Log object to console.


onEvent ​

Func onEvent(Str type, Bool useCapture, |Event| handler)

Attach an event handler for the given event on this window. Returns callback function instance.


open ​

Win open(Uri uri := `about:blank`, Str? winName := null, [Str:Str]? opts := null)

Open a new window. Returns the new window instance.


parent ​

Win? parent()

Returns a reference to the parent of the current window or subframe, or null if this is the top-most window.


reload ​

Void reload(Bool force := false)

Reload the current page. Use force to bypass browse cache.


removeEvent ​

Void removeEvent(Str type, Bool useCapture, Func handler)

Remove the given event handler from this window. If this handler was not registered, this method does nothing.


reqAnimationFrame ​

Void reqAnimationFrame(|This| f)

Request the browser to perform an animation before the next repaint.


screenSize ​

Size screenSize()

Return the size of the screen in pixels.


scrollBy ​

This scrollBy(Int x, Int y)

Scrolls the document in the window by the given amount.


scrollPos ​

Point scrollPos()

Return current scroll position of document in this window.


scrollTo ​

This scrollTo(Int x, Int y)

Scrolls to a particular set of coordinates in the document.


sessionStorage ​

Storage sessionStorage()

Return session storage instance for window.


setInterval ​

Int setInterval(Duration delay, |This| f)

Calls a function repeatedly, with a fixed time delay between each call to that function. Returns an intervalId that can be used in clearInterval.


setTimeout ​

Int setTimeout(Duration delay, |This| f)

Call the specified function after a specified delay. Returns a timeoutId that can be used in clearTimeout.


top ​

Win top()

Returns a reference to the topmost window in the window hierarchy. If this window is the topmost window, returns self.


uri ​

Uri uri()

Get the Uri for this window.


viewport ​

Size viewport()

Return the size of the window viewport in pixels.