@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
@@ -0,0 +1,181 @@
1
+ import { describeValue, MS_PER_SECOND, SYSTEM_CLOCK, } from "@ac-kit/core";
2
+ const DEFAULT_MAX_DELTA_SECONDS_ = 0.1;
3
+ /**
4
+ * Renders on animation frames, at most once each: on demand after
5
+ * `invalidate()`, or every frame while `continuous`. A throwing `render` is
6
+ * reported by the host like any frame callback; the next frame is already
7
+ * requested in continuous mode, and `invalidate()` keeps working.
8
+ *
9
+ * A frame with a delta of 0 starts a run: the first after idle, after
10
+ * `renderNow` or after a frame that rendered nothing. A hidden page gets no
11
+ * frames, so a pending render waits for it to be shown.
12
+ *
13
+ * @example
14
+ * const scheduler = new FrameScheduler(
15
+ * window,
16
+ * ({ deltaSeconds }) => {
17
+ * draw(deltaSeconds);
18
+ * },
19
+ * { signal },
20
+ * );
21
+ * scheduler.invalidate();
22
+ */
23
+ export class FrameScheduler {
24
+ frames_;
25
+ render_;
26
+ maxDeltaSeconds_;
27
+ clock_;
28
+ lifetime_ = new AbortController();
29
+ continuous_;
30
+ handle_;
31
+ invalidated_ = false;
32
+ rendering_ = false;
33
+ disposed_ = false;
34
+ index_ = 0;
35
+ /** The time of the last frame, `undefined` when the run is over. */
36
+ lastTime_;
37
+ /** @throws {RangeError} When `maxDeltaSeconds` is not positive. */
38
+ constructor(frames, render, options = {}) {
39
+ const { continuous = false, maxDeltaSeconds = DEFAULT_MAX_DELTA_SECONDS_, clock = SYSTEM_CLOCK, signal, } = options;
40
+ if (!(maxDeltaSeconds > 0)) {
41
+ throw new RangeError(`FrameScheduler: maxDeltaSeconds must be positive, got ${describeValue(maxDeltaSeconds)}`);
42
+ }
43
+ this.frames_ = frames;
44
+ this.render_ = render;
45
+ this.maxDeltaSeconds_ = maxDeltaSeconds;
46
+ this.clock_ = clock;
47
+ this.continuous_ = continuous;
48
+ if (signal?.aborted) {
49
+ this.disposed_ = true;
50
+ return;
51
+ }
52
+ // A derived signal aborts whatever a listener on `signal` does to the event.
53
+ const stop = signal === undefined
54
+ ? this.lifetime_.signal
55
+ : AbortSignal.any([signal, this.lifetime_.signal]);
56
+ stop.addEventListener("abort", () => this.release_(), { once: true });
57
+ if (continuous) {
58
+ this.request_();
59
+ }
60
+ }
61
+ /** Whether every frame renders. Changing it takes effect at the next frame. */
62
+ get continuous() {
63
+ return this.continuous_;
64
+ }
65
+ set continuous(value) {
66
+ this.continuous_ = value;
67
+ if (value) {
68
+ this.request_();
69
+ }
70
+ }
71
+ /** Whether a frame is requested and not run yet. */
72
+ get isPending() {
73
+ return this.handle_ !== undefined;
74
+ }
75
+ get isDisposed() {
76
+ return this.disposed_;
77
+ }
78
+ /** Requests one render at the next frame; calls before it coalesce. O(1). */
79
+ invalidate() {
80
+ this.invalidated_ = true;
81
+ this.request_();
82
+ }
83
+ /**
84
+ * Renders now, at `clock.now()`, and cancels a pending frame: for
85
+ * `observeCanvasSize`'s `onResize`. Called from within a render it is an
86
+ * `invalidate()` instead, as rendering inside a render would nest frames. In
87
+ * continuous mode the next frame is requested again.
88
+ */
89
+ renderNow() {
90
+ if (this.disposed_) {
91
+ return;
92
+ }
93
+ if (this.rendering_) {
94
+ this.invalidate();
95
+ return;
96
+ }
97
+ this.cancel_();
98
+ this.invalidated_ = false;
99
+ try {
100
+ this.renderAt_(this.clock_.now());
101
+ }
102
+ finally {
103
+ if (this.continuous_) {
104
+ this.request_();
105
+ }
106
+ this.finishRun_();
107
+ }
108
+ }
109
+ [Symbol.dispose]() {
110
+ this.lifetime_.abort();
111
+ }
112
+ release_() {
113
+ if (this.disposed_) {
114
+ return;
115
+ }
116
+ this.disposed_ = true;
117
+ this.cancel_();
118
+ }
119
+ request_() {
120
+ if (this.disposed_ || this.handle_ !== undefined) {
121
+ return;
122
+ }
123
+ this.handle_ = this.frames_.requestAnimationFrame((time) => this.onFrame_(time));
124
+ }
125
+ cancel_() {
126
+ if (this.handle_ !== undefined) {
127
+ this.frames_.cancelAnimationFrame(this.handle_);
128
+ this.handle_ = undefined;
129
+ }
130
+ }
131
+ onFrame_(time) {
132
+ this.handle_ = undefined;
133
+ if (this.disposed_) {
134
+ return;
135
+ }
136
+ const due = this.continuous_ || this.invalidated_;
137
+ this.invalidated_ = false;
138
+ if (!due) {
139
+ this.lastTime_ = undefined;
140
+ return;
141
+ }
142
+ if (this.continuous_) {
143
+ this.request_();
144
+ }
145
+ try {
146
+ this.renderAt_(time);
147
+ }
148
+ finally {
149
+ this.finishRun_();
150
+ }
151
+ }
152
+ // On demand, a run ends when nothing asks for the next frame.
153
+ finishRun_() {
154
+ if (this.handle_ === undefined) {
155
+ this.lastTime_ = undefined;
156
+ }
157
+ }
158
+ renderAt_(time) {
159
+ const elapsed = this.lastTime_ === undefined || !Number.isFinite(time)
160
+ ? 0
161
+ : (time - this.lastTime_) / MS_PER_SECOND;
162
+ // A clock that went back counts as no time passed.
163
+ const deltaSeconds = elapsed > 0 ? Math.min(elapsed, this.maxDeltaSeconds_) : 0;
164
+ // The baseline never moves back, so `renderNow`'s clock and the frames'
165
+ // time line, which may disagree, do not inflate the next delta; a
166
+ // non-finite time leaves it alone (and its frame's delta is 0).
167
+ if (Number.isFinite(time)) {
168
+ this.lastTime_ = Math.max(time, this.lastTime_ ?? time);
169
+ }
170
+ const frame = { time, deltaSeconds, index: this.index_ };
171
+ this.index_ += 1;
172
+ this.rendering_ = true;
173
+ try {
174
+ this.render_(frame);
175
+ }
176
+ finally {
177
+ this.rendering_ = false;
178
+ }
179
+ }
180
+ }
181
+ //# sourceMappingURL=frame-scheduler.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"frame-scheduler.js","sourceRoot":"","sources":["../../src/animation-frame/frame-scheduler.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,aAAa,EACb,aAAa,EACb,YAAY,GACZ,MAAM,cAAc,CAAC;AAsCtB,MAAM,0BAA0B,GAAG,GAAG,CAAC;AAEvC;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,OAAO,cAAc;IACT,OAAO,CAAkB;IACzB,OAAO,CAA+B;IACtC,gBAAgB,CAAS;IACzB,MAAM,CAAQ;IACd,SAAS,GAAG,IAAI,eAAe,EAAE,CAAC;IAC3C,WAAW,CAAU;IACrB,OAAO,CAAqB;IAC5B,YAAY,GAAG,KAAK,CAAC;IACrB,UAAU,GAAG,KAAK,CAAC;IACnB,SAAS,GAAG,KAAK,CAAC;IAClB,MAAM,GAAG,CAAC,CAAC;IACnB,oEAAoE;IAC5D,SAAS,CAAqB;IAEtC,mEAAmE;IACnE,YACC,MAAuB,EACvB,MAAoC,EACpC,OAAO,GAA0B,EAAE;QAEnC,MAAM,EACL,UAAU,GAAG,KAAK,EAClB,eAAe,GAAG,0BAA0B,EAC5C,KAAK,GAAG,YAAY,EACpB,MAAM,GACN,GAAG,OAAO,CAAC;QACZ,IAAI,CAAC,CAAC,eAAe,GAAG,CAAC,CAAC,EAAE,CAAC;YAC5B,MAAM,IAAI,UAAU,CACnB,yDAAyD,aAAa,CAAC,eAAe,CAAC,EAAE,CACzF,CAAC;QACH,CAAC;QAED,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC;QACtB,IAAI,CAAC,gBAAgB,GAAG,eAAe,CAAC;QACxC,IAAI,CAAC,MAAM,GAAG,KAAK,CAAC;QACpB,IAAI,CAAC,WAAW,GAAG,UAAU,CAAC;QAC9B,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC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Y,EAAE,KAAK,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC;QACpE,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC;QACjB,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACvB,IAAI,CAAC;YACJ,IAAI,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;gBAAS,CAAC;YACV,IAAI,CAAC,UAAU,GAAG,KAAK,CAAC;QACzB,CAAC;IACF,CAAC;CACD"}
@@ -0,0 +1,58 @@
1
+ /** A canvas's content box, as the page measures it. */
2
+ export type CanvasBoxSize = {
3
+ readonly cssWidth: number;
4
+ readonly cssHeight: number;
5
+ /** From `devicePixelContentBoxSize`, when the browser gives it (not Safari). */
6
+ readonly devicePixelWidth?: number;
7
+ readonly devicePixelHeight?: number;
8
+ /** The page's `devicePixelRatio`. */
9
+ readonly devicePixelRatio: number;
10
+ };
11
+ export type CanvasBackingSizeOptions = {
12
+ /** Most backing pixels per CSS pixel (heliotrope: 2). Default: no cap. */
13
+ readonly maxPixelRatio?: number;
14
+ /**
15
+ * Most backing pixels in all (e.g. 3840 × 2160); the ratio is lowered to fit.
16
+ * Default: no cap.
17
+ */
18
+ readonly maxPixels?: number;
19
+ /** Longest side (e.g. a device's `maxTextureDimension2D`). Default: no cap. */
20
+ readonly maxSide?: number;
21
+ };
22
+ export type CanvasBackingSize = {
23
+ /** Whole pixels, what `canvas.width` and `canvas.height` must hold. */
24
+ readonly width: number;
25
+ readonly height: number;
26
+ readonly cssWidth: number;
27
+ readonly cssHeight: number;
28
+ /**
29
+ * Backing pixels per CSS pixel actually used: `width / cssWidth`. For a
30
+ * canvas with no CSS width it is taken from the height, and for an empty one
31
+ * it is the ratio the caps leave.
32
+ */
33
+ readonly pixelRatio: number;
34
+ };
35
+ /**
36
+ * The backing-store size for a canvas: the device-pixel size exactly when the
37
+ * browser gives it and no cap applies (pixel-perfect, no moiré), else the CSS
38
+ * size times the capped ratio, rounded but floored wherever a cap binds, so
39
+ * rounding never passes `maxPixelRatio`, `maxPixels` or `maxSide`. A side with
40
+ * a CSS size is at least 1 pixel (which wins over a `maxPixelRatio` below one
41
+ * pixel per side); `maxPixels` and `maxSide` always hold, the larger side
42
+ * giving way. An empty canvas stays empty, whatever the device size says.
43
+ * O(1).
44
+ *
45
+ * @example
46
+ * const size = canvasBackingSize(
47
+ * { cssWidth: 300.4, cssHeight: 150, devicePixelRatio: 3 },
48
+ * { maxPixelRatio: 2 },
49
+ * );
50
+ * // { width: 600, height: 300, cssWidth: 300.4, cssHeight: 150, pixelRatio: … }
51
+ *
52
+ * @throws {RangeError} For a negative or non-finite size (a device dimension
53
+ * included) or ratio, a ratio of 0, a cap that is not positive, `maxPixels`
54
+ * or `maxSide` below 1, or a size, device dimensions included, too large for
55
+ * whole pixels without a cap.
56
+ */
57
+ export declare function canvasBackingSize(box: CanvasBoxSize, options?: CanvasBackingSizeOptions): CanvasBackingSize;
58
+ //# sourceMappingURL=canvas-backing-size.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canvas-backing-size.d.ts","sourceRoot":"","sources":["../../src/canvas/canvas-backing-size.ts"],"names":[],"mappings":"AAEA,uDAAuD;AACvD,MAAM,MAAM,aAAa,GAAG;IAC3B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,gFAAgF;IAChF,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IACpC,qCAAqC;IACrC,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;CAClC,CAAC;AAEF,MAAM,MAAM,wBAAwB,GAAG;IACtC,0EAA0E;IAC1E,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B,+EAA+E;IAC/E,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;CAC1B,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG;IAC/B,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B;;;;OAIG;IACH,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;CAC5B,CAAC;AA+EF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,iBAAiB,CAChC,GAAG,EAAE,aAAa,EAClB,OAAO,GAAE,wBAA6B,GACpC,iBAAiB,CAgFnB"}
@@ -0,0 +1,141 @@
1
+ import { assertNonNegative, assertPositive } from "@ac-kit/core";
2
+ // A cap of `Infinity` or `undefined` is no cap.
3
+ function capOf_(name, value, minimum) {
4
+ if (value === undefined || value === Infinity) {
5
+ return Infinity;
6
+ }
7
+ assertPositive(value, `canvasBackingSize: ${name}`);
8
+ if (value < minimum) {
9
+ throw new RangeError(`canvasBackingSize: ${name} must be at least ${minimum}, got ${value}`);
10
+ }
11
+ return value;
12
+ }
13
+ function fitsCaps_(width, height, caps) {
14
+ return width * height <= caps.pixels && Math.max(width, height) <= caps.side;
15
+ }
16
+ // The side at `ratio`, rounded, then floored to every per-side cap (the ratio
17
+ // cap and `maxSide`) so rounding never passes one; a visible side keeps 1.
18
+ function sideOf_(css, ratio, caps, round) {
19
+ if (!(css > 0)) {
20
+ return 0;
21
+ }
22
+ const bound = Math.floor(Math.min(css * caps.ratio, caps.side));
23
+ return Math.max(1, Math.min(round(css * ratio), bound));
24
+ }
25
+ function assertWholePixels_(width, height, what) {
26
+ if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height)) {
27
+ throw new RangeError(`canvasBackingSize: ${what} are too large for whole pixels; give maxSide or maxPixels`);
28
+ }
29
+ }
30
+ // Lowers the larger side, then the other if one pixel was not enough: every
31
+ // non-empty side stays at least 1 and the product ends within `pixels`.
32
+ function fitPixels_(width, height, pixels) {
33
+ let fittedWidth = width;
34
+ let fittedHeight = height;
35
+ for (let pass = 0; pass < 2 && fittedWidth * fittedHeight > pixels; pass += 1) {
36
+ if (fittedWidth >= fittedHeight) {
37
+ fittedWidth = Math.max(1, Math.floor(pixels / fittedHeight));
38
+ }
39
+ else {
40
+ fittedHeight = Math.max(1, Math.floor(pixels / fittedWidth));
41
+ }
42
+ }
43
+ return [fittedWidth, fittedHeight];
44
+ }
45
+ /**
46
+ * The backing-store size for a canvas: the device-pixel size exactly when the
47
+ * browser gives it and no cap applies (pixel-perfect, no moiré), else the CSS
48
+ * size times the capped ratio, rounded but floored wherever a cap binds, so
49
+ * rounding never passes `maxPixelRatio`, `maxPixels` or `maxSide`. A side with
50
+ * a CSS size is at least 1 pixel (which wins over a `maxPixelRatio` below one
51
+ * pixel per side); `maxPixels` and `maxSide` always hold, the larger side
52
+ * giving way. An empty canvas stays empty, whatever the device size says.
53
+ * O(1).
54
+ *
55
+ * @example
56
+ * const size = canvasBackingSize(
57
+ * { cssWidth: 300.4, cssHeight: 150, devicePixelRatio: 3 },
58
+ * { maxPixelRatio: 2 },
59
+ * );
60
+ * // { width: 600, height: 300, cssWidth: 300.4, cssHeight: 150, pixelRatio: … }
61
+ *
62
+ * @throws {RangeError} For a negative or non-finite size (a device dimension
63
+ * included) or ratio, a ratio of 0, a cap that is not positive, `maxPixels`
64
+ * or `maxSide` below 1, or a size, device dimensions included, too large for
65
+ * whole pixels without a cap.
66
+ */
67
+ export function canvasBackingSize(box, options = {}) {
68
+ const { cssWidth, cssHeight, devicePixelRatio } = box;
69
+ assertNonNegative(cssWidth, "canvasBackingSize: cssWidth");
70
+ assertNonNegative(cssHeight, "canvasBackingSize: cssHeight");
71
+ assertPositive(devicePixelRatio, "canvasBackingSize: devicePixelRatio");
72
+ const caps = {
73
+ ratio: capOf_("maxPixelRatio", options.maxPixelRatio, 0),
74
+ pixels: capOf_("maxPixels", options.maxPixels, 1),
75
+ side: capOf_("maxSide", options.maxSide, 1),
76
+ };
77
+ const { devicePixelWidth, devicePixelHeight } = box;
78
+ if (devicePixelWidth !== undefined) {
79
+ assertNonNegative(devicePixelWidth, "canvasBackingSize: devicePixelWidth");
80
+ }
81
+ if (devicePixelHeight !== undefined) {
82
+ assertNonNegative(devicePixelHeight, "canvasBackingSize: devicePixelHeight");
83
+ }
84
+ const isEmpty = cssWidth === 0 || cssHeight === 0;
85
+ if (!isEmpty &&
86
+ devicePixelWidth !== undefined &&
87
+ devicePixelHeight !== undefined) {
88
+ const width = Math.round(devicePixelWidth);
89
+ const height = Math.round(devicePixelHeight);
90
+ if (width >= 1 &&
91
+ height >= 1 &&
92
+ fitsCaps_(width, height, caps) &&
93
+ width <= cssWidth * caps.ratio &&
94
+ height <= cssHeight * caps.ratio) {
95
+ assertWholePixels_(width, height, `${width} × ${height} device pixels`);
96
+ return {
97
+ width,
98
+ height,
99
+ cssWidth,
100
+ cssHeight,
101
+ pixelRatio: pixelRatioOf_(width, height, box, devicePixelRatio),
102
+ };
103
+ }
104
+ }
105
+ let ratio = Math.min(devicePixelRatio, caps.ratio);
106
+ const root = Math.sqrt(cssWidth) * Math.sqrt(cssHeight);
107
+ if (ratio * root > Math.sqrt(caps.pixels)) {
108
+ ratio = Math.sqrt(caps.pixels) / root;
109
+ }
110
+ const longest = Math.max(cssWidth, cssHeight);
111
+ if (ratio * longest > caps.side) {
112
+ ratio = caps.side / longest;
113
+ }
114
+ // Under a lowered ratio the cap must hold: floor, never round up.
115
+ const round = ratio < devicePixelRatio ? Math.floor : Math.round;
116
+ let width = sideOf_(cssWidth, ratio, caps, round);
117
+ let height = sideOf_(cssHeight, ratio, caps, round);
118
+ if (!fitsCaps_(width, height, caps)) {
119
+ width = sideOf_(cssWidth, ratio, caps, Math.floor);
120
+ height = sideOf_(cssHeight, ratio, caps, Math.floor);
121
+ }
122
+ [width, height] = fitPixels_(width, height, caps.pixels);
123
+ assertWholePixels_(width, height, `${cssWidth} × ${cssHeight} CSS pixels at ratio ${ratio}`);
124
+ return {
125
+ width,
126
+ height,
127
+ cssWidth,
128
+ cssHeight,
129
+ pixelRatio: pixelRatioOf_(width, height, box, ratio),
130
+ };
131
+ }
132
+ function pixelRatioOf_(width, height, box, fallback) {
133
+ if (box.cssWidth > 0) {
134
+ return width / box.cssWidth;
135
+ }
136
+ if (box.cssHeight > 0) {
137
+ return height / box.cssHeight;
138
+ }
139
+ return fallback;
140
+ }
141
+ //# sourceMappingURL=canvas-backing-size.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"canvas-backing-size.js","sourceRoot":"","sources":["../../src/canvas/canvas-backing-size.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AA6CjE,gDAAgD;AAChD,SAAS,MAAM,CACd,IAAY,EACZ,KAAyB,EACzB,OAAe;IAEf,IAAI,KAAK,KAAK,SAAS,IAAI,KAAK,KAAK,QAAQ,EAAE,CAAC;QAC/C,OAAO,QAAQ,CAAC;IACjB,CAAC;IACD,cAAc,CAAC,KAAK,EAAE,sBAAsB,IAAI,EAAE,CAAC,CAAC;IACpD,IAAI,KAAK,GAAG,OAAO,EAAE,CAAC;QACrB,MAAM,IAAI,UAAU,CACnB,sBAAsB,IAAI,qBAAqB,OAAO,SAAS,KAAK,EAAE,CACtE,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACd,CAAC;AAED,SAAS,SAAS,CAAC,KAAa,EAAE,MAAc,EAAE,IAAW;IAC5D,OAAO,KAAK,GAAG,MAAM,IAAI,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC;AAC9E,CAAC;AAED,8EAA8E;AAC9E,2EAA2E;AAC3E,SAAS,OAAO,CACf,GAAW,EACX,KAAa,EACb,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1,61 @@
1
+ import { type Callable } from "@ac-kit/core";
2
+ /**
3
+ * One pixel of 8-bit `ImageData`, each component in [0, 255]: the shape of
4
+ * `@ac-kit/math-color`'s `Rgba8`, so it goes to its conversions as it is.
5
+ */
6
+ export type ImageDataPixel = {
7
+ r8: number;
8
+ g8: number;
9
+ b8: number;
10
+ a8: number;
11
+ };
12
+ /**
13
+ * The pixels of 8-bit `ImageData`, row by row from the top left, each a new
14
+ * object: `width × height` of them, none for an empty one. Its `colorSpace`
15
+ * says which RGB they are in; their colour is not premultiplied by alpha.
16
+ *
17
+ * Lazy, O(1) time per pixel, but one object allocated for each: on a full-HD
18
+ * image, several times slower than {@link forEachImageDataPixel}, which
19
+ * allocates nothing, and a load on the garbage collector. Reach for it where
20
+ * the pixels are kept as objects anyway.
21
+ *
22
+ * @example
23
+ * const colors = Array.from(imageDataPixels(imageData), (pixel) =>
24
+ * rgb8ToRgb1(pixel),
25
+ * );
26
+ *
27
+ * @param imageData `ImageData`, or anything holding its `data`.
28
+ * @throws {TypeError} When `data` is not a `Uint8ClampedArray` — `ImageData`
29
+ * with `pixelFormat: "rgba-float16"` holds a `Float16Array` — at the call,
30
+ * before any pixel.
31
+ */
32
+ export declare function imageDataPixels(imageData: Pick<ImageData, "data">): IterableIterator<ImageDataPixel>;
33
+ /**
34
+ * Calls `visit` with the components of each pixel of 8-bit `ImageData`, row by
35
+ * row from the top left, and its index in that order (`y × width + x`): never
36
+ * for an empty one. Its `colorSpace` says which RGB they are in; their colour
37
+ * is not premultiplied by alpha.
38
+ *
39
+ * O(1) time per pixel and no allocation of its own: the form for a loop over
40
+ * every pixel of a large image. {@link imageDataPixels} yields objects
41
+ * instead.
42
+ *
43
+ * @example
44
+ * let opaque = 0;
45
+ * forEachImageDataPixel(imageData, (r8, g8, b8, a8) => {
46
+ * if (a8 === 255) opaque++;
47
+ * });
48
+ *
49
+ * @param imageData `ImageData`, or anything holding its `data`.
50
+ * @throws {TypeError} When `data` is not a `Uint8ClampedArray` — `ImageData`
51
+ * with `pixelFormat: "rgba-float16"` holds a `Float16Array` — before any
52
+ * pixel. What `visit` throws goes through, ending the loop.
53
+ */
54
+ export declare function forEachImageDataPixel(imageData: Pick<ImageData, "data">, visit: Callable<[
55
+ r8: number,
56
+ g8: number,
57
+ b8: number,
58
+ a8: number,
59
+ index: number
60
+ ]>): void;
61
+ //# sourceMappingURL=image-data-pixels.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-data-pixels.d.ts","sourceRoot":"","sources":["../../src/canvas/image-data-pixels.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,QAAQ,EAAuB,MAAM,cAAc,CAAC;AAElE;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG;IAC5B,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;IACX,EAAE,EAAE,MAAM,CAAC;CACX,CAAC;AAEF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,eAAe,CAC9B,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,GAChC,gBAAgB,CAAC,cAAc,CAAC,CAKlC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAgB,qBAAqB,CACpC,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,MAAM,CAAC,EAClC,KAAK,EAAE,QAAQ,CACd;IAAC,EAAE,EAAE,MAAM;IAAE,EAAE,EAAE,MAAM;IAAE,EAAE,EAAE,MAAM;IAAE,EAAE,EAAE,MAAM;IAAE,KAAK,EAAE,MAAM;CAAC,CAC/D,GACC,IAAI,CAYN"}
@@ -0,0 +1,71 @@
1
+ import { isUint8ClampedArray } from "@ac-kit/core";
2
+ /**
3
+ * The pixels of 8-bit `ImageData`, row by row from the top left, each a new
4
+ * object: `width × height` of them, none for an empty one. Its `colorSpace`
5
+ * says which RGB they are in; their colour is not premultiplied by alpha.
6
+ *
7
+ * Lazy, O(1) time per pixel, but one object allocated for each: on a full-HD
8
+ * image, several times slower than {@link forEachImageDataPixel}, which
9
+ * allocates nothing, and a load on the garbage collector. Reach for it where
10
+ * the pixels are kept as objects anyway.
11
+ *
12
+ * @example
13
+ * const colors = Array.from(imageDataPixels(imageData), (pixel) =>
14
+ * rgb8ToRgb1(pixel),
15
+ * );
16
+ *
17
+ * @param imageData `ImageData`, or anything holding its `data`.
18
+ * @throws {TypeError} When `data` is not a `Uint8ClampedArray` — `ImageData`
19
+ * with `pixelFormat: "rgba-float16"` holds a `Float16Array` — at the call,
20
+ * before any pixel.
21
+ */
22
+ export function imageDataPixels(imageData) {
23
+ const { data } = imageData;
24
+ assertUint8Clamped_(data);
25
+ return pixels_(data);
26
+ }
27
+ /**
28
+ * Calls `visit` with the components of each pixel of 8-bit `ImageData`, row by
29
+ * row from the top left, and its index in that order (`y × width + x`): never
30
+ * for an empty one. Its `colorSpace` says which RGB they are in; their colour
31
+ * is not premultiplied by alpha.
32
+ *
33
+ * O(1) time per pixel and no allocation of its own: the form for a loop over
34
+ * every pixel of a large image. {@link imageDataPixels} yields objects
35
+ * instead.
36
+ *
37
+ * @example
38
+ * let opaque = 0;
39
+ * forEachImageDataPixel(imageData, (r8, g8, b8, a8) => {
40
+ * if (a8 === 255) opaque++;
41
+ * });
42
+ *
43
+ * @param imageData `ImageData`, or anything holding its `data`.
44
+ * @throws {TypeError} When `data` is not a `Uint8ClampedArray` — `ImageData`
45
+ * with `pixelFormat: "rgba-float16"` holds a `Float16Array` — before any
46
+ * pixel. What `visit` throws goes through, ending the loop.
47
+ */
48
+ export function forEachImageDataPixel(imageData, visit) {
49
+ const { data } = imageData;
50
+ assertUint8Clamped_(data);
51
+ for (let offset = 0, index = 0; offset + 3 < data.length; offset += 4) {
52
+ visit(data[offset], data[offset + 1], data[offset + 2], data[offset + 3], index++);
53
+ }
54
+ }
55
+ function* pixels_(data) {
56
+ for (let offset = 0; offset + 3 < data.length; offset += 4) {
57
+ yield {
58
+ r8: data[offset],
59
+ g8: data[offset + 1],
60
+ b8: data[offset + 2],
61
+ a8: data[offset + 3],
62
+ };
63
+ }
64
+ }
65
+ // The typings say `Uint8ClampedArray` even of a `Float16Array`.
66
+ function assertUint8Clamped_(data) {
67
+ if (!isUint8ClampedArray(data)) {
68
+ throw new TypeError("ImageData pixels are not 8-bit (rgba-unorm8)");
69
+ }
70
+ }
71
+ //# sourceMappingURL=image-data-pixels.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"image-data-pixels.js","sourceRoot":"","sources":["../../src/canvas/image-data-pixels.ts"],"names":[],"mappings":"AAAA,OAAO,EAAiB,mBAAmB,EAAE,MAAM,cAAc,CAAC;AAalE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,MAAM,UAAU,eAAe,CAC9B,SAAkC;IAElC,MAAM,EAAE,IAAI,EAAE,GAAG,SAAS,CAAC;IAC3B,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAE1B,OAAO,OAAO,CAAC,IAAI,CAAC,CAAC;AACtB,CAAC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,UAAU,qBAAqB,CACpC,SAAkC,EAClC,KAEC;IAED,MAAM,EAAE,IAAI,EAAE,GAAG,SAAS,CAAC;IAC3B,mBAAmB,CAAC,IAAI,CAAC,CAAC;IAC1B,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC,EAAE,CAAC;QACvE,KAAK,CACJ,IAAI,CAAC,MAAM,CAAE,EACb,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE,EACjB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE,EACjB,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE,EACjB,KAAK,EAAE,CACP,CAAC;IACH,CAAC;AACF,CAAC;AAED,QAAQ,CAAC,CAAC,OAAO,CAAC,IAAuB;IACxC,KAAK,IAAI,MAAM,GAAG,CAAC,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC,EAAE,CAAC;QAC5D,MAAM;YACL,EAAE,EAAE,IAAI,CAAC,MAAM,CAAE;YACjB,EAAE,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE;YACrB,EAAE,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE;YACrB,EAAE,EAAE,IAAI,CAAC,MAAM,GAAG,CAAC,CAAE;SACrB,CAAC;IACH,CAAC;AACF,CAAC;AAED,gEAAgE;AAChE,SAAS,mBAAmB,CAAC,IAAa;IACzC,IAAI,CAAC,mBAAmB,CAAC,IAAI,CAAC,EAAE,CAAC;QAChC,MAAM,IAAI,SAAS,CAAC,8CAA8C,CAAC,CAAC;IACrE,CAAC;AACF,CAAC"}
@@ -0,0 +1,120 @@
1
+ import { type Callable } from "@ac-kit/core";
2
+ /**
3
+ * What {@link readImageData} draws: an image, a video's current frame, a
4
+ * canvas, an `ImageBitmap` or a `VideoFrame` — every `CanvasImageSource` but an
5
+ * SVG `<image>`, whose size in pixels it cannot tell.
6
+ */
7
+ export type ImageDataSource = HTMLImageElement | HTMLVideoElement | HTMLCanvasElement | OffscreenCanvas | ImageBitmap | VideoFrame;
8
+ /** The members of a 2D context {@link readImageData} draws and reads through. */
9
+ export type ImageDataContext = Pick<CanvasRenderingContext2D, "drawImage" | "getImageData" | "imageSmoothingEnabled" | "imageSmoothingQuality">;
10
+ /**
11
+ * A canvas {@link readImageData} draws on: an `HTMLCanvasElement`, an
12
+ * `OffscreenCanvas`, or a stand-in.
13
+ */
14
+ export type ImageDataCanvas = {
15
+ getContext(contextId: "2d", settings?: CanvasRenderingContext2DSettings): ImageDataContext | null;
16
+ };
17
+ /** How {@link readImageData} draws the image before reading it. */
18
+ export type ReadImageDataOptions = {
19
+ /**
20
+ * The most pixels either side of the result may have, a positive integer. A
21
+ * larger source is drawn scaled down so that its longer side is `maxSize`,
22
+ * keeping its aspect ratio, its shorter side rounded and at least 1; a
23
+ * smaller one is drawn at its own size, never scaled up. It bounds what is
24
+ * drawn and read back, not what the browser decodes: the source is whole in
25
+ * memory already. Default: no limit but `maxSide` and `maxPixels`.
26
+ */
27
+ readonly maxSize?: number;
28
+ /**
29
+ * The most pixels the result may have, a positive integer: a larger one
30
+ * throws rather than risk a canvas the browser cannot allocate, which reads
31
+ * back blank instead of failing. Default: 16,777,216 (4096 × 4096), the
32
+ * smallest canvas area current browsers allow (Safari on iOS); Chromium,
33
+ * Firefox and desktop Safari allow far more.
34
+ */
35
+ readonly maxPixels?: number;
36
+ /**
37
+ * The most pixels either side of the result may have, a positive integer: a
38
+ * longer one throws, for the same reason as `maxPixels`. Unlike `maxSize`, it
39
+ * never scales. Default: 32,767, this library's conservative choice (2¹⁵ − 1,
40
+ * a side the major browsers all draw), not a limit of any one browser; raise
41
+ * it where the target browsers are known to draw wider canvases, as Chromium
42
+ * does.
43
+ */
44
+ readonly maxSide?: number;
45
+ /**
46
+ * How the image is resampled when scaled: `false` for nearest neighbour, or
47
+ * the `imageSmoothingQuality` of a smoothed one (`"low"`, `"medium"`,
48
+ * `"high"`). Default: a fresh context's, smoothed at `"low"`.
49
+ */
50
+ readonly smoothing?: false | ImageSmoothingQuality;
51
+ /**
52
+ * Given to `getContext("2d")` as they are, and so applied only by a canvas's
53
+ * first context. `colorSpace` is the space the pixels are converted to and
54
+ * returned in: `"display-p3"` keeps a wide-gamut image's colours, where the
55
+ * browser supports it.
56
+ */
57
+ readonly contextSettings?: CanvasRenderingContext2DSettings;
58
+ };
59
+ /**
60
+ * The source has no pixels to draw yet: an image still loading, or broken; a
61
+ * video without its current frame; a closed `ImageBitmap` or `VideoFrame`; an
62
+ * empty canvas.
63
+ */
64
+ export declare class ImageSourceUnavailableError extends Error {
65
+ constructor(options?: ErrorOptions);
66
+ }
67
+ /**
68
+ * Reads the pixels of an image as `ImageData`, scaled down to fit `maxSize`
69
+ * when it is larger: for analysing an image's colours in a page or a worker
70
+ * without walking all of its pixels. The image is drawn once with `drawImage`
71
+ * on the canvas `createCanvas` returns, which is then read back whole.
72
+ *
73
+ * The pixels are the browser's resampling of the source, converted to the
74
+ * canvas's colour space (the result's `colorSpace`): 8-bit, not premultiplied
75
+ * by alpha. A canvas holds its colours premultiplied, so a translucent pixel's
76
+ * colour comes back quantized; the read is not lossless, even at full size.
77
+ *
78
+ * The source must be ready to draw: await `image.decode()` on an image,
79
+ * `"loadeddata"` on a video. What can be told synchronously is checked — an
80
+ * image not complete or broken, a video without a current frame, a source of no
81
+ * size — and throws; a source the browser cannot draw for another reason reads
82
+ * back transparent.
83
+ *
84
+ * Time and memory are linear in the pixels read, plus the browser's resampling
85
+ * of the source.
86
+ *
87
+ * @example
88
+ * const image = new Image();
89
+ * image.src = url;
90
+ * await image.decode();
91
+ * const imageData = readImageData(
92
+ * (width, height) => new OffscreenCanvas(width, height),
93
+ * image,
94
+ * { maxSize: 80, contextSettings: { colorSpace: "display-p3" } },
95
+ * );
96
+ *
97
+ * @param createCanvas Returns a fresh canvas `width` × `height` pixels large,
98
+ * as `(width, height) => new OffscreenCanvas(width, height)` does. A canvas
99
+ * drawn on before is cleared, and its context's state (transform, clip,
100
+ * compositing) reset, only by assigning its `width` and `height`; and it
101
+ * keeps the colour space of its first context whatever `contextSettings`
102
+ * say.
103
+ * @param source Its own size is read from `naturalWidth` and `naturalHeight`
104
+ * for an image, `videoWidth` and `videoHeight` for a video, `displayWidth`
105
+ * and `displayHeight` for a `VideoFrame`, and `width` and `height`
106
+ * otherwise.
107
+ * @returns `ImageData` of the size `source` was drawn at, in the canvas's
108
+ * colour space.
109
+ * @throws {ImageSourceUnavailableError} When `source` has no pixels to draw
110
+ * yet, before any canvas is created.
111
+ * @throws {RangeError} When `maxSize`, `maxPixels` or `maxSide` is not a
112
+ * positive integer, or the size to draw at exceeds `maxPixels` or `maxSide`;
113
+ * pass a `maxSize`, or raise them, then.
114
+ * @throws {UnsupportedError} When the canvas gives no 2D context.
115
+ * @throws A `DOMException` named `"SecurityError"` when `source` is a
116
+ * cross-origin image loaded without CORS, which the browser does not let a
117
+ * page read.
118
+ */
119
+ export declare function readImageData(createCanvas: Callable<[width: number, height: number], ImageDataCanvas>, source: ImageDataSource, options?: ReadImageDataOptions): ImageData;
120
+ //# sourceMappingURL=read-image-data.d.ts.map