@ac-kit/browser 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +95 -0
  2. package/README.md +325 -4
  3. package/dist/animation-frame/frame-scheduler.d.ts +91 -0
  4. package/dist/animation-frame/frame-scheduler.d.ts.map +1 -0
  5. package/dist/animation-frame/frame-scheduler.js +181 -0
  6. package/dist/animation-frame/frame-scheduler.js.map +1 -0
  7. package/dist/canvas/canvas-backing-size.d.ts +58 -0
  8. package/dist/canvas/canvas-backing-size.d.ts.map +1 -0
  9. package/dist/canvas/canvas-backing-size.js +141 -0
  10. package/dist/canvas/canvas-backing-size.js.map +1 -0
  11. package/dist/canvas/image-data-pixels.d.ts +61 -0
  12. package/dist/canvas/image-data-pixels.d.ts.map +1 -0
  13. package/dist/canvas/image-data-pixels.js +71 -0
  14. package/dist/canvas/image-data-pixels.js.map +1 -0
  15. package/dist/canvas/read-image-data.d.ts +120 -0
  16. package/dist/canvas/read-image-data.d.ts.map +1 -0
  17. package/dist/canvas/read-image-data.js +147 -0
  18. package/dist/canvas/read-image-data.js.map +1 -0
  19. package/dist/dom/index.d.ts +4 -0
  20. package/dist/dom/index.d.ts.map +1 -0
  21. package/dist/dom/index.js +4 -0
  22. package/dist/dom/index.js.map +1 -0
  23. package/dist/dom/media-query/watch-media-query.d.ts +26 -0
  24. package/dist/dom/media-query/watch-media-query.d.ts.map +1 -0
  25. package/dist/dom/media-query/watch-media-query.js +42 -0
  26. package/dist/dom/media-query/watch-media-query.js.map +1 -0
  27. package/dist/dom/resize-observer/observe-canvas-size.d.ts +54 -0
  28. package/dist/dom/resize-observer/observe-canvas-size.d.ts.map +1 -0
  29. package/dist/dom/resize-observer/observe-canvas-size.js +189 -0
  30. package/dist/dom/resize-observer/observe-canvas-size.js.map +1 -0
  31. package/dist/dom/web-animations/wait-for-transitions.d.ts +59 -0
  32. package/dist/dom/web-animations/wait-for-transitions.d.ts.map +1 -0
  33. package/dist/dom/web-animations/wait-for-transitions.js +40 -0
  34. package/dist/dom/web-animations/wait-for-transitions.js.map +1 -0
  35. package/dist/index.d.ts +6 -0
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +6 -0
  38. package/dist/index.js.map +1 -1
  39. package/dist/indexeddb/open-indexed-db.d.ts +1 -1
  40. package/dist/indexeddb/open-indexed-db.d.ts.map +1 -1
  41. package/dist/indexeddb/open-indexed-db.js +2 -1
  42. package/dist/indexeddb/open-indexed-db.js.map +1 -1
  43. package/dist/media-capture/microphone-access.d.ts +116 -0
  44. package/dist/media-capture/microphone-access.d.ts.map +1 -0
  45. package/dist/media-capture/microphone-access.js +222 -0
  46. package/dist/media-capture/microphone-access.js.map +1 -0
  47. package/dist/testing/fake-animation-frames.d.ts +31 -0
  48. package/dist/testing/fake-animation-frames.d.ts.map +1 -0
  49. package/dist/testing/fake-animation-frames.js +75 -0
  50. package/dist/testing/fake-animation-frames.js.map +1 -0
  51. package/dist/testing/fake-audio-context.d.ts +174 -0
  52. package/dist/testing/fake-audio-context.d.ts.map +1 -0
  53. package/dist/testing/fake-audio-context.js +314 -0
  54. package/dist/testing/fake-audio-context.js.map +1 -0
  55. package/dist/testing/fake-match-media.d.ts +19 -0
  56. package/dist/testing/fake-match-media.d.ts.map +1 -0
  57. package/dist/testing/fake-match-media.js +135 -0
  58. package/dist/testing/fake-match-media.js.map +1 -0
  59. package/dist/testing/fake-media-devices.d.ts +90 -0
  60. package/dist/testing/fake-media-devices.d.ts.map +1 -0
  61. package/dist/testing/fake-media-devices.js +147 -0
  62. package/dist/testing/fake-media-devices.js.map +1 -0
  63. package/dist/testing/fake-resize-observer.d.ts +58 -0
  64. package/dist/testing/fake-resize-observer.d.ts.map +1 -0
  65. package/dist/testing/fake-resize-observer.js +118 -0
  66. package/dist/testing/fake-resize-observer.js.map +1 -0
  67. package/dist/testing/fake-web-midi.d.ts +25 -0
  68. package/dist/testing/fake-web-midi.d.ts.map +1 -0
  69. package/dist/testing/fake-web-midi.js +52 -0
  70. package/dist/testing/fake-web-midi.js.map +1 -0
  71. package/dist/testing/index.d.ts +7 -0
  72. package/dist/testing/index.d.ts.map +1 -0
  73. package/dist/testing/index.js +7 -0
  74. package/dist/testing/index.js.map +1 -0
  75. package/dist/web-audio/audio-clock-mapping.d.ts +124 -0
  76. package/dist/web-audio/audio-clock-mapping.d.ts.map +1 -0
  77. package/dist/web-audio/audio-clock-mapping.js +245 -0
  78. package/dist/web-audio/audio-clock-mapping.js.map +1 -0
  79. package/package.json +23 -7
package/CHANGELOG.md CHANGED
@@ -1,5 +1,100 @@
1
1
  # @ac-kit/browser
2
2
 
