外观
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/HttpResWin
// 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 storageDoc
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"
// animationXmlHttpRequest
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
| dropEffect | The effect used for drop targets. |
| effectAllowed | The effects that are allowed for this drag. |
Methods
| files | List of local files available on the data transfer, or empty list if this drag operation doesn't involve dragging files. |
| getData | 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 | Set data for given MIME type. |
| setDragImage | Set a custom image to be used for dragging, where x and y are offsets from the mouse cursor position. |
| types | List 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
| title | The title of this document. |
Methods
| activeElem | Get the currently focused element, or null for none. |
| addCookie | Add a cookie to this session. |
| body | Get the body element. |
| cookies | Map of cookie values keyed by cookie name. |
| createElem | Create a new element with the given tag name. |
| elemById | Get the element with this id, or null if no element is found with this id. |
| elemFromPos | Get the topmost element at the specified coordinates (relative to the viewport), or null if none found. |
| elemsFromPos | Get a list of all elements at the specified coordinates (relative to the viewport). |
| exec | 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. |
| hasFocus | Return true if this document or any element inside the document has focus. |
| head | Get the head element. |
| onEvent | Attach an event handler for the given event on this document. |
| out | Return a WebOutStream for writing content into this document. |
| querySelector | 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 | 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 | Remove 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 executedefUi: flag to indicate if default user interface is shownval: optional value for commands that take an argument
hasFocus
Bool hasFocus()
Return true if this document or any element inside the document has focus.
head
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
| accuracy | Returns a float representing the accuracy of the latitude and longitude properties, expressed in meters. |
| altitude | Returns a float representing the position's altitude in meters, relative to sea level. |
| altitudeAccuracy | Returns a float representing the accuracy of the altitude expressed in meters. |
| heading | Returns a float representing the direction in which the device is traveling. |
| lat | Returns a float representing the position's latitude in decimal degrees. |
| lng | Returns a float representing the position's longitude in decimal degrees. |
| speed | Returns a double representing the velocity of the device in meters per second. |
| toStr | |
| ts | Optional 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
| ext | Return file name extension (everything after the last dot) or null name has no dot. |
| name | Name of file. |
| readAsDataUri | Asynchronously load file contents as a data: URI representing the file's contents. |
| readAsText | Asynchronously load file contents as text and invoke the callback function with results. |
| size | Size of file in bytes. |
| type | MIME 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
| make | Create a new Elem in the current Doc. |
Fields
| enabled | The enabled attribute for this element, or null if one not applicable. |
| html | The HTML markup contained in this element. |
| id | The id for this element. |
| pos | Position of element relative to its parent in pixels. |
| scrollPos | Top left scroll position of element. |
| size | Size of element in pixels. |
| text | Text content contained in this element. |
Methods
| add | Add a new element as a child to this element. |
| addAll | Add all elements to this element. |
| animateStart | Start an animation on this element using the given key frames. |
| animateStop | Stop the current animation on this element, or do nothing if no animation in progress. |
| attr | Get the given HTML attribute value for this element. |
| attrs | Get name:value map of all attributes. |
| blur | Remove focus from this elem. |
| children | Get the child nodes of this element. |
| clone | Return a duplicate of this node. |
| closest | Traverses this element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector. |
| containsChild | Return true if given element is a descendant of this node, or false if not. |
| firstChild | Get the first child node of this element, or null if this element has no children. |
| focus | Request keyboard focus on this elem. |
| fromHtml | Create an Elem instance from a HTML string. |
| fromNative | Create an Elem instance from a native JavaScript DOM object. |
| get | Convenience for attr. |
| hasChildren | Return true if children is non-zero, false otherwise. |
| hasFocus | Return true if this elem has focus. |
| insertBefore | Insert a new element as a child to this element before the specified reference element. |
| invoke | Invoke the given native DOM function with optional arguments. |
| lastChild | Get the last child node of this element, or null if this element has no children. |
| nextSibling | Get the next sibling to this element, or null if this is the last element under its parent. |
| ns | The namespace URI of this element. |
| onEvent | Attach an event handler for the given event on this element. |
| pagePos | Position of element relative to the whole document. |
| parent | Get the parent Elem of this element, or null if this element has no parent. |
| prevSibling | Get the previous sibling to this element, or null if this is the first element under its parent. |
| prop | Get the given DOM property value for this element. |
| querySelector | Returns the first element that is a descendant of this element on which it is invoked that matches the specified group of selectors. |
| querySelectorAll | Returns a list of all elements descended from this element on which it is invoked that match the specified group of CSS selectors. |
| relPos | Given a page position, return p relative to this element. |
| remove | Remove a child element from this element. |
| removeAll | Remove all children from this element. |
| removeAttr | Remove the given HTML attribute from this element. |
| removeEvent | Remove the given event handler from this element. |
| renderCanvas | Paint a <canvas> element. |
| replace | Replace existing child node with a new child. |
| scrollIntoView | Scroll parent container so this Elem is visible to user. |
| scrollSize | Scrollable size of element. |
| set | Conveneince for setAttr. |
| setAttr | Set the given HTML attribute value for this element. |
| setProp | Set the given DOM properity value for this element. |
| style | Get the Style instance for this element. |
| tagName | Get the tag name for this element. |
| transition | Transition a set of CSS properties. |
| trap | The 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 }.firstChildfromNative
@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
| stash | Meta-data for this event instance. |
Methods
| alt | Return true if the ALT key was pressed during the event. |
| button | Mouse button number pressed. |
| ctrl | Return true if the CTRL key was pressed during the event. |
| data | Data message used with HttpSocket.onReceive |
| dataTransfer | The DataTransfer object for this event. |
| delta | Scroll amount for wheel events. |
| err | Err instance if available for window.onerror. |
| fromNative | Create an Event instance from a native JavaScript Event object. |
| get | Get an attribute by name. |
| key | Key instance for key pressed. |
| keyChar | Character string for key event that represents text typed. |
| meta | Return true if the Meta key was pressed during the event. |
| pagePos | The mouse position of this event relative to page. |
| relatedTarget | Optional secondary target depending on event type |
| set | Set an attribute to the given value. |
| shift | Return true if the SHIFT key was pressed during the event. |
| stop | Stop further propagation of this event. |
| target | The target to which the event was dispatched. |
| toNative | Get the native JavaScript Event object |
| toStr | |
| trap | Get or set an attribute. |
| type | The 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
| make | Create a new HttpReq instance. |
Fields
| async | If true then perform this request asynchronously. |
| headers | The request headers to send. |
| resType | The type of data contained in the response. |
| uri | The Uri to send the request. |
| withCredentials | Indicates whether or not cross-site Access-Control requests should be made using credentials such as cookies, authorization headers or TLS client certificates. |
Methods
| get | Convenience for send("GET", "", c). |
| onProgress | 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. |
| post | Convenience for send("POST", content, c). |
| postForm | Post the form map as a HTML form submission. |
| postFormMultipart | Post the form as a multipart/form-data submission. |
| send | Send 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
| content | The text content of the response when the XMLHttpRequest HttpReq.resType is "text" |
| contentBuf | The binary content of the response when the XMLHttpRequest HttpReq.resType is "arraybuffer" |
| headers | The response headers. |
| status | The 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
| close | Close the web socket. |
| onClose | Event fired when the web socket is closed |
| onError | Event fired when the web socket is closed due to an error |
| onOpen | Event fired when the web socket is opened |
| onReceive | Event fired when the web socket receives a message. |
| open | Open a web socket to given URI with sub-protocol list |
| send | Send the data as a message - data must be a Str or in-memory Buf |
| uri | Uri 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
| fromStr | Lookup by string name or symbol |
Fields
| a | |
| alt | |
| b | |
| backSlash | |
| backspace | |
| backtick | |
| c | |
| capsLock | |
| closeBracket | |
| code | Key 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 | |
| name | Key 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 | |
| symbol | If this a char symbol such as OpenBracket this is its symbol "[". |
| t | |
| tab | |
| u | |
| up | |
| v | |
| w | |
| x | |
| y | |
| z |
Methods
| equals | Equality is based on name. |
| fromCode | Lookup by key code. |
| hash | Hash code is based on name. |
| isModifier | Is this one of the modifier keys alt, shift, ctrl, meta |
| toStr | Return 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 := ...
right
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
| make | Construct new KeyFrame for given step and props. |
Fields
| props | Properies for this keyframe. |
| step | Position 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
| make | Construct new animation with given frames. |
Fields
| frames | Frames 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
| make | Constructor. |
Methods
| disconnect | Disconnect this observer from receiving DOM mutation events. |
| observe | Register to receive DOM mutation events for given node. |
| takeRecs | Empties 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":
trueto observe node additions and removals on target (including text nodes) - "attrs":
trueto observe target attribute mutations - "charData":
trueto observe target data mutation - "subtree":
trueto observe target and target's descendant mutations - "attrOldVal":
trueto capture attribute value before mutation (requires "attrs":'true') - "charDataOldVal":
trueto 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
| added | List of nodes added, or empyt list if no nodes added. |
| attr | Name of the changed attribute, or null if no attribute was changed. |
| attrNs | Namespace of the changed attribute, or null if no attribute was changed. |
| nextSibling | Next sibling of the added or removed nodes, or null if no nodes added or removed. |
| oldVal | Old value, depending on type |
| prevSibling | Previous sibling of the added or removed nodes, or null if not nodes added or removed. |
| removed | List of nodes removed, or empty list if no nodes removed. |
| target | Target node that mutation affected, depending on the type |
| type | Mutation 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
| make | Create a new ResizeObserver instance. |
Methods
| disconnect | Disconnect this observer from all resize events for all nodes. |
| observe | Register to receive resize events for given node. |
| onResize | Callback when an observed target size has been modified. |
| unobserve | Stop 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
| size | New size of target element. |
| target | Elem 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
| clear | Remove all items from storage. |
| get | Return Obj stored under this key, or null if key does not exist. |
| key | Return the key value for this index. |
| keys | Return a list of all keys for this index. |
| remove | Remove value for this key. |
| set | Store value under this key. |
| size | Return 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
| classes | The CSS classes for this element. |
Methods
| addClass | Add the given CSS class name to this element. |
| addPseudoClass | Add a psuedo-class CSS definietion to this element. |
| clear | Clear all style declarations. |
| computed | Get the computed property value. |
| effective | Get the effetive style property value, which is the most specific style or CSS rule in effect on this node. |
| get | Get the given property value. |
| hasClass | Return true if this element has the given CSS class name, or false if it does not. |
| removeClass | Remove the given CSS class name to this element. |
| set | Set the given propery value. |
| setAll | Set all the given property values. |
| setCss | Set properties via CSS text. |
| toggleClass | Toggle the presence of the given CSS class name based on the cond argument |
| trap | Get 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 missingtrue: always add class (seeaddClass)false: always remove class(seeremoveClass)
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
| ns | SVG XML namesapce |
| nsXLink | XLink XML namespace |
Methods
| def | Auto-generate an id for the def element and mount it into the svg document's defs section. |
| defUrl | Mount a definition element using def and return a CSS URL to the fragment identifier such as "url(#def-d)". |
| elem | Create element with proper namespace |
| image | Convenience to create a image element |
| line | Convenience to create line element |
| rect | Convenience to create rect element |
| text | Convenience 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
nsXLink
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
| delete | Removes any value associated to the key. |
| get | Returns the value associated to the key, or null if there is none. |
| has | Return true if key exists in this map. |
| set | Sets 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
| addStyleRules | Add new CSS style rules to this page. |
| alert | Display a modal message box with the given text. |
| clearInterval | Cancels a repeated action which was set up using setInterval. |
| clearTimeout | Clears the delay set by setTimeout. |
| clipboardReadText | Read textual contents of the system clipboard. |
| clipboardWriteText | Write given text to the system clipboard. |
| close | Close this window. |
| confirm | Display a confirmation dialog box with the given text. |
| cur | Return the current window instance. |
| devicePixelRatio | Ratio of physical pixels to the resolution in CSS pixels |
| doc | Return the Doc instance for this window. |
| eval | Evaluate given JavaScript code. |
| geoClearWatch | Unregister location/error monitoring handlers previously installed using geoWatchPosition. |
| geoCurPosition | Get the the current position of this device. |
| geoWatchPosition | Register a handler function that will be called automatically each time the position of the device changes. |
| hisBack | Go to previous page in session history. |
| hisForward | Go to next page in the session history. |
| hisPushState | Push a new history item onto the history stack. |
| hisReplaceState | Modify the current history item. |
| hisState | State at the top of the history stack |
| hyperlink | Hyperlink to the given Uri in this window. |
| localStorage | Return local storage instance for window. |
| log | Log object to console. |
| onEvent | Attach an event handler for the given event on this window. |
| open | Open a new window. |
| parent | Returns a reference to the parent of the current window or subframe, or null if this is the top-most window. |
| reload | Reload the current page. |
| removeEvent | Remove the given event handler from this window. |
| reqAnimationFrame | Request the browser to perform an animation before the next repaint. |
| screenSize | Return the size of the screen in pixels. |
| scrollBy | Scrolls the document in the window by the given amount. |
| scrollPos | Return current scroll position of document in this window. |
| scrollTo | Scrolls to a particular set of coordinates in the document. |
| sessionStorage | Return session storage instance for window. |
| setInterval | Calls a function repeatedly, with a fixed time delay between each call to that function. |
| setTimeout | Call the specified function after a specified delay. |
| top | Returns a reference to the topmost window in the window hierarchy. |
| uri | Get the Uri for this window. |
| viewport | Return 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
hyperlink
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.