img-auto-parallax 0.2.0 → 0.2.1

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.
package/dist/define.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { n as defineImgAutoParallax } from "./src-C092I6Rx.mjs";
1
+ import { n as defineImgAutoParallax } from "./src-1sjdGhl1.mjs";
2
2
  // src/define.ts
3
3
  defineImgAutoParallax();
@@ -1,5 +1,25 @@
1
1
  import { n as DepthModelOption, r as DepthModelPreset } from "./models-BeWE4rVt.mjs";
2
2
  import "vgpu";
3
+ /**
4
+ * Where downloaded models are kept across page loads:
5
+ * - `cache-api`: the Cache API (stores the HTTP response; suits large binaries)
6
+ * - `indexeddb`: IndexedDB
7
+ * - `none`: only the browser's HTTP cache (default)
8
+ */
9
+ type ModelCache = 'cache-api' | 'indexeddb' | 'none';
10
+ /**
11
+ * Where estimated depth maps are kept, so a later visit skips the model entirely:
12
+ * - `session`: `sessionStorage`, until the tab closes (~5 MB, a dozen or so images)
13
+ * - `indexeddb`: IndexedDB, until cleared
14
+ * - `none`: recomputed on every page load (default)
15
+ */
16
+ type DepthMapCache = 'session' | 'indexeddb' | 'none';
17
+ /**
18
+ * Remove everything img-auto-parallax stored across page loads: cached models
19
+ * (Cache API and IndexedDB) and depth maps (sessionStorage and IndexedDB).
20
+ * Results already in memory on this page are kept.
21
+ */
22
+ declare function clearCache(): Promise<void>;
3
23
  /** True on devices without a hovering pointer that expose orientation events. */
4
24
  declare function prefersGyro(): boolean;
5
25
  /** Called when `getGyroPermission()` changes, e.g. after a grant or once readings arrive. */
@@ -34,8 +54,20 @@ interface ImgAutoParallaxConfig {
34
54
  model: DepthModelOption;
35
55
  /** Override where ONNX Runtime loads its `.wasm` files from. Only read before the first load. */
36
56
  wasmPaths?: string;
37
- /** Model download progress. */
57
+ /** Model download progress. A model read from `cacheModel` reports once, complete. */
38
58
  onProgress?: (progress: ModelProgress) => void;
59
+ /**
60
+ * Keep downloaded models across page loads: `'cache-api'` (Cache API), `'indexeddb'`,
61
+ * or `'none'` / `false` (default: only the browser's HTTP cache).
62
+ * An element's `cache-model` attribute overrides it.
63
+ */
64
+ cacheModel?: ModelCache | false;
65
+ /**
66
+ * Keep estimated depth maps across page loads, so a later visit shows the effect
67
+ * without loading the model: `'session'` (sessionStorage), `'indexeddb'`,
68
+ * or `'none'` / `false` (default). An element's `cache-depth-map` attribute overrides it.
69
+ */
70
+ cacheDepthMap?: DepthMapCache | false;
39
71
  }
40
72
  /**
41
73
  * Configure the shared runtime. Can be called at any time; changing `model`
@@ -120,6 +152,10 @@ interface ParallaxOptions {
120
152
  layer?: ParallaxLayer;
121
153
  /** Nearness threshold between `layer="foreground"` and `layer="background"` (0–1, default 0.6). */
122
154
  cutoff?: number;
155
+ /** Where the model this element downloads is kept across page loads. Defaults to `configure({ cacheModel })`. */
156
+ cacheModel?: ModelCache | null;
157
+ /** Where this element's estimated depth map is kept across page loads. Defaults to `configure({ cacheDepthMap })`. */
158
+ cacheDepthMap?: DepthMapCache | null;
123
159
  }
124
160
  /** `detail` of the `parallax-error` event. */
