0
# Additional W3C APIs
1
2
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.
3
4
## Capabilities
5
6
### Media Capture and Streaming
7
8
Media capture API for accessing camera, microphone, and screen sharing capabilities.
9
10
```kotlin { .api }
11
/**
12
* Media stream for audio/video content
13
*/
14
external interface MediaStream : EventTarget, MediaProvider {
15
/** Whether the stream is active */
16
val active: Boolean
17
/** Unique stream identifier */
18
val id: String
19
20
/** Get audio tracks */
21
fun getAudioTracks(): Array<MediaStreamTrack>
22
/** Get video tracks */
23
fun getVideoTracks(): Array<MediaStreamTrack>
24
/** Get all tracks */
25
fun getTracks(): Array<MediaStreamTrack>
26
/** Get track by ID */
27
fun getTrackById(trackId: String): MediaStreamTrack?
28
/** Add track to stream */
29
fun addTrack(track: MediaStreamTrack)
30
/** Remove track from stream */
31
fun removeTrack(track: MediaStreamTrack)
32
/** Clone the stream */
33
fun clone(): MediaStream
34
}
35
36
/**
37
* Individual media track (audio or video)
38
*/
39
external interface MediaStreamTrack : EventTarget {
40
/** Track kind (audio/video) */
41
val kind: String
42
/** Track identifier */
43
val id: String
44
/** Track label */
45
val label: String
46
/** Whether track is enabled */
47
var enabled: Boolean
48
/** Whether track is muted */
49
val muted: Boolean
50
/** Track ready state */
51
val readyState: MediaStreamTrackState
52
53
/** Clone the track */
54
fun clone(): MediaStreamTrack
55
/** Stop the track */
56
fun stop()
57
/** Get track capabilities */
58
fun getCapabilities(): MediaTrackCapabilities
59
/** Get current constraints */
60
fun getConstraints(): MediaTrackConstraints
61
/** Get current settings */
62
fun getSettings(): MediaTrackSettings
63
/** Apply new constraints */
64
fun applyConstraints(constraints: MediaTrackConstraints = definedExternally): Promise<Unit>
65
}
66
67
/**
68
* Media devices access
69
*/
70
external interface MediaDevices : EventTarget {
71
/** Get user media (camera/microphone) */
72
fun getUserMedia(constraints: MediaStreamConstraints = definedExternally): Promise<MediaStream>
73
/** Get display media (screen sharing) */
74
fun getDisplayMedia(constraints: MediaStreamConstraints = definedExternally): Promise<MediaStream>
75
/** Enumerate available devices */
76
fun enumerateDevices(): Promise<Array<MediaDeviceInfo>>
77
/** Get supported constraints */
78
fun getSupportedConstraints(): MediaTrackSupportedConstraints
79
}
80
81
/**
82
* Media device information
83
*/
84
external interface MediaDeviceInfo {
85
/** Device identifier */
86
val deviceId: String
87
/** Device kind */
88
val kind: MediaDeviceKind
89
/** Device label */
90
val label: String
91
/** Device group identifier */
92
val groupId: String
93
}
94
95
enum class MediaStreamTrackState { LIVE, ENDED }
96
enum class MediaDeviceKind { AUDIOINPUT, AUDIOOUTPUT, VIDEOINPUT }
97
```
98
99
### File API
100
101
File handling and blob manipulation for file uploads and processing.
102
103
```kotlin { .api }
104
/**
105
* Binary data representation
106
*/
107
external class Blob(blobParts: Array<dynamic> = definedExternally, options: BlobPropertyBag = definedExternally) : MediaProvider, ImageBitmapSource {
108
/** Blob size in bytes */
109
val size: Double
110
/** Blob MIME type */
111
val type: String
112
113
/** Create blob slice */
114
fun slice(start: Int = definedExternally, end: Int = definedExternally, contentType: String = definedExternally): Blob
115
/** Get blob as stream */
116
fun stream(): ReadableStream<Uint8Array>
117
/** Get blob as text */
118
fun text(): Promise<String>
119
/** Get blob as array buffer */
120
fun arrayBuffer(): Promise<ArrayBuffer>
121
}
122
123
/**
124
* File representation extending Blob
125
*/
126
external class File(fileBits: Array<dynamic>, fileName: String, options: FilePropertyBag = definedExternally) : Blob {
127
/** File name */
128
val name: String
129
/** Last modified timestamp */
130
val lastModified: Double
131
}
132
133
/**
134
* Collection of files (from input[type=file])
135
*/
136
external interface FileList : ItemArrayLike<File>
137
138
/**
139
* Asynchronous file reading
140
*/
141
external interface FileReader : EventTarget {
142
/** Reader state */
143
val readyState: Short
144
/** Read result */
145
val result: dynamic
146
/** Read error */
147
val error: dynamic
148
149
/** Read as array buffer */
150
fun readAsArrayBuffer(blob: Blob)
151
/** Read as binary string */
152
fun readAsBinaryString(blob: Blob)
153
/** Read as data URL */
154
fun readAsDataURL(blob: Blob)
155
/** Read as text */
156
fun readAsText(blob: Blob, label: String = definedExternally)
157
/** Abort reading */
158
fun abort()
159
160
companion object {
161
const val EMPTY: Short = 0
162
const val LOADING: Short = 1
163
const val DONE: Short = 2
164
}
165
}
166
167
external interface BlobPropertyBag {
168
var type: String?
169
var endings: String?
170
}
171
172
external interface FilePropertyBag : BlobPropertyBag {
173
var lastModified: Double?
174
}
175
```
176
177
### SVG Graphics
178
179
Comprehensive SVG API for vector graphics manipulation and creation.
180
181
```kotlin { .api }
182
/**
183
* Base SVG element interface
184
*/
185
external interface SVGElement : Element, ElementCSSInlineStyle, GlobalEventHandlers, SVGElementInstance {
186
/** Element dataset */
187
val dataset: DOMStringMap
188
/** Owner SVG element */
189
val ownerSVGElement: SVGSVGElement?
190
/** Viewport element */
191
val viewportElement: SVGElement?
192
}
193
194
/**
195
* Root SVG element
196
*/
197
external interface SVGSVGElement : SVGGraphicsElement, SVGFitToViewBox, SVGZoomAndPan, WindowEventHandlers {
198
/** SVG x coordinate */
199
val x: SVGAnimatedLength
200
/** SVG y coordinate */
201
val y: SVGAnimatedLength
202
/** SVG width */
203
val width: SVGAnimatedLength
204
/** SVG height */
205
val height: SVGAnimatedLength
206
/** Content script type */
207
var contentScriptType: String
208
/** Content style type */
209
var contentStyleType: String
210
/** Current scale */
211
var currentScale: Float
212
/** Current translate */
213
val currentTranslate: SVGPoint
214
215
/** Create SVG number */
216
fun createSVGNumber(): SVGNumber
217
/** Create SVG length */
218
fun createSVGLength(): SVGLength
219
/** Create SVG angle */
220
fun createSVGAngle(): SVGAngle
221
/** Create SVG point */
222
fun createSVGPoint(): SVGPoint
223
/** Create SVG matrix */
224
fun createSVGMatrix(): SVGMatrix
225
/** Create SVG rectangle */
226
fun createSVGRect(): SVGRect
227
/** Create SVG transform */
228
fun createSVGTransform(): SVGTransform
229
/** Get element by ID */
230
fun getElementById(elementId: String): Element
231
}
232
233
/**
234
* SVG graphics element base
235
*/
236
external interface SVGGraphicsElement : SVGElement, SVGTests {
237
/** Element transform */
238
val transform: SVGAnimatedTransformList
239
/** Nearest viewport element */
240
val nearestViewportElement: SVGElement?
241
/** Farthest viewport element */
242
val farthestViewportElement: SVGElement?
243
244
/** Get bounding box */
245
fun getBBox(): SVGRect
246
/** Get transformation matrix */
247
fun getCTM(): SVGMatrix?
248
/** Get screen transformation matrix */
249
fun getScreenCTM(): SVGMatrix?
250
}
251
252
/**
253
* SVG shape elements
254
*/
255
external interface SVGPathElement : SVGGeometryElement {
256
/** Path data */
257
val d: SVGAnimatedString
258
}
259
260
external interface SVGRectElement : SVGGeometryElement {
261
/** Rectangle x */
262
val x: SVGAnimatedLength
263
/** Rectangle y */
264
val y: SVGAnimatedLength
265
/** Rectangle width */
266
val width: SVGAnimatedLength
267
/** Rectangle height */
268
val height: SVGAnimatedLength
269
/** Rectangle rx */
270
val rx: SVGAnimatedLength
271
/** Rectangle ry */
272
val ry: SVGAnimatedLength
273
}
274
275
external interface SVGCircleElement : SVGGeometryElement {
276
/** Circle center x */
277
val cx: SVGAnimatedLength
278
/** Circle center y */
279
val cy: SVGAnimatedLength
280
/** Circle radius */
281
val r: SVGAnimatedLength
282
}
283
284
/**
285
* SVG data types
286
*/
287
external interface SVGAnimatedLength {
288
val baseVal: SVGLength
289
val animVal: SVGLength
290
}
291
292
external interface SVGLength {
293
val unitType: Short
294
var value: Float
295
var valueInSpecifiedUnits: Float
296
var valueAsString: String
297
}
298
299
external interface SVGPoint {
300
var x: Float
301
var y: Float
302
}
303
```
304
305
### WebGL Graphics
306
307
WebGL API for 3D graphics rendering and GPU acceleration.
308
309
```kotlin { .api }
310
/**
311
* WebGL rendering context
312
*/
313
external interface WebGLRenderingContext : WebGLRenderingContextBase, RenderingContext {
314
/** Canvas element */
315
val canvas: dynamic
316
/** Drawing buffer width */
317
val drawingBufferWidth: Int
318
/** Drawing buffer height */
319
val drawingBufferHeight: Int
320
321
/** Get context attributes */
322
fun getContextAttributes(): WebGLContextAttributes?
323
/** Check if context is lost */
324
fun isContextLost(): Boolean
325
}
326
327
/**
328
* WebGL context base functionality
329
*/
330
external interface WebGLRenderingContextBase {
331
// Buffer operations
332
/** Create buffer */
333
fun createBuffer(): WebGLBuffer?
334
/** Delete buffer */
335
fun deleteBuffer(buffer: WebGLBuffer?)
336
/** Bind buffer */
337
fun bindBuffer(target: Int, buffer: WebGLBuffer?)
338
/** Buffer data */
339
fun bufferData(target: Int, data: dynamic, usage: Int)
340
341
// Shader operations
342
/** Create shader */
343
fun createShader(type: Int): WebGLShader?
344
/** Delete shader */
345
fun deleteShader(shader: WebGLShader?)
346
/** Shader source */
347
fun shaderSource(shader: WebGLShader, source: String)
348
/** Compile shader */
349
fun compileShader(shader: WebGLShader)
350
351
// Program operations
352
/** Create program */
353
fun createProgram(): WebGLProgram?
354
/** Delete program */
355
fun deleteProgram(program: WebGLProgram?)
356
/** Attach shader */
357
fun attachShader(program: WebGLProgram, shader: WebGLShader)
358
/** Link program */
359
fun linkProgram(program: WebGLProgram)
360
/** Use program */
361
fun useProgram(program: WebGLProgram?)
362
363
// Rendering
364
/** Clear color */
365
fun clearColor(red: Float, green: Float, blue: Float, alpha: Float)
366
/** Clear */
367
fun clear(mask: Int)
368
/** Draw arrays */
369
fun drawArrays(mode: Int, first: Int, count: Int)
370
/** Draw elements */
371
fun drawElements(mode: Int, count: Int, type: Int, offset: Int)
372
/** Viewport */
373
fun viewport(x: Int, y: Int, width: Int, height: Int)
374
}
375
376
/**
377
* WebGL objects
378
*/
379
external interface WebGLObject
380
external interface WebGLBuffer : WebGLObject
381
external interface WebGLShader : WebGLObject
382
external interface WebGLProgram : WebGLObject
383
external interface WebGLTexture : WebGLObject
384
385
/**
386
* Typed arrays for WebGL
387
*/
388
external class Float32Array : ArrayBufferView {
389
constructor(length: Int)
390
constructor(array: Array<Float>)
391
constructor(buffer: ArrayBuffer)
392
393
val length: Int
394
operator fun get(index: Int): Float
395
operator fun set(index: Int, value: Float)
396
}
397
398
external class Uint8Array : ArrayBufferView {
399
constructor(length: Int)
400
constructor(array: Array<Byte>)
401
constructor(buffer: ArrayBuffer)
402
403
val length: Int
404
operator fun get(index: Int): Byte
405
operator fun set(index: Int, value: Byte)
406
}
407
408
external interface ArrayBufferView : BufferDataSource {
409
val buffer: ArrayBuffer
410
val byteOffset: Int
411
val byteLength: Int
412
}
413
414
external class ArrayBuffer(length: Int) : BufferDataSource {
415
val byteLength: Int
416
fun slice(begin: Int, end: Int = definedExternally): ArrayBuffer
417
}
418
```
419
420
### Service Workers
421
422
Service worker API for offline capabilities, background sync, and push notifications.
423
424
```kotlin { .api }
425
/**
426
* Service worker registration
427
*/
428
external interface ServiceWorkerRegistration : EventTarget {
429
/** Installing service worker */
430
val installing: ServiceWorker?
431
/** Waiting service worker */
432
val waiting: ServiceWorker?
433
/** Active service worker */
434
val active: ServiceWorker?
435
/** Registration scope */
436
val scope: String
437
/** Update via cache */
438
val updateViaCache: ServiceWorkerUpdateViaCache
439
440
/** Update registration */
441
fun update(): Promise<Unit>
442
/** Unregister service worker */
443
fun unregister(): Promise<Boolean>
444
/** Show notification */
445
fun showNotification(title: String, options: NotificationOptions = definedExternally): Promise<Unit>
446
/** Get notifications */
447
fun getNotifications(filter: GetNotificationOptions = definedExternally): Promise<Array<Notification>>
448
}
449
450
/**
451
* Service worker instance
452
*/
453
external interface ServiceWorker : EventTarget, AbstractWorker {
454
/** Script URL */
455
val scriptURL: String
456
/** Worker state */
457
val state: ServiceWorkerState
458
459
/** Post message to worker */
460
fun postMessage(message: dynamic, transfer: Array<dynamic> = definedExternally)
461
}
462
463
/**
464
* Service worker container
465
*/
466
external interface ServiceWorkerContainer : EventTarget {
467
/** Controller service worker */
468
val controller: ServiceWorker?
469
/** Ready promise */
470
val ready: Promise<ServiceWorkerRegistration>
471
472
/** Register service worker */
473
fun register(scriptURL: String, options: RegistrationOptions = definedExternally): Promise<ServiceWorkerRegistration>
474
/** Get registration */
475
fun getRegistration(clientURL: String = definedExternally): Promise<ServiceWorkerRegistration?>
476
/** Get all registrations */
477
fun getRegistrations(): Promise<Array<ServiceWorkerRegistration>>
478
/** Start messages */
479
fun startMessages()
480
}
481
482
/**
483
* Cache API for offline storage
484
*/
485
external interface Cache {
486
/** Match request in cache */
487
fun match(request: dynamic, options: CacheQueryOptions = definedExternally): Promise<Response?>
488
/** Match all requests in cache */
489
fun matchAll(request: dynamic = definedExternally, options: CacheQueryOptions = definedExternally): Promise<Array<Response>>
490
/** Add request to cache */
491
fun add(request: dynamic): Promise<Unit>
492
/** Add multiple requests to cache */
493
fun addAll(requests: Array<dynamic>): Promise<Unit>
494
/** Put request/response in cache */
495
fun put(request: dynamic, response: Response): Promise<Unit>
496
/** Delete from cache */
497
fun delete(request: dynamic, options: CacheQueryOptions = definedExternally): Promise<Boolean>
498
/** Get cache keys */
499
fun keys(request: dynamic = definedExternally, options: CacheQueryOptions = definedExternally): Promise<Array<Request>>
500
}
501
502
/**
503
* Cache storage management
504
*/
505
external interface CacheStorage {
506
/** Match in any cache */
507
fun match(request: dynamic, options: MultiCacheQueryOptions = definedExternally): Promise<Response?>
508
/** Check if cache exists */
509
fun has(cacheName: String): Promise<Boolean>
510
/** Open cache */
511
fun open(cacheName: String): Promise<Cache>
512
/** Delete cache */
513
fun delete(cacheName: String): Promise<Boolean>
514
/** Get cache names */
515
fun keys(): Promise<Array<String>>
516
}
517
518
enum class ServiceWorkerState { INSTALLING, INSTALLED, ACTIVATING, ACTIVATED, REDUNDANT }
519
enum class ServiceWorkerUpdateViaCache { IMPORTS, ALL, NONE }
520
```
521
522
### Web Notifications
523
524
Web notification API for desktop notifications and push messaging.
525
526
```kotlin { .api }
527
/**
528
* Web notification
529
*/
530
external class Notification(title: String, options: NotificationOptions = definedExternally) : EventTarget {
531
/** Notification permission */
532
val permission: NotificationPermission
533
/** Maximum actions supported */
534
val maxActions: Int
535
/** Notification title */
536
val title: String
537
/** Notification direction */
538
val dir: NotificationDirection
539
/** Notification language */
540
val lang: String
541
/** Notification body */
542
val body: String
543
/** Notification tag */
544
val tag: String
545
/** Notification icon */
546
val icon: String
547
/** Notification badge */
548
val badge: String
549
/** Notification image */
550
val image: String
551
/** Notification data */
552
val data: Any?
553
/** Notification actions */
554
val actions: Array<NotificationAction>
555
/** Silent notification */
556
val silent: Boolean
557
/** Notification timestamp */
558
val timestamp: Double
559
560
/** Close notification */
561
fun close()
562
563
companion object {
564
/** Request permission */
565
fun requestPermission(deprecatedCallback: ((NotificationPermission) -> Unit)? = definedExternally): Promise<NotificationPermission>
566
}
567
}
568
569
external interface NotificationOptions {
570
var dir: NotificationDirection?
571
var lang: String?
572
var body: String?
573
var tag: String?
574
var image: String?
575
var icon: String?
576
var badge: String?
577
var sound: String?
578
var vibrate: Array<Int>?
579
var timestamp: Double?
580
var renotify: Boolean?
581
var silent: Boolean?
582
var requireInteraction: Boolean?
583
var data: Any?
584
var actions: Array<NotificationAction>?
585
}
586
587
external interface NotificationAction {
588
var action: String
589
var title: String
590
var icon: String?
591
}
592
593
enum class NotificationPermission { DEFAULT, DENIED, GRANTED }
594
enum class NotificationDirection { AUTO, LTR, RTL }
595
```
596
597
**Usage Examples:**
598
599
```kotlin
600
import kotlinx.browser.window
601
import org.w3c.dom.mediacapture.*
602
import org.w3c.files.*
603
import org.w3c.dom.svg.*
604
import org.khronos.webgl.*
605
import org.w3c.workers.*
606
607
// Media capture
608
suspend fun startVideoStream(): MediaStream {
609
val constraints = object : MediaStreamConstraints {
610
override var video = object {
611
val width = 1280
612
val height = 720
613
}
614
override var audio = true
615
}
616
617
return window.navigator.mediaDevices.getUserMedia(constraints).await()
618
}
619
620
// File handling
621
fun handleFileUpload(files: FileList) {
622
for (i in 0 until files.length) {
623
val file = files.item(i) ?: continue
624
625
val reader = FileReader()
626
reader.onload = { event ->
627
val result = (event.target as FileReader).result
628
console.log("File ${file.name} loaded: ${file.size} bytes")
629
}
630
reader.readAsDataURL(file)
631
}
632
}
633
634
// SVG manipulation
635
fun createSVGChart(data: Array<Double>): SVGSVGElement {
636
val svg = document.createElementNS("http://www.w3.org/2000/svg", "svg") as SVGSVGElement
637
svg.setAttribute("width", "400")
638
svg.setAttribute("height", "300")
639
640
data.forEachIndexed { index, value ->
641
val rect = document.createElementNS("http://www.w3.org/2000/svg", "rect") as SVGRectElement
642
rect.setAttribute("x", (index * 40).toString())
643
rect.setAttribute("y", (300 - value * 10).toString())
644
rect.setAttribute("width", "30")
645
rect.setAttribute("height", (value * 10).toString())
646
rect.setAttribute("fill", "blue")
647
svg.appendChild(rect)
648
}
649
650
return svg
651
}
652
653
// WebGL rendering
654
fun initWebGL(canvas: HTMLCanvasElement) {
655
val gl = canvas.getContext("webgl") as? WebGLRenderingContext
656
?: throw Exception("WebGL not supported")
657
658
gl.clearColor(0.0f, 0.0f, 0.0f, 1.0f)
659
gl.clear(WebGLRenderingContext.COLOR_BUFFER_BIT)
660
661
// Create shader
662
val vertexShader = gl.createShader(WebGLRenderingContext.VERTEX_SHADER)!!
663
gl.shaderSource(vertexShader, """
664
attribute vec4 position;
665
void main() {
666
gl_Position = position;
667
}
668
""".trimIndent())
669
gl.compileShader(vertexShader)
670
}
671
672
// Service worker registration
673
suspend fun registerServiceWorker() {
674
if ("serviceWorker" in window.navigator) {
675
try {
676
val registration = window.navigator.serviceWorker.register("/sw.js").await()
677
console.log("Service worker registered:", registration.scope)
678
} catch (error) {
679
console.error("Service worker registration failed:", error)
680
}
681
}
682
}
683
684
// Web notifications
685
suspend fun showNotification(title: String, message: String) {
686
val permission = Notification.requestPermission().await()
687
if (permission == NotificationPermission.GRANTED) {
688
val notification = Notification(title, object : NotificationOptions {
689
override var body = message
690
override var icon = "/icon.png"
691
override var requireInteraction = true
692
})
693
694
notification.onclick = {
695
window.focus()
696
notification.close()
697
}
698
}
699
}
700
```