3
+ ## 0.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 34e8cfa: `watchMediaQuery(window, query, { onChange?, signal? })` (from
8
+ `@ac-kit/browser/dom`) follows a media query such as `(prefers-reduced-motion:
9
+ reduce)`: its `matches` is the current value, `onChange` hears each change, and
10
+ disposing it, or aborting `signal`, stops the listening. It throws a
11
+ `TypeError` for a window without `matchMedia`. `./testing` gains
12
+ `FakeMatchMedia`, a `matchMedia` whose queries the test flips.
13
+ - 34e8cfa: Adds canvas sizing and frame scheduling. `canvasBackingSize(box, caps)` gives
14
+ the whole-pixel backing size of a canvas: the device-pixel size exactly when the
15
+ browser reports it and no cap applies, else the CSS size times the ratio,
16
+ rounded, and floored under `maxPixelRatio`, `maxPixels` or `maxSide` so the cap
17
+ holds; a worker takes the sizes the page sends. `observeCanvasSize` (from
18
+ `@ac-kit/browser/dom`) keeps a canvas at that size, follows ratio changes with
19
+ or without `devicePixelContentBoxSize`, assigns the canvas only when its size
20
+ differs, ignores a hidden canvas, and calls `onResize` after layout and before
21
+ paint. `FrameScheduler` renders on animation frames at most once each, on
22
+ `invalidate()` or every frame while `continuous`, with a capped frame delta,
23
+ `renderNow()` and `AbortSignal` or `Symbol.dispose` stop. `./testing` gains
24
+ `FakeAnimationFrames` and `FakeResizeObserver`.
25
+
26
+ ### Patch Changes
27
+
28
+ - 34e8cfa: An error message that quotes an argument of the wrong kind or value describes
29
+ it with `@ac-kit/core`'s `describeValue`, so building the message can no
30
+ longer throw on a symbol. The text changes: `-0` keeps its sign (`got -0`), a
31
+ string is JSON-quoted and an object is named by its kind. Affected:
32
+ `bigIntParse`'s radix, `decodeFloat64Base64`'s counts, `formatDuration`'s
33
+ value, `RateLimiter`'s `maxKeys`, cost and clock time, `TokenBucket`'s
34
+ capacity, refill rate and cost, `getBackoffDelay`'s attempt, delays and
35
+ factor, `retry`'s `maxAttempts`, `maxElapsedMs` and `delayMs`, `BitSet` and
36
+ `BitVector`'s size and members, the LRU caches', `TtlMap`'s and the bounded
37
+ collections' capacity, `TtlMap`'s time to live, `MultiSet`'s occurrence
38
+ count, `BloomFilter`, `CountMinSketch`, `CuckooFilter`, `HyperLogLog` and
39
+ `TopK`'s sizing options, `RingVector`, `SegmentedRingVector` and
40
+ `TypedVector`'s capacities and indexes, `openIndexedDb`'s version and
41
+ `readImageData`'s size.
42
+ - Updated dependencies [34e8cfa]
43
+ - Updated dependencies [34e8cfa]
44
+ - Updated dependencies [34e8cfa]
45
+ - Updated dependencies [34e8cfa]
46
+ - Updated dependencies [34e8cfa]
47
+ - Updated dependencies [34e8cfa]
48
+ - Updated dependencies [34e8cfa]
49
+ - Updated dependencies [34e8cfa]
50
+ - Updated dependencies [34e8cfa]
51
+ - Updated dependencies [34e8cfa]
52
+ - Updated dependencies [34e8cfa]
53
+ - Updated dependencies [34e8cfa]
54
+ - Updated dependencies [34e8cfa]
55
+ - Updated dependencies [34e8cfa]
56
+ - Updated dependencies [34e8cfa]
57
+ - Updated dependencies [34e8cfa]
58
+ - Updated dependencies [34e8cfa]
59
+ - Updated dependencies [34e8cfa]
60
+ - @ac-kit/async@0.8.0
61
+ - @ac-kit/core@0.12.0
62
+
63
+ ## 0.2.0
64
+
65
+ ### Minor Changes
66
+
67
+ - 065cf8d: - New `readImageData(createCanvas, source, { maxSize?, maxPixels?, maxSide?, smoothing?, contextSettings? })` returns the pixels of an image, a video's current frame, a canvas, an `ImageBitmap` or a `VideoFrame` as `ImageData`, drawn once with `drawImage` on the canvas `createCanvas(width, height)` returns, then read back whole; no global is read. `createCanvas` must return a fresh canvas (new, or resized by assigning its `width` and `height`).
68
+ - `maxSize`, a positive integer, scales a larger source down until its longer side is `maxSize`, the shorter one `round(maxSize / aspect)` (or `× aspect`) and at least 1; a source no larger is drawn at its own size, never scaled up. It bounds what is drawn and read, not what the browser decodes.
69
+ - The size drawn is held to `maxPixels` (a positive integer, default 16,777,216 = 4096 × 4096, the smallest canvas Safari on iOS allows) and `maxSide` (a positive integer, default 32,767, a conservative policy of this library, not a browser limit; raise it where wider canvases are known to work): beyond either, it throws `RangeError` before creating a canvas, rather than read back the blank canvas a browser gives when it cannot allocate one. Neither scales: that is `maxSize`'s job.
70
+ - `smoothing` is `false` (nearest neighbour) or an `ImageSmoothingQuality`, a fresh context's when absent. `contextSettings` go to `getContext("2d")` unchanged and so apply on a canvas's first context only; the pixels come back in the canvas's colour space, which the result's `colorSpace` names, 8-bit and not premultiplied (a translucent pixel's colour is quantized: the read is not lossless).
71
+ - New `ImageSourceUnavailableError`, thrown before any canvas is created for a source with nothing to draw: an image not `complete` (even with its size known) or broken, a video below `HAVE_CURRENT_DATA`, a closed `ImageBitmap` or `VideoFrame`, an empty canvas. Awaiting `image.decode()` remains the caller's precondition. `maxSize`, `maxPixels` or `maxSide` that is not a positive integer throws `RangeError`, a canvas giving no 2D context `UnsupportedError`, and a cross-origin image read without CORS the browser's `SecurityError`.
72
+ - New `imageDataPixels(imageData)` yields the pixels of 8-bit `ImageData` row by row from the top left, each a new `{ r8, g8, b8, a8 }` (`ImageDataPixel`, the shape of `@ac-kit/math-color`'s `Rgba8`), lazily; empty data yields nothing.
73
+ - New `forEachImageDataPixel(imageData, visit)` calls `visit(r8, g8, b8, a8, index)` for each pixel in the same order, allocating nothing, for loops over large images where one object per pixel costs.
74
+ - Both pixel readers accept a `Uint8ClampedArray` from any realm (an iframe's) and throw `TypeError` at the call, before any pixel, for any other data, `ImageData` with `pixelFormat: "rgba-float16"` included.
75
+ - New subpath `@ac-kit/browser/dom`, for what works on a document's elements, with `waitForTransitions(element, { subtree?, properties?, signal? })`: it resolves once the CSS transitions in a snapshot of `element.getAnimations({ subtree })`, taken at the call after pending style changes, have ended. None running resolves at once; a delayed transition counts even at zero duration; a cancelled one counts as ended; one started after the call is not waited for. `subtree` adds the descendants' transitions and those of pseudo-elements, and `properties` restricts it to transitions of the CSS properties named. An aborted `signal` rejects with its reason — already aborted, aborted during the call, or aborted while waiting, even if another listener stops the `abort` event; an `abort` event dispatched by hand on a signal not aborted is ignored.
76
+ - 065cf8d: - New `requestMicrophoneStream(navigator, { deviceId?, sampleRate?, signal? })` opens audio only, for analysis: `getUserMedia` with echo cancellation, noise suppression, auto gain control and voice isolation off, one channel and `sampleRate` as ideals, no video. It resolves with `{ stream, isDefaultInstead }`; the caller owns the stream and stops its tracks.
77
+ - A `deviceId` is asked for as `exact`; when the browser rejects it with an `OverconstrainedError` whose `constraint` is `"deviceId"`, empty or absent (the specification has the browser withhold it as `""` before the page may see device information, and `deviceId` is the only `exact` constraint asked), the same request without `deviceId` is made once more, and `isDefaultInstead: true` says the stream is the browser's choice. An `OverconstrainedError` naming another constraint, or any one without a `deviceId`, goes through unchanged.
78
+ - New `MicrophoneUnsupportedError` (no `navigator.mediaDevices.getUserMedia`), `MicrophoneDeniedError` (`NotAllowedError`, `SecurityError`, `PermissionDeniedError`), `MicrophoneNotFoundError` (`NotFoundError`, `DevicesNotFoundError`) and `MicrophoneInUseError` (`NotReadableError`, `AbortError`, `TrackStartError`), each with the browser's error as `cause`, the retry's included; any other rejection, a non-error value included, goes through unchanged.
79
+ - An aborted `signal` rejects with its reason: at the call without asking the browser, while waiting (a prompt left open), before the retry, which is then not made, and when the stream has been opened but not yet returned. A stream opened after the abort has its tracks stopped.
80
+ - New `queryMicrophonePermission(navigator, { signal? })` resolves with `"granted"`, `"denied"`, `"prompt"` (also when the browser has no Permissions API or cannot query `"microphone"`) or `"unsupported"` without `getUserMedia`; it never opens the microphone. An aborted `signal` rejects with its reason, before or during the query.
81
+ - New `listMicrophones(navigator, { signal? })` resolves with the `audioinput` devices `{ deviceId, label }` in the browser's order, leaving out those with an empty `deviceId` (withheld before the page was given a microphone); empty when `enumerateDevices` is missing or rejects. An aborted `signal` rejects with its reason, before or while listing, rather than resolving empty.
82
+ - New `MicrophoneNavigator`, the `navigator` members these three read, each optional: no global is read. New `MicrophoneQueryOptions`, `{ signal? }`.
83
+ - New `AudioClockMapping({ windowMs, jumpMs, steadyMs, readyTicks, biasMs? })` maps an audio clock onto the page's from ticks `observe(audioMs, pageMs)`: its `offsetMs` is the least `pageMs − audioMs` of the ticks of the last `windowMs` of page time, less `biasMs` (default 0), once `readyTicks` ticks have come since it last started (`undefined` before); `toPageMs` and `toAudioMs` convert with it and throw `Error` before it is ready.
84
+ - It starts again (`resetCount` + 1, not ready until `readyTicks` more ticks) on `reset()`, on an audio time below the previous tick's, on a tick whose offset is more than `jumpMs` below the window's least, and on `readyTicks` ticks in a row, all within the window, each more than `jumpMs` above the least of the window's ticks before it, whose offsets span at most `steadyMs` and fall by at most `steadyMs / 2`; it then keeps those ticks and is ready on them. When `readyTicks` ticks do not fit in the window, no step up is taken: the window takes the new offset as the older ticks leave it.
85
+ - A time that is not finite, or a `pageMs` below the previous tick's, throws `RangeError` and leaves the mapping as it was; so does an option out of range (`windowMs` positive, `jumpMs` and `steadyMs` non-negative and finite, `readyTicks` a positive integer, `biasMs` finite).
86
+ - O(n) time per tick and per conversion, n the ticks in the window, and O(n) memory, the most ticks the window held, in a ring buffer growing by doubling: a tick allocates nothing otherwise. It reads no clock and no global.
87
+ - New subpath `@ac-kit/browser/testing`, stand-ins for tests under Node that import no test runner and record their calls as data: `FakeMediaDevices` (`getUserMedia` answering outcomes in turn — `"ok"`, a `DOMException` name, or `{ thrown }` — with `requests`, `tracks`, `liveTracks`, `holdNext`, `enumerateDevices` over `devices`, `changeDevices` dispatching `devicechange`), `FakeMediaStream`, `FakeMediaStreamTrack` (settings, `stop`, `end`, `mute`, `unmute`, `listenerCount`); `FakeAudioEnvironment` (`createContext`, `createWorkletNode`, refused rates, held `addModule` and `resume`), `FakeAudioContext`, `FakeAudioWorkletNode`, `FakeMessagePort` (records what the page posts, then hands it to `onPostMessage`), `FakeMediaStreamSource`, `FakeAudioNode`, `FakeGainNode`, `FakeBufferSource`, `FakeAudioBuffer`; `FakeMidiAccess` and `FakeMidiInput`.
88
+
89
+ ### Patch Changes
90
+
91
+ - Updated dependencies [065cf8d]
92
+ - Updated dependencies [065cf8d]
93
+ - Updated dependencies [065cf8d]
94
+ - Updated dependencies [065cf8d]
95
+ - @ac-kit/async@0.7.0
96
+ - @ac-kit/core@0.11.0
97
+
3
98
  ## 0.1.1
4
99
 
5
100
  ### Patch Changes
package/README.md CHANGED
@@ -3,12 +3,19 @@
3
3
  Browser extensions and zero-dependency wrappers over browser APIs, the
4
4
  browser's counterpart of `@ac-kit/node`: IndexedDB as promises, with versioned
5
5
  upgrades; Web MIDI, with access asked for and the input port a person chose
6
- followed by its name across reloads and hot-plugs; and requests over
7
- `XMLHttpRequest` that report their upload progress, which `fetch` cannot.
6
+ followed by its name across reloads and hot-plugs; the microphone opened for
7
+ analysis, its permission and its devices; an audio clock mapped onto the
8
+ page's; requests over
9
+ `XMLHttpRequest` that report their upload progress, which `fetch` cannot; an
10
+ image's pixels read through a canvas, scaled down; a canvas's backing store
11
+ kept at its displayed size in device pixels; rendering on animation frames at
12
+ most once each; and the wait for an element's CSS transitions to end.
8
13
 
9
14
  Every function takes the browser object it works through — `indexedDB`,
10
- `navigator`, a `MIDIAccess`, `XMLHttpRequest` — rather than reading a global,
11
- so it also runs in tests against a stand-in such as `fake-indexeddb`.
15
+ `navigator`, a `MIDIAccess`, `XMLHttpRequest`, a canvas factory, an element —
16
+ rather than reading a global, so it also runs in tests against a stand-in such
17
+ as `fake-indexeddb` or those of `@ac-kit/browser/testing`. What works on a document's elements is imported from
18
+ `@ac-kit/browser/dom`; everything else, workers included, from the root.
12
19
 
13
20
  ## IndexedDB
14
21
 
@@ -133,6 +140,95 @@ if ((await queryWebMidiPermission(navigator)) !== "unsupported") {
133
140
  - `isSameMidiPort` — whether two port identities (name and manufacturer) are
134
141
  the same device; a port's id changes between sessions, its identity does not.
135
142
 
143
+ ## Microphone
144
+
145
+ ```ts
146
+ import {
147
+ listMicrophones,
148
+ MicrophoneDeniedError,
149
+ queryMicrophonePermission,
150
+ requestMicrophoneStream,
151
+ } from "@ac-kit/browser";
152
+
153
+ if ((await queryMicrophonePermission(navigator)) !== "unsupported") {
154
+ try {
155
+ const { stream, isDefaultInstead } = await requestMicrophoneStream(
156
+ navigator,
157
+ { deviceId: chosen?.deviceId, sampleRate: 48_000, signal },
158
+ );
159
+ if (isDefaultInstead) showDefaultMicrophoneNotice();
160
+ analyse(stream);
161
+ } catch (error) {
162
+ if (error instanceof MicrophoneDeniedError) showHowToAllow();
163
+ else throw error;
164
+ }
165
+ const devices = await listMicrophones(navigator);
166
+ }
167
+ ```
168
+
169
+ - `requestMicrophoneStream(navigator, { deviceId?, sampleRate?, signal? })` —
170
+ audio only, for analysis: echo cancellation, noise suppression, auto gain
171
+ and voice isolation off, one channel and `sampleRate` asked for as ideals. A
172
+ `deviceId` is insisted on (`exact`); when the browser cannot open it (an
173
+ `OverconstrainedError` on `deviceId`, or on a constraint it withholds, as
174
+ before the page was given a microphone), it asks once more without it, and
175
+ `isDefaultInstead: true` says the stream is the browser's choice. It may
176
+ prompt, so call it from a user gesture. The caller owns the stream: stop its
177
+ tracks to release the microphone. Fails with `MicrophoneUnsupportedError`
178
+ without audio capture (outside a secure context), `MicrophoneDeniedError`
179
+ when refused, `MicrophoneNotFoundError` without a microphone and
180
+ `MicrophoneInUseError` when another application holds it, each with the
181
+ browser's error as `cause`; any other error goes through unchanged.
182
+ Aborting `signal` rejects with its reason, until the call returns: a
183
+ microphone the browser opens afterwards is stopped at once.
184
+ - `queryMicrophonePermission(navigator, { signal? })` — `"granted"`,
185
+ `"prompt"` (also when the browser cannot say), `"denied"`, or
186
+ `"unsupported"` without audio capture; it never opens the microphone.
187
+ - `listMicrophones(navigator, { signal? })` — the audio inputs
188
+ `{ deviceId, label }` the browser lists, without those whose id it withholds
189
+ before the page was given a microphone; empty when it cannot list them.
190
+ Aborting `signal` rejects both with its reason.
191
+
192
+ ## Audio clock
193
+
194
+ ```ts
195
+ import { AudioClockMapping } from "@ac-kit/browser";
196
+
197
+ const mapping = new AudioClockMapping({
198
+ windowMs: 2000,
199
+ jumpMs: 50,
200
+ steadyMs: 5,
201
+ readyTicks: 5,
202
+ });
203
+ // The AudioWorklet posts the frame it is at every few render quanta.
204
+ node.port.onmessage = ({ data }) => {
205
+ mapping.observe((data.frame / context.sampleRate) * 1000, performance.now());
206
+ };
207
+ context.addEventListener("statechange", () => mapping.reset());
208
+ if (mapping.isReady) {
209
+ showNoteAt(mapping.toPageMs(noteAudioMs));
210
+ }
211
+ ```
212
+
213
+ - `AudioClockMapping` — the offset between an audio clock (the samples an
214
+ `AudioContext` or an `AudioWorklet` processed) and `performance.now()`, from
215
+ ticks the audio thread posts, each noted with the page time it arrived. A
216
+ tick only ever arrives late, so the offset is the least `page − audio` over
217
+ the last `windowMs` of ticks, less `biasMs`: the page's jank falls out, a
218
+ slow drift is followed. It starts again, and is not ready until
219
+ `readyTicks` more ticks, on `reset()` (a context suspended and resumed, a
220
+ worklet restarted), when the audio clock goes backwards, on a tick more
221
+ than `jumpMs` below the window's least `page − audio`, or on `readyTicks`
222
+ ticks in a row more than `jumpMs` above it whose offsets differ by at most `steadyMs` and do not keep
223
+ falling (a backlog draining after a freeze does). `toPageMs` and
224
+ `toAudioMs` convert either way once ready, and throw before; `resetCount`
225
+ counts the restarts. A tick arriving before the previous one, or a time not
226
+ finite, throws `RangeError`. The ticks of a step up must all lie in the
227
+ window: when `readyTicks` of them do not fit, the window takes the new
228
+ offset on its own once the older ticks leave it. It reads no clock: it runs
229
+ in a worker or under Node as well. O(n) per tick and per conversion, n the
230
+ ticks in the window, held in a ring buffer: a tick allocates nothing.
231
+
136
232
  ## Upload progress
137
233
 
138
234
  ```ts
@@ -173,6 +269,226 @@ rules, as for `fetch`. `fetch` cannot report an upload's progress, and streams
173
269
  a request body only without its declared length; reach for `fetch` for
174
270
  everything else.
175
271
 
272
+ ## Image pixels
273
+
274
+ ```ts
275
+ import {
276
+ forEachImageDataPixel,
277
+ imageDataPixels,
278
+ readImageData,
279
+ } from "@ac-kit/browser";
280
+ import { rgb8ToRgb1 } from "@ac-kit/math-color";
281
+
282
+ const image = new Image();
283
+ image.src = url;
284
+ await image.decode();
285
+ const imageData = readImageData(
286
+ (width, height) => new OffscreenCanvas(width, height),
287
+ image,
288
+ { maxSize: 80, contextSettings: { colorSpace: "display-p3" } },
289
+ );
290
+ const colors = Array.from(imageDataPixels(imageData), rgb8ToRgb1);
291
+
292
+ let opaque = 0;
293
+ forEachImageDataPixel(imageData, (r8, g8, b8, a8) => {
294
+ if (a8 === 255) opaque++;
295
+ });
296
+ ```
297
+
298
+ - `readImageData(createCanvas, source, options?)` — the pixels of an image, a
299
+ video's frame, a canvas, an `ImageBitmap` or a `VideoFrame` as `ImageData`,
300
+ drawn once with `drawImage` on the canvas `createCanvas(width, height)`
301
+ returns, which must be fresh: a new `OffscreenCanvas` (in a page or a
302
+ worker) or `<canvas>`, or one resized by assigning its `width` and `height`,
303
+ which clears it and resets its drawing state.
304
+ - `maxSize` scales a larger source down until its longer side fits, keeping
305
+ its aspect ratio, and never scales one up. It bounds what is drawn and
306
+ read back, not what the browser decodes.
307
+ - `maxPixels` (default 16,777,216, 4096 × 4096: the smallest canvas Safari
308
+ on iOS allows) and `maxSide` (default 32,767, a conservative policy of
309
+ this library rather than a browser's limit: Chromium draws wider) bound
310
+ what is read: beyond them it throws `RangeError` rather than read back the
311
+ blank canvas a browser gives when it cannot allocate one. Pass a
312
+ `maxSize`, or raise them for browsers known to allow more.
313
+ - `smoothing` picks the resampling (`false` for nearest neighbour, or a
314
+ quality), a fresh context's (`"low"`) when absent.
315
+ - `contextSettings` go to `getContext("2d")` as they are, and so apply on a
316
+ canvas's first context only: `colorSpace: "display-p3"` keeps a
317
+ wide-gamut photo's colours. The pixels come back converted to the canvas's
318
+ colour space, named by the result's `colorSpace`.
319
+ - The source must be ready: await `image.decode()` first. It throws
320
+ `ImageSourceUnavailableError` for an image not complete or broken, a video
321
+ without its current frame, or a closed bitmap or frame — what it can tell
322
+ synchronously; a source the browser cannot draw for another reason reads
323
+ back transparent. It throws `UnsupportedError` when the canvas gives no 2D
324
+ context; a cross-origin image loaded without CORS fails with the browser's
325
+ `SecurityError`.
326
+ - `imageDataPixels(imageData)` — the pixels of 8-bit `ImageData`, row by row,
327
+ each a new `{ r8, g8, b8, a8 }`: `@ac-kit/math-color`'s `Rgba8`, its
328
+ conversions' input. Lazy; none for an empty one. One object per pixel costs:
329
+ on a full-HD image it is several times slower than
330
+ `forEachImageDataPixel`.
331
+ - `forEachImageDataPixel(imageData, visit)` — calls `visit(r8, g8, b8, a8,
332
+ index)` for each pixel, allocating nothing: the loop for a large image.
333
+
334
+ Both read `ImageData` from any realm (an iframe's), and throw a `TypeError` for
335
+ `ImageData` holding 16-bit floats (`pixelFormat: "rgba-float16"`).
336
+
337
+ The pixels are the browser's `drawImage` resampling: the same image and options
338
+ give the same pixels in the same browser. They are 8-bit and not premultiplied
339
+ by alpha, while a canvas stores its colours premultiplied: a translucent
340
+ pixel's colour comes back quantized, so the read is not lossless, even at full
341
+ size.
342
+
343
+ ## CSS transitions
344
+
345
+ ```ts
346
+ import { waitForTransitions } from "@ac-kit/browser/dom";
347
+
348
+ panel.classList.add("is-hidden");
349
+ await waitForTransitions(panel, { signal });
350
+ panel.replaceChildren(next);
351
+ panel.classList.remove("is-hidden");
352
+ ```
353
+
354
+ - `waitForTransitions(element, { subtree?, properties?, signal? })` — resolves
355
+ once the CSS transitions the element runs at the call have ended: a snapshot
356
+ of `element.getAnimations()`, taken after the style changes made before the
357
+ call. A transition that never starts — no change, no duration nor delay — is
358
+ not waited for (a delayed one is, even of zero duration), one cancelled
359
+ meanwhile counts as ended, and one started after the call is not waited for.
360
+ A `transitionend` listener would wait forever for the first two, and end
361
+ early on a descendant's. `subtree` waits for the descendants' transitions
362
+ too, their pseudo-elements' (`::before`, `::after`) included, as
363
+ `getAnimations({ subtree: true })` lists them; `properties` only for those
364
+ changing the CSS properties named. Aborting `signal`, even during the
365
+ call, rejects with its reason. A hidden page's rendering, and its
366
+ transitions with it, may be paused: bound the wait with
367
+ `AbortSignal.timeout()`, or `@ac-kit/async`'s `withTimeout`, where that
368
+ matters.
369
+
370
+ ## Canvas size
371
+
372
+ ```ts
373
+ import { FrameScheduler } from "@ac-kit/browser";
374
+ import { observeCanvasSize } from "@ac-kit/browser/dom";
375
+
376
+ const controller = new AbortController();
377
+ const scheduler = new FrameScheduler(window, () => draw(), {
378
+ signal: controller.signal,
379
+ });
380
+ observeCanvasSize(canvas, {
381
+ maxPixelRatio: 2,
382
+ // After layout, before paint: draw now rather than one stretched frame.
383
+ onResize: () => scheduler.renderNow(),
384
+ signal: controller.signal,
385
+ });
386
+ ```
387
+
388
+ - `canvasBackingSize(box, { maxPixelRatio?, maxPixels?, maxSide? })` — the
389
+ whole-pixel size `canvas.width` and `canvas.height` must hold for a content
390
+ box: the device-pixel size exactly when the browser gives it
391
+ (`devicePixelContentBoxSize`, not Safari) and no cap applies, else the CSS
392
+ size times the page's ratio, rounded; where a cap binds it is floored, so
393
+ rounding never passes a cap. Pure, so a worker drawing on an
394
+ `OffscreenCanvas` takes the sizes the page sends. It throws a `RangeError`
395
+ for a negative or non-finite size, or one too large for whole pixels.
396
+ - `observeCanvasSize(canvas, { onResize, resizeCanvas?, signal?, …caps })`
397
+ (from `/dom`) — keeps the backing store at the displayed size. It uses the
398
+ canvas's own window's `ResizeObserver`, on `device-pixel-content-box` where
399
+ supported (that also fires when the ratio changes, on another screen),
400
+ else on `content-box` plus a `resolution` media query. `onResize` is
401
+ called at the first layout and whenever the backing size changes, never
402
+ for a hidden (empty) canvas. The canvas is assigned only when its size
403
+ differs, since assigning resets it; `resizeCanvas: false` leaves it to a
404
+ worker. The canvas's CSS size must not depend on its `width` and `height`
405
+ attributes, or the backing size feeds back into the layout. Returns a
406
+ `Disposable`.
407
+
408
+ ## Frames
409
+
410
+ - `watchMediaQuery(window, query, { onChange?, signal? })` (from `/dom`) —
411
+ follows a media query such as `(prefers-reduced-motion: reduce)`: `matches`
412
+ is the current value, `onChange(matches)` hears each change, and disposing it
413
+ (or aborting `signal`) stops the listening. It throws a `TypeError` for a
414
+ window without `matchMedia`. `@ac-kit/browser/testing`'s `FakeMatchMedia`
415
+ stands in for `window.matchMedia` under Node: `set(query, matches)` flips a
416
+ query and fires `change`.
417
+
418
+ - `FrameScheduler(frames, render, { continuous?, maxDeltaSeconds?, clock?,
419
+ signal? })` — renders on animation frames, at most once each: after
420
+ `invalidate()` (calls before the frame coalesce), or every frame while
421
+ `continuous`. `FrameInfo` carries the frame's `time`, `deltaSeconds`
422
+ (0 on the first frame of a run, capped at `maxDeltaSeconds`, 0.1 by
423
+ default, so a tab back from the background does not jump) and `index`.
424
+ `renderNow()` renders at once and cancels a pending frame. Disposing, or
425
+ aborting `signal`, cancels the pending frame. `frames` is `window` or a
426
+ worker's global scope. A hidden page gets no frames, so a pending render
427
+ waits for it to be shown.
428
+
429
+ For a simulation stepped at a fixed rate under the frame rate, see
430
+ `FixedTimestep` in `@ac-kit/async`.
431
+
432
+ ## Testing
433
+
434
+ ```ts
435
+ import {
436
+ MicrophoneDeniedError,
437
+ requestMicrophoneStream,
438
+ } from "@ac-kit/browser";
439
+ import {
440
+ FakeAudioEnvironment,
441
+ FakeMediaDevices,
442
+ } from "@ac-kit/browser/testing";
443
+ import { expect, it } from "vitest";
444
+
445
+ it("tells a refusal", async () => {
446
+ const mediaDevices = new FakeMediaDevices(["NotAllowedError"]);
447
+
448
+ await expect(
449
+ requestMicrophoneStream({ mediaDevices }),
450
+ ).rejects.toBeInstanceOf(MicrophoneDeniedError);
451
+ expect(mediaDevices.requests).toHaveLength(1);
452
+ });
453
+
454
+ it("hears the worklet", async () => {
455
+ const audio = new FakeAudioEnvironment();
456
+ // Code under test receives audio.createContext and audio.createWorkletNode.
457
+ const input = createInput(audio.createContext, audio.createWorkletNode);
458
+ await input.start();
459
+ audio.node.emit({ type: "level", rms: 0.1 });
460
+ });
461
+ ```
462
+
463
+ `@ac-kit/browser/testing` holds stand-ins for the browser objects these
464
+ helpers, and code built on them, take — for tests under Node, not for a page:
465
+
466
+ - `FakeMediaDevices` — `getUserMedia` answering given outcomes in turn (a
467
+ `DOMException` by name, or a value thrown as it is), holding a call until
468
+ let go (`holdNext`) as a prompt does, devices listed and changed with a
469
+ `devicechange` event; its `FakeMediaStream`s and `FakeMediaStreamTrack`s
470
+ (settings, `ended`, `mute`, listeners counted).
471
+ - `FakeAudioEnvironment` — the `createContext` and `createWorkletNode`
472
+ factories to inject, making `FakeAudioContext`s (state and `statechange`,
473
+ `resume` held until a gesture, refused sampling rates, failing modules, the
474
+ sources and sounds made) and `FakeAudioWorkletNode`s whose `port`, a
475
+ `FakeMessagePort`, keeps what the page posts (`posted`, `postedOf(type)`),
476
+ hands it to `port.onPostMessage` where the test runs the processor's logic,
477
+ and delivers what the test `emit`s.
478
+ - `FakeMidiAccess` and `FakeMidiInput` — ports plugged in and out, messages
479
+ sent with their time stamps.
480
+ - `FakeAnimationFrames` — `requestAnimationFrame` queueing, `runFrame(time)`
481
+ running what was queued before the call.
482
+ - `FakeResizeObserver` — records what is observed, delivers `resize(size)`
483
+ entries, and can refuse `device-pixel-content-box` as Safari does.
484
+
485
+ They import no test runner: calls are recorded as data (`requests`,
486
+ `posted`, `modules`, `connections`, `stopCount`, `closeCount`…), and a
487
+ runner's own spy wraps any method where more is needed:
488
+ `vi.spyOn(mediaDevices, "getUserMedia")`. A spy whose implementation replaces
489
+ the method's loses that record: to answer what the page posts to a worklet,
490
+ set `port.onPostMessage` rather than mock `port.postMessage`.
491
+
176
492
  Browser-bound: it needs a page's (or a worker's) browser APIs, and depends on
177
493
  `@ac-kit/core` and `@ac-kit/async` only. Its Node counterpart is
178
494
  `@ac-kit/node`.
@@ -185,4 +501,9 @@ for the full reference.
185
501
 
186
502
  - [Indexed Database API 3.0](https://www.w3.org/TR/IndexedDB/)
187
503
  - [Web MIDI API](https://webaudio.github.io/web-midi-api/)
504
+ - [Media Capture and Streams](https://www.w3.org/TR/mediacapture-streams/)
505
+ - [Web Audio API](https://www.w3.org/TR/webaudio/)
188
506
  - [XMLHttpRequest Standard](https://xhr.spec.whatwg.org/)
507
+ - [HTML Standard: the 2D rendering context](https://html.spec.whatwg.org/multipage/canvas.html#2dcontext)
508
+ - [Web Animations](https://www.w3.org/TR/web-animations-1/)
509
+ - [CSS Transitions](https://www.w3.org/TR/css-transitions-1/)
@@ -0,0 +1,91 @@
1
+ import { type Callable, type Clock } from "@ac-kit/core";
2
+ /** `window` or a dedicated worker's global scope. */
3
+ export type AnimationFrames = Pick<AnimationFrameProvider, "requestAnimationFrame" | "cancelAnimationFrame">;
4
+ export type FrameInfo = {
5
+ /** The frame's time, ms on `performance.now()`'s time line. */
6
+ readonly time: number;
7
+ /**
8
+ * Seconds since the previous frame when it rendered too, else 0; at most
9
+ * `maxDeltaSeconds`. 0 for a non-finite `time`, which the next frame's delta
10
+ * does not count from.
11
+ */
12
+ readonly deltaSeconds: number;
13
+ /** Frames rendered before this one. */
14
+ readonly index: number;
15
+ };
16
+ export type FrameSchedulerOptions = {
17
+ /**
18
+ * Render every frame (playback, an animation) instead of on `invalidate()`.
19
+ * Default false.
20
+ */
21
+ readonly continuous?: boolean;
22
+ /**
23
+ * Cap on `deltaSeconds`, so a tab back from the background does not jump.
24
+ * Default 0.1.
25
+ */
26
+ readonly maxDeltaSeconds?: number;
27
+ /** `renderNow`'s time source. Default `SYSTEM_CLOCK`. */
28
+ readonly clock?: Clock;
29
+ /** Disposes the scheduler when it aborts. */
30
+ readonly signal?: AbortSignal;
31
+ };
32
+ /**
33
+ * Renders on animation frames, at most once each: on demand after
34
+ * `invalidate()`, or every frame while `continuous`. A throwing `render` is
35
+ * reported by the host like any frame callback; the next frame is already
36
+ * requested in continuous mode, and `invalidate()` keeps working.
37
+ *
38
+ * A frame with a delta of 0 starts a run: the first after idle, after
39
+ * `renderNow` or after a frame that rendered nothing. A hidden page gets no
40
+ * frames, so a pending render waits for it to be shown.
41
+ *
42
+ * @example
43
+ * const scheduler = new FrameScheduler(
44
+ * window,
45
+ * ({ deltaSeconds }) => {
46
+ * draw(deltaSeconds);
47
+ * },
48
+ * { signal },
49
+ * );
50
+ * scheduler.invalidate();
51
+ */
52
+ export declare class FrameScheduler implements Disposable {
53
+ private readonly frames_;
54
+ private readonly render_;
55
+ private readonly maxDeltaSeconds_;
56
+ private readonly clock_;
57
+ private readonly lifetime_;
58
+ private continuous_;
59
+ private handle_;
60
+ private invalidated_;
61
+ private rendering_;
62
+ private disposed_;
63
+ private index_;
64
+ /** The time of the last frame, `undefined` when the run is over. */
65
+ private lastTime_;
66
+ /** @throws {RangeError} When `maxDeltaSeconds` is not positive. */
67
+ constructor(frames: AnimationFrames, render: Callable<[frame: FrameInfo]>, options?: FrameSchedulerOptions);
68
+ /** Whether every frame renders. Changing it takes effect at the next frame. */
69
+ get continuous(): boolean;
70
+ set continuous(value: boolean);
71
+ /** Whether a frame is requested and not run yet. */
72
+ get isPending(): boolean;
73
+ get isDisposed(): boolean;
74
+ /** Requests one render at the next frame; calls before it coalesce. O(1). */
75
+ invalidate(): void;
76
+ /**
77
+ * Renders now, at `clock.now()`, and cancels a pending frame: for
78
+ * `observeCanvasSize`'s `onResize`. Called from within a render it is an
79
+ * `invalidate()` instead, as rendering inside a render would nest frames. In
80
+ * continuous mode the next frame is requested again.
81
+ */
82
+ renderNow(): void;
83
+ [Symbol.dispose](): void;
84
+ private release_;
85
+ private request_;
86
+ private cancel_;
87
+ private onFrame_;
88
+ private finishRun_;
89
+ private renderAt_;
90
+ }
91
+ //# sourceMappingURL=frame-scheduler.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frame-scheduler.d.ts","sourceRoot":"","sources":["../../src/animation-frame/frame-scheduler.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,QAAQ,EACb,KAAK,KAAK,EAIV,MAAM,cAAc,CAAC;AAEtB,qDAAqD;AACrD,MAAM,MAAM,eAAe,GAAG,IAAI,CACjC,sBAAsB,EACtB,uBAAuB,GAAG,sBAAsB,CAChD,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACvB,+DAA+D;IAC/D,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB;;;;OAIG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,uCAAuC;IACvC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,qBAAqB,GAAG;IACnC;;;OAGG;IACH,QAAQ,CAAC,UAAU,CAAC,EAAE,OAAO,CAAC;IAC9B;;;OAGG;IACH,QAAQ,CAAC,eAAe,CAAC,EAAE,MAAM,CAAC;IAClC,yDAAyD;IACzD,QAAQ,CAAC,KAAK,CAAC,EAAE,KAAK,CAAC;IACvB,6CAA6C;IAC7C,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAC;CAC9B,CAAC;AAIF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,qBAAa,cAAe,YAAW,UAAU;IAChD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAkB;IAC1C,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA+B;IACvD,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;IAC1C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAyB;IACnD,OAAO,CAAC,WAAW,CAAU;IAC7B,OAAO,CAAC,OAAO,CAAqB;IACpC,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,SAAS,CAAS;IAC1B,OAAO,CAAC,MAAM,CAAK;IACnB,oEAAoE;IACpE,OAAO,CAAC,SAAS,CAAqB;IAEtC,mEAAmE;IACnE,YACC,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,QAAQ,CAAC,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,EACpC,OAAO,GAAE,qBAA0B,EAiCnC;IAED,+EAA+E;IAC/E,IAAI,UAAU,IAAI,OAAO,CAExB;IAED,IAAI,UAAU,CAAC,KAAK,EAAE,OAAO,EAK5B;IAED,oDAAoD;IACpD,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED,IAAI,UAAU,IAAI,OAAO,CAExB;IAED,6EAA6E;IAC7E,UAAU,IAAI,IAAI,CAGjB;IAED;;;;;OAKG;IACH,SAAS,IAAI,IAAI,CAmBhB;IAED,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,IAAI,CAEvB;IAED,OAAO,CAAC,QAAQ;IAQhB,OAAO,CAAC,QAAQ;IAShB,OAAO,CAAC,OAAO;IAOf,OAAO,CAAC,QAAQ;IAuBhB,OAAO,CAAC,UAAU;IAMlB,OAAO,CAAC,SAAS;CAuBjB"}