125
161
  interface ParallaxErrorDetail {
@@ -180,6 +216,19 @@ declare class ImgAutoParallaxElement extends HTMLElement implements Required<Par
180
216
  set srcDepth(value: string | null | undefined);
181
217
  get model(): string | null;
182
218
  set model(value: string | null);
219
+ /**
220
+ * Where this element keeps the model it downloads across page loads: `cache-api`
221
+ * (Cache API), `indexeddb` or `none`. Defaults to `configure({ cacheModel })`.
222
+ */
223
+ get cacheModel(): ModelCache | null;
224
+ set cacheModel(value: ModelCache | null);
225
+ /**
226
+ * Where this element keeps its estimated depth map across page loads, so a later
227
+ * visit needs no model: `session` (sessionStorage), `indexeddb` or `none`.
228
+ * Defaults to `configure({ cacheDepthMap })`. Ignored with `src-depth`.
229
+ */
230
+ get cacheDepthMap(): DepthMapCache | null;
231
+ set cacheDepthMap(value: DepthMapCache | null);
183
232
  /** Maximum displacement as a fraction of the image height (0–0.3, default 0.03). */
184
233
  get strength(): number;
185
234
  set strength(value: number);
@@ -237,4 +286,4 @@ declare class ImgAutoParallaxElement extends HTMLElement implements Required<Par
237
286
  disconnectedCallback(): void;
238
287
  attributeChangedCallback(name: string, old: string | null, value: string | null): void;
239
288
  }
240
- export { GyroPermission as _, ParallaxIdle as a, prefersGyro as b, ParallaxState as c, ImgAutoParallaxConfig as d, ModelProgress as f, preload as g, isSupported as h, ParallaxErrorDetail as i, ParallaxTrigger as l, hasWebGpu as m, ImgAutoParallaxElement as n, ParallaxLayer as o, configure as p, ImgAutoParallaxEventMap as r, ParallaxOptions as s, DEFAULTS as t, ParallaxView as u, getGyroPermission as v, requestGyroPermission as x, onGyroPermissionChange as y };
289
+ export { ModelCache as C, DepthMapCache as S, GyroPermission as _, ParallaxIdle as a, prefersGyro as b, ParallaxState as c, ImgAutoParallaxConfig as d, ModelProgress as f, preload as g, isSupported as h, ParallaxErrorDetail as i, ParallaxTrigger as l, hasWebGpu as m, ImgAutoParallaxElement as n, ParallaxLayer as o, configure as p, ImgAutoParallaxEventMap as r, ParallaxOptions as s, DEFAULTS as t, ParallaxView as u, getGyroPermission as v, clearCache as w, requestGyroPermission as x, onGyroPermissionChange as y };
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { _ as GyroPermission, a as ParallaxIdle, b as prefersGyro, c as ParallaxState, d as ImgAutoParallaxConfig, f as ModelProgress, g as preload, h as isSupported, i as ParallaxErrorDetail, l as ParallaxTrigger, m as hasWebGpu, n as ImgAutoParallaxElement, o as ParallaxLayer, p as configure, r as ImgAutoParallaxEventMap, s as ParallaxOptions, t as DEFAULTS, u as ParallaxView, v as getGyroPermission, x as requestGyroPermission, y as onGyroPermissionChange } from "./element-DDl79CEt.mjs";
1
+ import { C as ModelCache, S as DepthMapCache, _ as GyroPermission, a as ParallaxIdle, b as prefersGyro, c as ParallaxState, d as ImgAutoParallaxConfig, f as ModelProgress, g as preload, h as isSupported, i as ParallaxErrorDetail, l as ParallaxTrigger, m as hasWebGpu, n as ImgAutoParallaxElement, o as ParallaxLayer, p as configure, r as ImgAutoParallaxEventMap, s as ParallaxOptions, t as DEFAULTS, u as ParallaxView, v as getGyroPermission, w as clearCache, x as requestGyroPermission, y as onGyroPermissionChange } from "./element-Q75M2zZ8.mjs";
2
2
  import { a as MODEL_PRESETS, i as DepthModelSpec, n as DepthModelOption, o as listModels, r as DepthModelPreset, s as registerModel, t as DEFAULT_MODEL } from "./models-BeWE4rVt.mjs";
