Kotlin DOM API compatibility library providing JavaScript interoperability and DOM manipulation utilities
—
Comprehensive collection of specialized W3C APIs including media handling, graphics (SVG/WebGL), service workers, file management, and modern browser features for advanced web application development.
Media capture API for accessing camera, microphone, and screen sharing capabilities.
/**
* Media stream for audio/video content
*/
external interface MediaStream : EventTarget, MediaProvider {
/** Whether the stream is active */
val active: Boolean
/** Unique stream identifier */
val id: String
/** Get audio tracks */
fun getAudioTracks(): Array<MediaStreamTrack>
/** Get video tracks */
fun getVideoTracks(): Array<MediaStreamTrack>
/** Get all tracks */
fun getTracks(): Array<MediaStreamTrack>
/** Get track by ID */
fun getTrackById(trackId: String): MediaStreamTrack?
/** Add track to stream */
fun addTrack(track: MediaStreamTrack)
/** Remove track from stream */
fun removeTrack(track: MediaStreamTrack)
/** Clone the stream */
fun clone(): MediaStream
}
/**
* Individual media track (audio or video)
*/
external interface MediaStreamTrack : EventTarget {
/** Track kind (audio/video) */
val kind: String
/** Track identifier */
val id: String
/** Track label */
val label: String
/** Whether track is enabled */
var enabled: Boolean
/** Whether track is muted */
val muted: Boolean
/** Track ready state */
val readyState: MediaStreamTrackState
/** Clone the track */
fun clone(): MediaStreamTrack
/** Stop the track */
fun stop()
/** Get track capabilities */
fun getCapabilities(): MediaTrackCapabilities
/** Get current constraints */
fun getConstraints(): MediaTrackConstraints
/** Get current settings */
fun getSettings(): MediaTrackSettings
/** Apply new constraints */
fun applyConstraints(constraints: MediaTrackConstraints = definedExternally): Promise<Unit>
}
/**
* Media devices access
*/
external interface MediaDevices : EventTarget {
/** Get user media (camera/microphone) */
fun getUserMedia(constraints: MediaStreamConstraints = definedExternally): Promise<MediaStream>
/** Get display media (screen sharing) */
fun getDisplayMedia(constraints: MediaStreamConstraints = definedExternally): Promise<MediaStream>
/** Enumerate available devices */
fun enumerateDevices(): Promise<Array<MediaDeviceInfo>>
/** Get supported constraints */
fun getSupportedConstraints(): MediaTrackSupportedConstraints
}
/**
* Media device information
*/
external interface MediaDeviceInfo {
/** Device identifier */
val deviceId: String
/** Device kind */
val kind: MediaDeviceKind
/** Device label */
val label: String
/** Device group identifier */
val groupId: String
}
enum class MediaStreamTrackState { LIVE, ENDED }
enum class MediaDeviceKind { AUDIOINPUT, AUDIOOUTPUT, VIDEOINPUT }File handling and blob manipulation for file uploads and processing.
/**
* Binary data representation
*/
external class Blob(blobParts: Array<dynamic> = definedExternally, options: BlobPropertyBag = definedExternally) : MediaProvider, ImageBitmapSource {
/** Blob size in bytes */
val size: Double
/** Blob MIME type */
val type: String
/** Create blob slice */
fun slice(start: Int = definedExternally, end: Int = definedExternally, contentType: String = definedExternally): Blob
/** Get blob as stream */
fun stream(): ReadableStream<Uint8Array>
/** Get blob as text */
fun text(): Promise<String>
/** Get blob as array buffer */
fun arrayBuffer(): Promise<ArrayBuffer>
}
/**
* File representation extending Blob
*/
external class File(fileBits: Array<dynamic>, fileName: String, options: FilePropertyBag = definedExternally) : Blob {
/** File name */
val name: String
/** Last modified timestamp */
val lastModified: Double
}
/**
* Collection of files (from input[type=file])
*/
external interface FileList : ItemArrayLike<File>
/**
* Asynchronous file reading
*/
external interface FileReader : EventTarget {
/** Reader state */
val readyState: Short
/** Read result */
val result: dynamic
/** Read error */
val error: dynamic
/** Read as array buffer */
fun readAsArrayBuffer(blob: Blob)
/** Read as binary string */
fun readAsBinaryString(blob: Blob)
/** Read as data URL */
fun readAsDataURL(blob: Blob)
/** Read as text */
fun readAsText(blob: Blob, label: String = definedExternally)
/** Abort reading */
fun abort()
companion object {
const val EMPTY: Short = 0
const val LOADING: Short = 1
const val DONE: Short = 2
}
}
external interface BlobPropertyBag {
var type: String?
var endings: String?
}
external interface FilePropertyBag : BlobPropertyBag {
var lastModified: Double?
}Comprehensive SVG API for vector graphics manipulation and creation.
/**
* Base SVG element interface
*/
external interface SVGElement : Element, ElementCSSInlineStyle, GlobalEventHandlers, SVGElementInstance {
/** Element dataset */
val dataset: DOMStringMap
/** Owner SVG element */
val ownerSVGElement: SVGSVGElement?
/** Viewport element */
val viewportElement: SVGElement?
}
/**
* Root SVG element
*/
external interface SVGSVGElement : SVGGraphicsElement, SVGFitToViewBox, SVGZoomAndPan, WindowEventHandlers {
/** SVG x coordinate */
val x: SVGAnimatedLength
/** SVG y coordinate */
val y: SVGAnimatedLength
/** SVG width */
val width: SVGAnimatedLength
/** SVG height */
val height: SVGAnimatedLength
/** Content script type */
var contentScriptType: String
/** Content style type */
var contentStyleType: String
/** Current scale */
var currentScale: Float
/** Current translate */
val currentTranslate: SVGPoint
/** Create SVG number */
fun createSVGNumber(): SVGNumber
/** Create SVG length */
fun createSVGLength(): SVGLength
/** Create SVG angle */
fun createSVGAngle(): SVGAngle
/** Create SVG point */
fun createSVGPoint(): SVGPoint
/** Create SVG matrix */
fun createSVGMatrix(): SVGMatrix
/** Create SVG rectangle */
fun createSVGRect(): SVGRect
/** Create SVG transform */
fun createSVGTransform(): SVGTransform
/** Get element by ID */
fun getElementById(elementId: String): Element
}
/**
* SVG graphics element base
*/
external interface SVGGraphicsElement : SVGElement, SVGTests {
/** Element transform */
val transform: SVGAnimatedTransformList
/** Nearest viewport element */
val nearestViewportElement: SVGElement?
/** Farthest viewport element */
val farthestViewportElement: SVGElement?
/** Get bounding box */
fun getBBox(): SVGRect
/** Get transformation matrix */
fun getCTM(): SVGMatrix?
/** Get screen transformation matrix */
fun getScreenCTM(): SVGMatrix?
}
/**
* SVG shape elements
*/
external interface SVGPathElement : SVGGeometryElement {
/** Path data */
val d: SVGAnimatedString
}
external interface SVGRectElement : SVGGeometryElement {
/** Rectangle x */
val x: SVGAnimatedLength
/** Rectangle y */
val y: SVGAnimatedLength
/** Rectangle width */
val width: SVGAnimatedLength
/** Rectangle height */
val height: SVGAnimatedLength
/** Rectangle rx */
val rx: SVGAnimatedLength
/** Rectangle ry */
val ry: SVGAnimatedLength
}
external interface SVGCircleElement : SVGGeometryElement {
/** Circle center x */
val cx: SVGAnimatedLength
/** Circle center y */
val cy: SVGAnimatedLength
/** Circle radius */
val r: SVGAnimatedLength
}
/**
* SVG data types
*/
external interface SVGAnimatedLength {
val baseVal: SVGLength
val animVal: SVGLength
}
external interface SVGLength {
val unitType: Short
var value: Float
var valueInSpecifiedUnits: Float
var valueAsString: String
}
external interface SVGPoint {
var x: Float
var y: Float
}WebGL API for 3D graphics rendering and GPU acceleration.
/**
* WebGL rendering context
*/
external interface WebGLRenderingContext : WebGLRenderingContextBase, RenderingContext {
/** Canvas element */
val canvas: dynamic
/** Drawing buffer width */
val drawingBufferWidth: Int
/** Drawing buffer height */
val drawingBufferHeight: Int
/** Get context attributes */
fun getContextAttributes(): WebGLContextAttributes?
/** Check if context is lost */
fun isContextLost(): Boolean
}
/**
* WebGL context base functionality
*/
external interface WebGLRenderingContextBase {
// Buffer operations
/** Create buffer */
fun createBuffer(): WebGLBuffer?
/** Delete buffer */
fun deleteBuffer(buffer: WebGLBuffer?)
/** Bind buffer */
fun bindBuffer(target: Int, buffer: WebGLBuffer?)
/** Buffer data */
fun bufferData(target: Int, data: dynamic, usage: Int)
// Shader operations
/** Create shader */
fun createShader(type: Int): WebGLShader?
/** Delete shader */
fun deleteShader(shader: WebGLShader?)
/** Shader source */
fun shaderSource(shader: WebGLShader, source: String)
/** Compile shader */
fun compileShader(shader: WebGLShader)
// Program operations
/** Create program */
fun createProgram(): WebGLProgram?
/** Delete program */
fun deleteProgram(program: WebGLProgram?)
/** Attach shader */
fun attachShader(program: WebGLProgram, shader: WebGLShader)
/** Link program */
fun linkProgram(program: WebGLProgram)
/** Use program */
fun useProgram(program: WebGLProgram?)
// Rendering
/** Clear color */
fun clearColor(red: Float, green: Float, blue: Float, alpha: Float)
/** Clear */
fun clear(mask: Int)
/** Draw arrays */
fun drawArrays(mode: Int, first: Int, count: Int)
/** Draw elements */
fun drawElements(mode: Int, count: Int, type: Int, offset: Int)
/** Viewport */
fun viewport(x: Int, y: Int, width: Int, height: Int)
}
/**
* WebGL objects
*/
external interface WebGLObject
external interface WebGLBuffer : WebGLObject
external interface WebGLShader : WebGLObject
external interface WebGLProgram : WebGLObject
external interface WebGLTexture : WebGLObject
/**
* Typed arrays for WebGL
*/
external class Float32Array : ArrayBufferView {
constructor(length: Int)
constructor(array: Array<Float>)
constructor(buffer: ArrayBuffer)
val length: Int
operator fun get(index: Int): Float
operator fun set(index: Int, value: Float)
}
external class Uint8Array : ArrayBufferView {
constructor(length: Int)
constructor(array: Array<Byte>)
constructor(buffer: ArrayBuffer)
val length: Int
operator fun get(index: Int): Byte
operator fun set(index: Int, value: Byte)
}
external interface ArrayBufferView : BufferDataSource {
val buffer: ArrayBuffer
val byteOffset: Int
val byteLength: Int
}
external class ArrayBuffer(length: Int) : BufferDataSource {
val byteLength: Int
fun slice(begin: Int, end: Int = definedExternally): ArrayBuffer
}Service worker API for offline capabilities, background sync, and push notifications.
/**
* Service worker registration
*/
external interface ServiceWorkerRegistration : EventTarget {
/** Installing service worker */
val installing: ServiceWorker?
/** Waiting service worker */
val waiting: ServiceWorker?
/** Active service worker */
val active: ServiceWorker?
/** Registration scope */
val scope: String
/** Update via cache */
val updateViaCache: ServiceWorkerUpdateViaCache
/** Update registration */
fun update(): Promise<Unit>
/** Unregister service worker */
fun unregister(): Promise<Boolean>
/** Show notification */
fun showNotification(title: String, options: NotificationOptions = definedExternally): Promise<Unit>
/** Get notifications */
fun getNotifications(filter: GetNotificationOptions = definedExternally): Promise<Array<Notification>>
}
/**
* Service worker instance
*/
external interface ServiceWorker : EventTarget, AbstractWorker {
/** Script URL */
val scriptURL: String
/** Worker state */
val state: ServiceWorkerState
/** Post message to worker */
fun postMessage(message: dynamic, transfer: Array<dynamic> = definedExternally)
}
/**
* Service worker container
*/
external interface ServiceWorkerContainer : EventTarget {
/** Controller service worker */
val controller: ServiceWorker?
/** Ready promise */
val ready: Promise<ServiceWorkerRegistration>
/** Register service worker */
fun register(scriptURL: String, options: RegistrationOptions = definedExternally): Promise<ServiceWorkerRegistration>
/** Get registration */
fun getRegistration(clientURL: String = definedExternally): Promise<ServiceWorkerRegistration?>
/** Get all registrations */
fun getRegistrations(): Promise<Array<ServiceWorkerRegistration>>
/** Start messages */
fun startMessages()
}
/**
* Cache API for offline storage
*/
external interface Cache {
/** Match request in cache */
fun match(request: dynamic, options: CacheQueryOptions = definedExternally): Promise<Response?>
/** Match all requests in cache */
fun matchAll(request: dynamic = definedExternally, options: CacheQueryOptions = definedExternally): Promise<Array<Response>>
/** Add request to cache */
fun add(request: dynamic): Promise<Unit>
/** Add multiple requests to cache */
fun addAll(requests: Array<dynamic>): Promise<Unit>
/** Put request/response in cache */
fun put(request: dynamic, response: Response): Promise<Unit>
/** Delete from cache */
fun delete(request: dynamic, options: CacheQueryOptions = definedExternally): Promise<Boolean>
/** Get cache keys */
fun keys(request: dynamic = definedExternally, options: CacheQueryOptions = definedExternally): Promise<Array<Request>>
}
/**
* Cache storage management
*/
external interface CacheStorage {
/** Match in any cache */
fun match(request: dynamic, options: MultiCacheQueryOptions = definedExternally): Promise<Response?>
/** Check if cache exists */
fun has(cacheName: String): Promise<Boolean>
/** Open cache */
fun open(cacheName: String): Promise<Cache>
/** Delete cache */
fun delete(cacheName: String): Promise<Boolean>
/** Get cache names */
fun keys(): Promise<Array<String>>
}
enum class ServiceWorkerState { INSTALLING, INSTALLED, ACTIVATING, ACTIVATED, REDUNDANT }
enum class ServiceWorkerUpdateViaCache { IMPORTS, ALL, NONE }Web notification API for desktop notifications and push messaging.
/**
* Web notification
*/
external class Notification(title: String, options: NotificationOptions = definedExternally) : EventTarget {
/** Notification permission */
val permission: NotificationPermission
/** Maximum actions supported */
val maxActions: Int
/** Notification title */
val title: String
/** Notification direction */
val dir: NotificationDirection
/** Notification language */
val lang: String
/** Notification body */
val body: String
/** Notification tag */
val tag: String
/** Notification icon */
val icon: String
/** Notification badge */
val badge: String
/** Notification image */
val image: String
/** Notification data */
val data: Any?
/** Notification actions */
val actions: Array<NotificationAction>
/** Silent notification */
val silent: Boolean
/** Notification timestamp */
val timestamp: Double
/** Close notification */
fun close()
companion object {
/** Request permission */
fun requestPermission(deprecatedCallback: ((NotificationPermission) -> Unit)? = definedExternally): Promise<NotificationPermission>
}
}
external interface NotificationOptions {
var dir: NotificationDirection?
var lang: String?
var body: String?
var tag: String?
var image: String?
var icon: String?
var badge: String?
var sound: String?
var vibrate: Array<Int>?
var timestamp: Double?
var renotify: Boolean?
var silent: Boolean?
var requireInteraction: Boolean?
var data: Any?
var actions: Array<NotificationAction>?
}
external interface NotificationAction {
var action: String
var title: String
var icon: String?
}
enum class NotificationPermission { DEFAULT, DENIED, GRANTED }
enum class NotificationDirection { AUTO, LTR, RTL }Usage Examples:
import kotlinx.browser.window
import org.w3c.dom.mediacapture.*
import org.w3c.files.*
import org.w3c.dom.svg.*
import org.khronos.webgl.*
import org.w3c.workers.*
// Media capture
suspend fun startVideoStream(): MediaStream {
val constraints = object : MediaStreamConstraints {
override var video = object {
val width = 1280
val height = 720
}
override var audio = true
}
return window.navigator.mediaDevices.getUserMedia(constraints).await()
}
// File handling
fun handleFileUpload(files: FileList) {
for (i in 0 until files.length) {
val file = files.item(i) ?: continue
val reader = FileReader()
reader.onload = { event ->
val result = (event.target as FileReader).result
console.log("File ${file.name} loaded: ${file.size} bytes")
}
reader.readAsDataURL(file)
}
}
// SVG manipulation
fun createSVGChart(data: Array<Double>): SVGSVGElement {
val svg = document.createElementNS("http://www.w3.org/2000/svg", "svg") as SVGSVGElement
svg.setAttribute("width", "400")
svg.setAttribute("height", "300")
data.forEachIndexed { index, value ->
val rect = document.createElementNS("http://www.w3.org/2000/svg", "rect") as SVGRectElement
rect.setAttribute("x", (index * 40).toString())
rect.setAttribute("y", (300 - value * 10).toString())
rect.setAttribute("width", "30")
rect.setAttribute("height", (value * 10).toString())
rect.setAttribute("fill", "blue")
svg.appendChild(rect)
}
return svg
}
// WebGL rendering
fun initWebGL(canvas: HTMLCanvasElement) {
val gl = canvas.getContext("webgl") as? WebGLRenderingContext
?: throw Exception("WebGL not supported")
gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f)
gl.clear(WebGLRenderingContext.COLOR_BUFFER_BIT)
// Create shader
val vertexShader = gl.createShader(WebGLRenderingContext.VERTEX_SHADER)!!
gl.shaderSource(vertexShader, """
attribute vec4 position;
void main() {
gl_Position = position;
}
""".trimIndent())
gl.compileShader(vertexShader)
}
// Service worker registration
suspend fun registerServiceWorker() {
if ("serviceWorker" in window.navigator) {
try {
val registration = window.navigator.serviceWorker.register("/sw.js").await()
console.log("Service worker registered:", registration.scope)
} catch (error) {
console.error("Service worker registration failed:", error)
}
}
}
// Web notifications
suspend fun showNotification(title: String, message: String) {
val permission = Notification.requestPermission().await()
if (permission == NotificationPermission.GRANTED) {
val notification = Notification(title, object : NotificationOptions {
override var body = message
override var icon = "/icon.png"
override var requireInteraction = true
})
notification.onclick = {
window.focus()
notification.close()
}
}
}Install with Tessl CLI
npx tessl i tessl/maven-org-jetbrains-kotlin--kotlin-dom-api-compat