3
3
  export declare const DEFAULT_TAG = "img-auto-parallax";
4
4
  /**
@@ -11,4 +11,4 @@ declare global {
11
11
  'img-auto-parallax': ImgAutoParallaxElement;
12
12
  }
13
13
  }
14
- export { DEFAULTS, DEFAULT_MODEL, type DepthModelOption, type DepthModelPreset, type DepthModelSpec, type GyroPermission, type ImgAutoParallaxConfig, ImgAutoParallaxElement, type ImgAutoParallaxEventMap, MODEL_PRESETS, type ModelProgress, type ParallaxErrorDetail, type ParallaxIdle, type ParallaxLayer, type ParallaxOptions, type ParallaxState, type ParallaxTrigger, type ParallaxView, configure, getGyroPermission, hasWebGpu, isSupported, listModels, onGyroPermissionChange, prefersGyro, preload, registerModel, requestGyroPermission };
14
+ export { DEFAULTS, DEFAULT_MODEL, type DepthMapCache, type DepthModelOption, type DepthModelPreset, type DepthModelSpec, type GyroPermission, type ImgAutoParallaxConfig, ImgAutoParallaxElement, type ImgAutoParallaxEventMap, MODEL_PRESETS, type ModelCache, type ModelProgress, type ParallaxErrorDetail, type ParallaxIdle, type ParallaxLayer, type ParallaxOptions, type ParallaxState, type ParallaxTrigger, type ParallaxView, clearCache, configure, getGyroPermission, hasWebGpu, isSupported, listModels, onGyroPermissionChange, prefersGyro, preload, registerModel, requestGyroPermission };
package/dist/index.mjs CHANGED
@@ -1,3 +1,3 @@
1
- import { a as configure, c as preload, d as prefersGyro, f as requestGyroPermission, i as ImgAutoParallaxElement, l as getGyroPermission, n as defineImgAutoParallax, o as hasWebGpu, r as DEFAULTS, s as isSupported, t as DEFAULT_TAG, u as onGyroPermissionChange } from "./src-C092I6Rx.mjs";
2
- import { i as registerModel, n as MODEL_PRESETS, r as listModels, t as DEFAULT_MODEL } from "./models-BmGGoJKs.mjs";
3
- export { DEFAULTS, DEFAULT_MODEL, DEFAULT_TAG, ImgAutoParallaxElement, MODEL_PRESETS, configure, defineImgAutoParallax, getGyroPermission, hasWebGpu, isSupported, listModels, onGyroPermissionChange, prefersGyro, preload, registerModel, requestGyroPermission };
1
+ import { h as clearCache, i as registerModel, n as MODEL_PRESETS, r as listModels, t as DEFAULT_MODEL } from "./models-X3MUVk-z.mjs";
2
+ import { a as configure, c as preload, d as prefersGyro, f as requestGyroPermission, i as ImgAutoParallaxElement, l as getGyroPermission, n as defineImgAutoParallax, o as hasWebGpu, r as DEFAULTS, s as isSupported, t as DEFAULT_TAG, u as onGyroPermissionChange } from "./src-1sjdGhl1.mjs";
3
+ export { DEFAULTS, DEFAULT_MODEL, DEFAULT_TAG, ImgAutoParallaxElement, MODEL_PRESETS, clearCache, configure, defineImgAutoParallax, getGyroPermission, hasWebGpu, isSupported, listModels, onGyroPermissionChange, prefersGyro, preload, registerModel, requestGyroPermission };
package/dist/internal.mjs CHANGED
@@ -1 +1 @@
1
- export { t as DEFAULT_MODEL, o as MAX_COLOUR_SIDE, f as depthMapPath, c as fitWithin, l as inferenceSize, p as jointBilateralUpsample, m as nearnessToRgba, h as normalizeDepth, g as resizeRgba, a as resolveModel, d as rgbaToNchw } from "./models-BmGGoJKs.mjs";
1
+ export { t as DEFAULT_MODEL, o as MAX_COLOUR_SIDE, x as depthMapPath, c as fitWithin, l as inferenceSize, S as jointBilateralUpsample, C as nearnessToRgba, w as normalizeDepth, T as resizeRgba, a as resolveModel, f as rgbaToNchw } from "./models-X3MUVk-z.mjs";
@@ -147,6 +147,187 @@ function jointBilateralUpsample(low, lw, lh, rgba, hw, hh) {
147
147
  }
148
148
  return high;
149
149
  }
150
+ // src/storage.ts
151
+ const MODEL_CACHES = [
152
+ "cache-api",
153
+ "indexeddb",
154
+ "none"
155
+ ];
156
+ const DEPTH_MAP_CACHES = [
157
+ "session",
158
+ "indexeddb",
159
+ "none"
160
+ ];
161
+ const NAME = "img-auto-parallax";
162
+ /** Bump when the stored depth format or its meaning changes. */
163
+ const DEPTH_VERSION = 1;
164
+ const SESSION_PREFIX = `${NAME}:depth:`;
165
+ const MODELS = "models";
166
+ const DEPTH_MAPS = "depth-maps";
167
+ let database;
168
+ function openDatabase() {
169
+ database ??= new Promise((resolve, reject) => {
170
+ const request = indexedDB.open(NAME, 1);
171
+ request.onupgradeneeded = () => {
172
+ for (const store of [MODELS, DEPTH_MAPS]) if (!request.result.objectStoreNames.contains(store)) request.result.createObjectStore(store);
173
+ };
174
+ request.onsuccess = () => resolve(request.result);
175
+ request.onerror = () => reject(request.error);
176
+ request.onblocked = () => reject(/* @__PURE__ */ new Error("IndexedDB is blocked."));
177
+ });
178
+ database.catch(() => {
179
+ database = void 0;
180
+ });
181
+ return database;
182
+ }
183
+ async function idb(store, mode, run) {
184
+ const db = await openDatabase();
185
+ return new Promise((resolve, reject) => {
186
+ const request = run(db.transaction(store, mode).objectStore(store));
187
+ request.onsuccess = () => resolve(request.result);
188
+ request.onerror = () => reject(request.error);
189
+ });
190
+ }
191
+ /** Header holding the source URL of a model stored in the Cache API. */
192
+ const MODEL_URL_HEADER = "x-img-auto-parallax-url";
193
+ /**
194
+ * Each model has one slot (its name), holding the bytes and the URL they came from.
195
+ * A new version has a new URL (bundlers hash file names): it misses, downloads,
196
+ * and overwrites the slot, so outdated copies never pile up.
197
+ * The Cache API keys requests by URL, so a slot is a same-origin path no server sees.
198
+ */
199
+ function slotUrl(slot) {
200
+ return new URL(`/__${NAME}/models/${encodeURIComponent(slot)}`, location.origin).href;
201
+ }
202
+ /** The model stored in `slot`, if it is the copy of `url`. */
203
+ async function readModel(cache, slot, url) {
204
+ try {
205
+ if (cache === "cache-api") {
206
+ const response = await (await caches.open(NAME)).match(slotUrl(slot));
207
+ return response?.headers.get(MODEL_URL_HEADER) === url ? new Uint8Array(await response.arrayBuffer()) : void 0;
208
+ }
209
+ if (cache === "indexeddb") {
210
+ const value = await idb(MODELS, "readonly", (store) => store.get(slot));
211
+ return value?.url === url && value.bytes instanceof Uint8Array ? value.bytes : void 0;
212
+ }
213
+ } catch {}
214
+ }
215
+ /** Keep the model from `url` in `slot` for later page loads, replacing any older copy. Never throws. */
216
+ async function writeModel(cache, slot, url, bytes) {
217
+ if (cache === "none") return;
218
+ const copy = bytes.slice();
219
+ try {
220
+ if (cache === "cache-api") await (await caches.open(NAME)).put(slotUrl(slot), new Response(copy, { headers: {
221
+ "content-type": "application/octet-stream",
222
+ "content-length": String(copy.byteLength),
223
+ [MODEL_URL_HEADER]: url
224
+ } }));
225
+ else if (cache === "indexeddb") {
226
+ const value = {
227
+ url,
228
+ bytes: copy
229
+ };
230
+ await idb(MODELS, "readwrite", (store) => store.put(value, slot));
231
+ }
232
+ } catch {}
233
+ }
234
+ /** 0..1 nearness to the stored 8-bit form. */
235
+ function quantizeNearness(nearness, width, height) {
236
+ const data = new Uint8Array(width * height);
237
+ for (let i = 0; i < data.length; i++) data[i] = Math.round(Math.min(1, Math.max(0, nearness[i] ?? 0)) * 255);
238
+ return {
239
+ width,
240
+ height,
241
+ data
242
+ };
243
+ }
244
+ /** The stored 8-bit form back to 0..1 nearness. */
245
+ function dequantizeNearness(map) {
246
+ const out = new Float32Array(map.data.length);
247
+ for (let i = 0; i < out.length; i++) out[i] = map.data[i] / 255;
248
+ return out;
249
+ }
250
+ function isStoredDepthMap(value) {
251
+ const map = value;
252
+ return !!map && Number.isInteger(map.width) && Number.isInteger(map.height) && map.width > 0 && map.height > 0 && map.data instanceof Uint8Array && map.data.length === map.width * map.height;
253
+ }
254
+ function toBase64(bytes) {
255
+ let binary = "";
256
+ for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
257
+ return btoa(binary);
258
+ }
259
+ function fromBase64(text) {
260
+ const binary = atob(text);
261
+ const bytes = new Uint8Array(binary.length);
262
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
263
+ return bytes;
264
+ }
265
+ function depthKey(key) {
266
+ return `v${DEPTH_VERSION} ${key}`;
267
+ }
268
+ /** The depth map stored for `key` (model, resolution and image URL), if any. */
269
+ async function readDepthMap(cache, key) {
270
+ try {
271
+ if (cache === "session") {
272
+ const text = sessionStorage.getItem(SESSION_PREFIX + depthKey(key));
273
+ if (!text) return void 0;
274
+ const { width, height, data } = JSON.parse(text);
275
+ const map = {
276
+ width,
277
+ height,
278
+ data: fromBase64(data)
279
+ };
280
+ return isStoredDepthMap(map) ? map : void 0;
281
+ }
282
+ if (cache === "indexeddb") {
283
+ const value = await idb(DEPTH_MAPS, "readonly", (store) => store.get(depthKey(key)));
284
+ return isStoredDepthMap(value) ? value : void 0;
285
+ }
286
+ } catch {}
287
+ }
288
+ /** Keep a depth map for later page loads. Never throws. */
289
+ async function writeDepthMap(cache, key, map) {
290
+ try {
291
+ if (cache === "session") {
292
+ const name = SESSION_PREFIX + depthKey(key);
293
+ const text = JSON.stringify({
294
+ width: map.width,
295
+ height: map.height,
296
+ data: toBase64(map.data)
297
+ });
298
+ try {
299
+ sessionStorage.setItem(name, text);
300
+ } catch {
301
+ clearSessionDepthMaps();
302
+ sessionStorage.setItem(name, text);
303
+ }
304
+ } else if (cache === "indexeddb") await idb(DEPTH_MAPS, "readwrite", (store) => store.put(map, depthKey(key)));
305
+ } catch {}
306
+ }
307
+ function clearSessionDepthMaps() {
308
+ const keys = [];
309
+ for (let i = 0; i < sessionStorage.length; i++) {
310
+ const name = sessionStorage.key(i);
311
+ if (name?.startsWith(SESSION_PREFIX)) keys.push(name);
312
+ }
313
+ for (const name of keys) sessionStorage.removeItem(name);
314
+ }
315
+ /**
316
+ * Remove everything img-auto-parallax stored across page loads: cached models
317
+ * (Cache API and IndexedDB) and depth maps (sessionStorage and IndexedDB).
318
+ * Results already in memory on this page are kept.
319
+ */
320
+ async function clearCache() {
321
+ try {
322
+ clearSessionDepthMaps();
323
+ } catch {}
324
+ try {
325
+ if (typeof caches !== "undefined") await caches.delete(NAME);
326
+ } catch {}
327
+ try {
328
+ if (typeof indexedDB !== "undefined") await Promise.all([MODELS, DEPTH_MAPS].map((store) => idb(store, "readwrite", (s) => s.clear())));
329
+ } catch {}
330
+ }
150
331
  // src/preprocess.ts
151
332
  const IMAGENET_MEAN = [
152
333
  .485,
@@ -236,20 +417,37 @@ function createPreprocessor() {
236
417
  };
237
418
  }
238
419
  let precompiledScratch;
239
- /** Colour at display size plus a decoded depth map (red channel, near = bright). */
240
- function readPrecompiled(source, depthMap) {
241
- precompiledScratch ??= {
420
+ function getPrecompiledScratch() {
421
+ return precompiledScratch ??= {
242
422
  display: createScratch(),
243
423
  depth: createScratch()
244
424
  };
425
+ }
426
+ /** Colour at display size, as kept on the GPU. */
427
+ function readColour(source) {
245
428
  const [width, height] = sourceSize(source);
246
429
  if (!width || !height) throw new Error("[img-auto-parallax] source has no intrinsic size.");
247
430
  const colourSize = fitWithin(width, height, MAX_COLOUR_SIDE);
248
- const rgba = drawScaled(precompiledScratch.display, source, colourSize[0], colourSize[1]);
431
+ return {
432
+ rgba: drawScaled(getPrecompiledScratch().display, source, colourSize[0], colourSize[1]),
433
+ colourSize
434
+ };
435
+ }
436
+ /** Colour at display size plus a depth map stored by `cache-depth-map`. */
437
+ function readStored(source, map) {
438
+ return {
439
+ ...readColour(source),
440
+ nearness: dequantizeNearness(map),
441
+ depthSize: [map.width, map.height]
442
+ };
443
+ }
444
+ /** Colour at display size plus a decoded depth map (red channel, near = bright). */
445
+ function readPrecompiled(source, depthMap) {
446
+ const { rgba, colourSize } = readColour(source);
249
447
  const [dw, dh] = sourceSize(depthMap);
250
448
  if (!dw || !dh) throw new Error("[img-auto-parallax] depth map has no intrinsic size.");
251
449
  return {
252
- nearness: rgbaToNearness(drawScaled(precompiledScratch.depth, depthMap, dw, dh), dw * dh),
450
+ nearness: rgbaToNearness(drawScaled(getPrecompiledScratch().depth, depthMap, dw, dh), dw * dh),
253
451
  depthSize: [dw, dh],
254
452
  rgba,
255
453
  colourSize
@@ -326,4 +524,4 @@ function resolveModel(option, supportsF16) {
326
524
  if (spec.requiresF16 && !supportsF16 && spec.fallback) return spec.fallback;
327
525
  return spec;
328
526
  }
329
- export { resolveModel as a, fitWithin as c, rgbaToNchw as d, depthMapPath as f, resizeRgba as g, normalizeDepth as h, registerModel as i, inferenceSize as l, nearnessToRgba as m, MODEL_PRESETS as n, MAX_COLOUR_SIDE as o, jointBilateralUpsample as p, listModels as r, createPreprocessor as s, DEFAULT_MODEL as t, readPrecompiled as u };
527
+ export { nearnessToRgba as C, jointBilateralUpsample as S, resizeRgba as T, readDepthMap as _, resolveModel as a, writeModel as b, fitWithin as c, readStored as d, rgbaToNchw as f, quantizeNearness as g, clearCache as h, registerModel as i, inferenceSize as l, MODEL_CACHES as m, MODEL_PRESETS as n, MAX_COLOUR_SIDE as o, DEPTH_MAP_CACHES as p, listModels as r, createPreprocessor as s, DEFAULT_MODEL as t, readPrecompiled as u, readModel as v, normalizeDepth as w, depthMapPath as x, writeDepthMap as y };