@scrollframe/core 0.0.0-stage → 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Javier Cornejo Leal
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,3 @@
1
- # Temporary Holding Version
1
+ # @scrollframe/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ See the [scrollframe documentation](https://github.com/JavierCornejoLeal/scrollframe#readme).
package/dist/index.cjs ADDED
@@ -0,0 +1,319 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ManifestError: () => ManifestError,
24
+ PROGRESS_CSS_VAR: () => PROGRESS_CSS_VAR,
25
+ ScrollSequence: () => ScrollSequence,
26
+ clamp: () => clamp,
27
+ coarseToFineOrder: () => coarseToFineOrder,
28
+ frameIndexFromProgress: () => frameIndexFromProgress,
29
+ frameUrl: () => frameUrl,
30
+ nearestLoaded: () => nearestLoaded,
31
+ parseManifest: () => parseManifest,
32
+ posterUrl: () => posterUrl,
33
+ progressFromRect: () => progressFromRect,
34
+ selectFrameSet: () => selectFrameSet,
35
+ sortSets: () => sortSets
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/manifest.ts
40
+ var ManifestError = class extends Error {
41
+ name = "ManifestError";
42
+ };
43
+ function isObject(value) {
44
+ return typeof value === "object" && value !== null;
45
+ }
46
+ function isPositiveInt(value) {
47
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
48
+ }
49
+ function parseManifest(input) {
50
+ if (!isObject(input)) throw new ManifestError("Manifest must be an object.");
51
+ if (input.version !== 1) throw new ManifestError(`Unsupported manifest version: ${String(input.version)}.`);
52
+ if (!isPositiveInt(input.frameCount)) throw new ManifestError("`frameCount` must be a positive integer.");
53
+ if (typeof input.baseUrl !== "string") throw new ManifestError("`baseUrl` must be a string.");
54
+ if (typeof input.pattern !== "string" || !input.pattern.includes("{index}")) {
55
+ throw new ManifestError("`pattern` must be a string containing `{index}`.");
56
+ }
57
+ if (typeof input.padding !== "number" || input.padding < 0) throw new ManifestError("`padding` must be >= 0.");
58
+ if (typeof input.poster !== "string") throw new ManifestError("`poster` must be a string.");
59
+ if (!Array.isArray(input.sets) || input.sets.length === 0) throw new ManifestError("`sets` must be a non-empty array.");
60
+ const sets = input.sets.map((set, i) => {
61
+ if (!isObject(set)) throw new ManifestError(`sets[${i}] must be an object.`);
62
+ const { name, maxViewportWidth, width, height, dir } = set;
63
+ if (typeof name !== "string" || typeof dir !== "string") {
64
+ throw new ManifestError(`sets[${i}] needs string \`name\` and \`dir\`.`);
65
+ }
66
+ if (!isPositiveInt(width) || !isPositiveInt(height)) {
67
+ throw new ManifestError(`sets[${i}] needs positive integer \`width\` and \`height\`.`);
68
+ }
69
+ if (maxViewportWidth !== null && !isPositiveInt(maxViewportWidth)) {
70
+ throw new ManifestError(`sets[${i}].maxViewportWidth must be a positive integer or null.`);
71
+ }
72
+ return { name, dir, width, height, maxViewportWidth };
73
+ });
74
+ return {
75
+ version: 1,
76
+ frameCount: input.frameCount,
77
+ baseUrl: input.baseUrl,
78
+ pattern: input.pattern,
79
+ padding: input.padding,
80
+ poster: input.poster,
81
+ sets: sortSets(sets)
82
+ };
83
+ }
84
+ function sortSets(sets) {
85
+ return [...sets].sort((a, b) => (a.maxViewportWidth ?? Infinity) - (b.maxViewportWidth ?? Infinity));
86
+ }
87
+ function selectFrameSet(manifest, viewportWidth) {
88
+ const match = manifest.sets.find((set) => set.maxViewportWidth === null || viewportWidth <= set.maxViewportWidth);
89
+ return match ?? manifest.sets[manifest.sets.length - 1];
90
+ }
91
+ function joinUrl(...parts) {
92
+ return parts.filter((part) => part.length > 0).map((part, i) => i === 0 ? part.replace(/\/+$/, "") : part.replace(/^\/+|\/+$/g, "")).join("/");
93
+ }
94
+ function frameUrl(manifest, set, index, baseUrl = manifest.baseUrl) {
95
+ const file = manifest.pattern.replace("{index}", String(index).padStart(manifest.padding, "0"));
96
+ return joinUrl(baseUrl, set.dir, file);
97
+ }
98
+ function posterUrl(manifest, set, baseUrl = manifest.baseUrl) {
99
+ return joinUrl(baseUrl, set.dir, manifest.poster);
100
+ }
101
+
102
+ // src/math.ts
103
+ function clamp(value, min = 0, max = 1) {
104
+ return Math.min(max, Math.max(min, value));
105
+ }
106
+ function progressFromRect(top, height, viewportHeight) {
107
+ const distance = height - viewportHeight;
108
+ if (distance <= 0) return top <= 0 ? 1 : 0;
109
+ return clamp(-top / distance);
110
+ }
111
+ function frameIndexFromProgress(progress, frameCount) {
112
+ if (frameCount <= 1) return 0;
113
+ return Math.round(clamp(progress) * (frameCount - 1));
114
+ }
115
+ function coarseToFineOrder(frameCount) {
116
+ const order = [];
117
+ const seen = new Uint8Array(frameCount);
118
+ for (let step = 16; step >= 1; step /= 2) {
119
+ for (let i = 0; i < frameCount; i += step) {
120
+ if (!seen[i]) {
121
+ seen[i] = 1;
122
+ order.push(i);
123
+ }
124
+ }
125
+ if (step === 16 && frameCount > 0 && !seen[frameCount - 1]) {
126
+ seen[frameCount - 1] = 1;
127
+ order.push(frameCount - 1);
128
+ }
129
+ }
130
+ return order;
131
+ }
132
+ function nearestLoaded(index, frameCount, isLoaded) {
133
+ for (let offset = 0; offset < frameCount; offset++) {
134
+ const before = index - offset;
135
+ const after = index + offset;
136
+ if (before >= 0 && isLoaded(before)) return before;
137
+ if (after < frameCount && isLoaded(after)) return after;
138
+ }
139
+ return -1;
140
+ }
141
+
142
+ // src/sequence.ts
143
+ var RETRY_DELAYS_MS = [1e3, 2e3, 4e3];
144
+ var PROGRESS_CSS_VAR = "--sf-progress";
145
+ function prefersStaticMedia() {
146
+ if (typeof window === "undefined") return true;
147
+ const reducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
148
+ const connection = navigator.connection;
149
+ return reducedMotion || connection?.saveData === true;
150
+ }
151
+ var ScrollSequence = class {
152
+ options;
153
+ ctx;
154
+ set;
155
+ frames = [];
156
+ generation = 0;
157
+ observer = null;
158
+ rafId = 0;
159
+ drawnIndex = -1;
160
+ ready = false;
161
+ destroyed = false;
162
+ preloading = false;
163
+ started = false;
164
+ /** The section has been near the viewport at least once, so frames are wanted. */
165
+ near = false;
166
+ retries = 0;
167
+ retryTimer;
168
+ constructor(options) {
169
+ this.options = { concurrency: 6, preloadMargin: "100% 0px", ...options };
170
+ this.ctx = options.canvas.getContext("2d");
171
+ this.set = selectFrameSet(options.manifest, window.innerWidth);
172
+ this.applyCanvasSize();
173
+ }
174
+ /** Starts observing. Returns `this` for chaining. Idempotent; no-op under reduced motion / Save-Data. */
175
+ start() {
176
+ if (this.started || this.destroyed || prefersStaticMedia()) return this;
177
+ this.started = true;
178
+ this.observer = new IntersectionObserver(
179
+ (entries) => {
180
+ if (entries.some((entry) => entry.isIntersecting)) {
181
+ this.near = true;
182
+ this.preload();
183
+ }
184
+ },
185
+ { rootMargin: this.options.preloadMargin }
186
+ );
187
+ this.observer.observe(this.options.container);
188
+ window.addEventListener("scroll", this.schedule, { passive: true });
189
+ window.addEventListener("resize", this.handleResize, { passive: true });
190
+ window.addEventListener("online", this.handleOnline);
191
+ this.schedule();
192
+ return this;
193
+ }
194
+ destroy() {
195
+ this.destroyed = true;
196
+ this.generation++;
197
+ this.observer?.disconnect();
198
+ window.removeEventListener("scroll", this.schedule);
199
+ window.removeEventListener("resize", this.handleResize);
200
+ window.removeEventListener("online", this.handleOnline);
201
+ clearTimeout(this.retryTimer);
202
+ cancelAnimationFrame(this.rafId);
203
+ this.releaseFrames();
204
+ }
205
+ get progress() {
206
+ const rect = this.options.container.getBoundingClientRect();
207
+ return progressFromRect(rect.top, rect.height, window.innerHeight);
208
+ }
209
+ applyCanvasSize() {
210
+ this.options.canvas.width = this.set.width;
211
+ this.options.canvas.height = this.set.height;
212
+ }
213
+ releaseFrames() {
214
+ this.frames = [];
215
+ }
216
+ schedule = () => {
217
+ if (this.rafId || this.destroyed) return;
218
+ this.rafId = requestAnimationFrame(() => {
219
+ this.rafId = 0;
220
+ this.render();
221
+ });
222
+ };
223
+ handleResize = () => {
224
+ const next = selectFrameSet(this.options.manifest, window.innerWidth);
225
+ if (next.name !== this.set.name) {
226
+ this.generation++;
227
+ this.releaseFrames();
228
+ this.set = next;
229
+ this.drawnIndex = -1;
230
+ this.preloading = false;
231
+ this.retries = 0;
232
+ clearTimeout(this.retryTimer);
233
+ this.applyCanvasSize();
234
+ if (this.near) this.preload();
235
+ }
236
+ this.schedule();
237
+ };
238
+ handleOnline = () => {
239
+ if (!this.near) return;
240
+ clearTimeout(this.retryTimer);
241
+ this.retries = 0;
242
+ this.preload();
243
+ };
244
+ scheduleRetry() {
245
+ const delay = RETRY_DELAYS_MS[this.retries];
246
+ if (delay === void 0 || this.destroyed) return;
247
+ this.retries++;
248
+ this.retryTimer = setTimeout(() => this.preload(), delay);
249
+ }
250
+ render() {
251
+ const progress = this.progress;
252
+ const { manifest, container, onProgress } = this.options;
253
+ const target = frameIndexFromProgress(progress, manifest.frameCount);
254
+ container.style.setProperty(PROGRESS_CSS_VAR, progress.toFixed(4));
255
+ onProgress?.(progress, target);
256
+ const index = nearestLoaded(target, manifest.frameCount, (i) => this.frames[i] != null);
257
+ if (index === -1 || index === this.drawnIndex || !this.ctx) return;
258
+ const frame = this.frames[index];
259
+ if (!frame) return;
260
+ this.ctx.drawImage(frame, 0, 0, this.set.width, this.set.height);
261
+ this.drawnIndex = index;
262
+ if (!this.ready) {
263
+ this.ready = true;
264
+ this.options.onReady?.();
265
+ }
266
+ }
267
+ preload() {
268
+ if (this.preloading || this.destroyed) return;
269
+ this.preloading = true;
270
+ const generation = this.generation;
271
+ const { manifest, baseUrl, concurrency } = this.options;
272
+ if (this.frames.length !== manifest.frameCount) this.frames = new Array(manifest.frameCount).fill(null);
273
+ const queue = coarseToFineOrder(manifest.frameCount).filter((index) => this.frames[index] == null);
274
+ let failed = 0;
275
+ const worker = async () => {
276
+ for (let index = queue.shift(); index !== void 0; index = queue.shift()) {
277
+ const url = frameUrl(manifest, this.set, index, baseUrl);
278
+ try {
279
+ const frame = await loadFrame(url);
280
+ if (generation !== this.generation) return;
281
+ this.frames[index] = frame;
282
+ this.schedule();
283
+ } catch {
284
+ failed++;
285
+ }
286
+ }
287
+ };
288
+ const workers = Array.from({ length: Math.min(concurrency, queue.length) }, worker);
289
+ void Promise.all(workers).then(() => {
290
+ if (generation !== this.generation) return;
291
+ this.preloading = false;
292
+ if (failed > 0) this.scheduleRetry();
293
+ else this.retries = 0;
294
+ });
295
+ }
296
+ };
297
+ async function loadFrame(url) {
298
+ const image = new Image();
299
+ image.decoding = "async";
300
+ image.src = url;
301
+ await image.decode();
302
+ return image;
303
+ }
304
+ // Annotate the CommonJS export names for ESM import in node:
305
+ 0 && (module.exports = {
306
+ ManifestError,
307
+ PROGRESS_CSS_VAR,
308
+ ScrollSequence,
309
+ clamp,
310
+ coarseToFineOrder,
311
+ frameIndexFromProgress,
312
+ frameUrl,
313
+ nearestLoaded,
314
+ parseManifest,
315
+ posterUrl,
316
+ progressFromRect,
317
+ selectFrameSet,
318
+ sortSets
319
+ });
@@ -0,0 +1,104 @@
1
+ /** One resolution of the sequence (mobile, tablet, desktop...). */
2
+ interface FrameSet {
3
+ name: string;
4
+ /** Largest viewport width (CSS px) this set is meant for. `null` means "no upper limit". */
5
+ maxViewportWidth: number | null;
6
+ width: number;
7
+ height: number;
8
+ /** Folder of this set, relative to the manifest `baseUrl`. */
9
+ dir: string;
10
+ }
11
+ interface SequenceManifest {
12
+ version: 1;
13
+ frameCount: number;
14
+ /** Public URL where the sequence folders are served from, e.g. `/sequence`. */
15
+ baseUrl: string;
16
+ /** File name pattern; `{index}` is replaced by the zero-padded frame index. */
17
+ pattern: string;
18
+ padding: number;
19
+ /** Poster file name inside every set folder (first frame, used as LCP image). */
20
+ poster: string;
21
+ /** Sorted from smallest to largest viewport. */
22
+ sets: FrameSet[];
23
+ }
24
+ declare class ManifestError extends Error {
25
+ name: string;
26
+ }
27
+ /** Validates unknown JSON and returns a typed manifest with sets sorted by viewport. */
28
+ declare function parseManifest(input: unknown): SequenceManifest;
29
+ declare function sortSets(sets: FrameSet[]): FrameSet[];
30
+ /** Picks the first set whose `maxViewportWidth` covers the viewport; falls back to the largest. */
31
+ declare function selectFrameSet(manifest: SequenceManifest, viewportWidth: number): FrameSet;
32
+ declare function frameUrl(manifest: SequenceManifest, set: FrameSet, index: number, baseUrl?: string): string;
33
+ declare function posterUrl(manifest: SequenceManifest, set: FrameSet, baseUrl?: string): string;
34
+
35
+ declare function clamp(value: number, min?: number, max?: number): number;
36
+ /**
37
+ * Scroll progress (0..1) of a tall section whose content is sticky.
38
+ * 0 when the section top reaches the viewport top, 1 when its bottom reaches the viewport bottom.
39
+ */
40
+ declare function progressFromRect(top: number, height: number, viewportHeight: number): number;
41
+ declare function frameIndexFromProgress(progress: number, frameCount: number): number;
42
+ /**
43
+ * Coarse-to-fine load order: every 16th frame first, then every 8th, 4th, 2nd, then the rest.
44
+ * Scrubbing works (at lower temporal resolution) long before every frame is downloaded.
45
+ */
46
+ declare function coarseToFineOrder(frameCount: number): number[];
47
+ /** Closest index (searching both directions) for which `isLoaded` returns true, or -1. */
48
+ declare function nearestLoaded(index: number, frameCount: number, isLoaded: (i: number) => boolean): number;
49
+
50
+ interface ScrollSequenceOptions {
51
+ /** Tall element that defines the scroll distance (its height = scroll length). */
52
+ container: HTMLElement;
53
+ canvas: HTMLCanvasElement;
54
+ manifest: SequenceManifest;
55
+ /** Overrides `manifest.baseUrl` (useful with a CDN). */
56
+ baseUrl?: string;
57
+ /** Parallel image requests while preloading. Default 6. */
58
+ concurrency?: number;
59
+ /** How far before the viewport preloading starts (IntersectionObserver rootMargin). Default "100% 0px". */
60
+ preloadMargin?: string;
61
+ onProgress?: (progress: number, frameIndex: number) => void;
62
+ /** Called once the first sequence frame is painted on the canvas. */
63
+ onReady?: () => void;
64
+ }
65
+ /** Progress is exposed to CSS so overlays can animate without re-rendering any framework. */
66
+ declare const PROGRESS_CSS_VAR = "--sf-progress";
67
+ /**
68
+ * Scroll-scrubbed image sequence painted on a canvas.
69
+ * Nothing is downloaded until the container gets close to the viewport, and only the
70
+ * frame set that matches the current viewport is fetched.
71
+ */
72
+ declare class ScrollSequence {
73
+ private readonly options;
74
+ private readonly ctx;
75
+ private set;
76
+ private frames;
77
+ private generation;
78
+ private observer;
79
+ private rafId;
80
+ private drawnIndex;
81
+ private ready;
82
+ private destroyed;
83
+ private preloading;
84
+ private started;
85
+ /** The section has been near the viewport at least once, so frames are wanted. */
86
+ private near;
87
+ private retries;
88
+ private retryTimer;
89
+ constructor(options: ScrollSequenceOptions);
90
+ /** Starts observing. Returns `this` for chaining. Idempotent; no-op under reduced motion / Save-Data. */
91
+ start(): this;
92
+ destroy(): void;
93
+ get progress(): number;
94
+ private applyCanvasSize;
95
+ private releaseFrames;
96
+ private readonly schedule;
97
+ private readonly handleResize;
98
+ private readonly handleOnline;
99
+ private scheduleRetry;
100
+ private render;
101
+ private preload;
102
+ }
103
+
104
+ export { type FrameSet, ManifestError, PROGRESS_CSS_VAR, ScrollSequence, type ScrollSequenceOptions, type SequenceManifest, clamp, coarseToFineOrder, frameIndexFromProgress, frameUrl, nearestLoaded, parseManifest, posterUrl, progressFromRect, selectFrameSet, sortSets };
@@ -0,0 +1,104 @@
1
+ /** One resolution of the sequence (mobile, tablet, desktop...). */
2
+ interface FrameSet {
3
+ name: string;
4
+ /** Largest viewport width (CSS px) this set is meant for. `null` means "no upper limit". */
5
+ maxViewportWidth: number | null;
6
+ width: number;
7
+ height: number;
8
+ /** Folder of this set, relative to the manifest `baseUrl`. */
9
+ dir: string;
10
+ }
11
+ interface SequenceManifest {
12
+ version: 1;
13
+ frameCount: number;
14
+ /** Public URL where the sequence folders are served from, e.g. `/sequence`. */
15
+ baseUrl: string;
16
+ /** File name pattern; `{index}` is replaced by the zero-padded frame index. */
17
+ pattern: string;
18
+ padding: number;
19
+ /** Poster file name inside every set folder (first frame, used as LCP image). */
20
+ poster: string;
21
+ /** Sorted from smallest to largest viewport. */
22
+ sets: FrameSet[];
23
+ }
24
+ declare class ManifestError extends Error {
25
+ name: string;
26
+ }
27
+ /** Validates unknown JSON and returns a typed manifest with sets sorted by viewport. */
28
+ declare function parseManifest(input: unknown): SequenceManifest;
29
+ declare function sortSets(sets: FrameSet[]): FrameSet[];
30
+ /** Picks the first set whose `maxViewportWidth` covers the viewport; falls back to the largest. */
31
+ declare function selectFrameSet(manifest: SequenceManifest, viewportWidth: number): FrameSet;
32
+ declare function frameUrl(manifest: SequenceManifest, set: FrameSet, index: number, baseUrl?: string): string;
33
+ declare function posterUrl(manifest: SequenceManifest, set: FrameSet, baseUrl?: string): string;
34
+
35
+ declare function clamp(value: number, min?: number, max?: number): number;
36
+ /**
37
+ * Scroll progress (0..1) of a tall section whose content is sticky.
38
+ * 0 when the section top reaches the viewport top, 1 when its bottom reaches the viewport bottom.
39
+ */
40
+ declare function progressFromRect(top: number, height: number, viewportHeight: number): number;
41
+ declare function frameIndexFromProgress(progress: number, frameCount: number): number;
42
+ /**
43
+ * Coarse-to-fine load order: every 16th frame first, then every 8th, 4th, 2nd, then the rest.
44
+ * Scrubbing works (at lower temporal resolution) long before every frame is downloaded.
45
+ */
46
+ declare function coarseToFineOrder(frameCount: number): number[];
47
+ /** Closest index (searching both directions) for which `isLoaded` returns true, or -1. */
48
+ declare function nearestLoaded(index: number, frameCount: number, isLoaded: (i: number) => boolean): number;
49
+
50
+ interface ScrollSequenceOptions {
51
+ /** Tall element that defines the scroll distance (its height = scroll length). */
52
+ container: HTMLElement;
53
+ canvas: HTMLCanvasElement;
54
+ manifest: SequenceManifest;
55
+ /** Overrides `manifest.baseUrl` (useful with a CDN). */
56
+ baseUrl?: string;
57
+ /** Parallel image requests while preloading. Default 6. */
58
+ concurrency?: number;
59
+ /** How far before the viewport preloading starts (IntersectionObserver rootMargin). Default "100% 0px". */
60
+ preloadMargin?: string;
61
+ onProgress?: (progress: number, frameIndex: number) => void;
62
+ /** Called once the first sequence frame is painted on the canvas. */
63
+ onReady?: () => void;
64
+ }
65
+ /** Progress is exposed to CSS so overlays can animate without re-rendering any framework. */
66
+ declare const PROGRESS_CSS_VAR = "--sf-progress";
67
+ /**
68
+ * Scroll-scrubbed image sequence painted on a canvas.
69
+ * Nothing is downloaded until the container gets close to the viewport, and only the
70
+ * frame set that matches the current viewport is fetched.
71
+ */
72
+ declare class ScrollSequence {
73
+ private readonly options;
74
+ private readonly ctx;
75
+ private set;
76
+ private frames;
77
+ private generation;
78
+ private observer;
79
+ private rafId;
80
+ private drawnIndex;
81
+ private ready;
82
+ private destroyed;
83
+ private preloading;
84
+ private started;
85
+ /** The section has been near the viewport at least once, so frames are wanted. */
86
+ private near;
87
+ private retries;
88
+ private retryTimer;
89
+ constructor(options: ScrollSequenceOptions);
90
+ /** Starts observing. Returns `this` for chaining. Idempotent; no-op under reduced motion / Save-Data. */
91
+ start(): this;
92
+ destroy(): void;
93
+ get progress(): number;
94
+ private applyCanvasSize;
95
+ private releaseFrames;
96
+ private readonly schedule;
97
+ private readonly handleResize;
98
+ private readonly handleOnline;
99
+ private scheduleRetry;
100
+ private render;
101
+ private preload;
102
+ }
103
+
104
+ export { type FrameSet, ManifestError, PROGRESS_CSS_VAR, ScrollSequence, type ScrollSequenceOptions, type SequenceManifest, clamp, coarseToFineOrder, frameIndexFromProgress, frameUrl, nearestLoaded, parseManifest, posterUrl, progressFromRect, selectFrameSet, sortSets };
package/dist/index.js ADDED
@@ -0,0 +1,280 @@
1
+ // src/manifest.ts
2
+ var ManifestError = class extends Error {
3
+ name = "ManifestError";
4
+ };
5
+ function isObject(value) {
6
+ return typeof value === "object" && value !== null;
7
+ }
8
+ function isPositiveInt(value) {
9
+ return typeof value === "number" && Number.isInteger(value) && value > 0;
10
+ }
11
+ function parseManifest(input) {
12
+ if (!isObject(input)) throw new ManifestError("Manifest must be an object.");
13
+ if (input.version !== 1) throw new ManifestError(`Unsupported manifest version: ${String(input.version)}.`);
14
+ if (!isPositiveInt(input.frameCount)) throw new ManifestError("`frameCount` must be a positive integer.");
15
+ if (typeof input.baseUrl !== "string") throw new ManifestError("`baseUrl` must be a string.");
16
+ if (typeof input.pattern !== "string" || !input.pattern.includes("{index}")) {
17
+ throw new ManifestError("`pattern` must be a string containing `{index}`.");
18
+ }
19
+ if (typeof input.padding !== "number" || input.padding < 0) throw new ManifestError("`padding` must be >= 0.");
20
+ if (typeof input.poster !== "string") throw new ManifestError("`poster` must be a string.");
21
+ if (!Array.isArray(input.sets) || input.sets.length === 0) throw new ManifestError("`sets` must be a non-empty array.");
22
+ const sets = input.sets.map((set, i) => {
23
+ if (!isObject(set)) throw new ManifestError(`sets[${i}] must be an object.`);
24
+ const { name, maxViewportWidth, width, height, dir } = set;
25
+ if (typeof name !== "string" || typeof dir !== "string") {
26
+ throw new ManifestError(`sets[${i}] needs string \`name\` and \`dir\`.`);
27
+ }
28
+ if (!isPositiveInt(width) || !isPositiveInt(height)) {
29
+ throw new ManifestError(`sets[${i}] needs positive integer \`width\` and \`height\`.`);
30
+ }
31
+ if (maxViewportWidth !== null && !isPositiveInt(maxViewportWidth)) {
32
+ throw new ManifestError(`sets[${i}].maxViewportWidth must be a positive integer or null.`);
33
+ }
34
+ return { name, dir, width, height, maxViewportWidth };
35
+ });
36
+ return {
37
+ version: 1,
38
+ frameCount: input.frameCount,
39
+ baseUrl: input.baseUrl,
40
+ pattern: input.pattern,
41
+ padding: input.padding,
42
+ poster: input.poster,
43
+ sets: sortSets(sets)
44
+ };
45
+ }
46
+ function sortSets(sets) {
47
+ return [...sets].sort((a, b) => (a.maxViewportWidth ?? Infinity) - (b.maxViewportWidth ?? Infinity));
48
+ }
49
+ function selectFrameSet(manifest, viewportWidth) {
50
+ const match = manifest.sets.find((set) => set.maxViewportWidth === null || viewportWidth <= set.maxViewportWidth);
51
+ return match ?? manifest.sets[manifest.sets.length - 1];
52
+ }
53
+ function joinUrl(...parts) {
54
+ return parts.filter((part) => part.length > 0).map((part, i) => i === 0 ? part.replace(/\/+$/, "") : part.replace(/^\/+|\/+$/g, "")).join("/");
55
+ }
56
+ function frameUrl(manifest, set, index, baseUrl = manifest.baseUrl) {
57
+ const file = manifest.pattern.replace("{index}", String(index).padStart(manifest.padding, "0"));
58
+ return joinUrl(baseUrl, set.dir, file);
59
+ }
60
+ function posterUrl(manifest, set, baseUrl = manifest.baseUrl) {
61
+ return joinUrl(baseUrl, set.dir, manifest.poster);
62
+ }
63
+
64
+ // src/math.ts
65
+ function clamp(value, min = 0, max = 1) {
66
+ return Math.min(max, Math.max(min, value));
67
+ }
68
+ function progressFromRect(top, height, viewportHeight) {
69
+ const distance = height - viewportHeight;
70
+ if (distance <= 0) return top <= 0 ? 1 : 0;
71
+ return clamp(-top / distance);
72
+ }
73
+ function frameIndexFromProgress(progress, frameCount) {
74
+ if (frameCount <= 1) return 0;
75
+ return Math.round(clamp(progress) * (frameCount - 1));
76
+ }
77
+ function coarseToFineOrder(frameCount) {
78
+ const order = [];
79
+ const seen = new Uint8Array(frameCount);
80
+ for (let step = 16; step >= 1; step /= 2) {
81
+ for (let i = 0; i < frameCount; i += step) {
82
+ if (!seen[i]) {
83
+ seen[i] = 1;
84
+ order.push(i);
85
+ }
86
+ }
87
+ if (step === 16 && frameCount > 0 && !seen[frameCount - 1]) {
88
+ seen[frameCount - 1] = 1;
89
+ order.push(frameCount - 1);
90
+ }
91
+ }
92
+ return order;
93
+ }
94
+ function nearestLoaded(index, frameCount, isLoaded) {
95
+ for (let offset = 0; offset < frameCount; offset++) {
96
+ const before = index - offset;
97
+ const after = index + offset;
98
+ if (before >= 0 && isLoaded(before)) return before;
99
+ if (after < frameCount && isLoaded(after)) return after;
100
+ }
101
+ return -1;
102
+ }
103
+
104
+ // src/sequence.ts
105
+ var RETRY_DELAYS_MS = [1e3, 2e3, 4e3];
106
+ var PROGRESS_CSS_VAR = "--sf-progress";
107
+ function prefersStaticMedia() {
108
+ if (typeof window === "undefined") return true;
109
+ const reducedMotion = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
110
+ const connection = navigator.connection;
111
+ return reducedMotion || connection?.saveData === true;
112
+ }
113
+ var ScrollSequence = class {
114
+ options;
115
+ ctx;
116
+ set;
117
+ frames = [];
118
+ generation = 0;
119
+ observer = null;
120
+ rafId = 0;
121
+ drawnIndex = -1;
122
+ ready = false;
123
+ destroyed = false;
124
+ preloading = false;
125
+ started = false;
126
+ /** The section has been near the viewport at least once, so frames are wanted. */
127
+ near = false;
128
+ retries = 0;
129
+ retryTimer;
130
+ constructor(options) {
131
+ this.options = { concurrency: 6, preloadMargin: "100% 0px", ...options };
132
+ this.ctx = options.canvas.getContext("2d");
133
+ this.set = selectFrameSet(options.manifest, window.innerWidth);
134
+ this.applyCanvasSize();
135
+ }
136
+ /** Starts observing. Returns `this` for chaining. Idempotent; no-op under reduced motion / Save-Data. */
137
+ start() {
138
+ if (this.started || this.destroyed || prefersStaticMedia()) return this;
139
+ this.started = true;
140
+ this.observer = new IntersectionObserver(
141
+ (entries) => {
142
+ if (entries.some((entry) => entry.isIntersecting)) {
143
+ this.near = true;
144
+ this.preload();
145
+ }
146
+ },
147
+ { rootMargin: this.options.preloadMargin }
148
+ );
149
+ this.observer.observe(this.options.container);
150
+ window.addEventListener("scroll", this.schedule, { passive: true });
151
+ window.addEventListener("resize", this.handleResize, { passive: true });
152
+ window.addEventListener("online", this.handleOnline);
153
+ this.schedule();
154
+ return this;
155
+ }
156
+ destroy() {
157
+ this.destroyed = true;
158
+ this.generation++;
159
+ this.observer?.disconnect();
160
+ window.removeEventListener("scroll", this.schedule);
161
+ window.removeEventListener("resize", this.handleResize);
162
+ window.removeEventListener("online", this.handleOnline);
163
+ clearTimeout(this.retryTimer);
164
+ cancelAnimationFrame(this.rafId);
165
+ this.releaseFrames();
166
+ }
167
+ get progress() {
168
+ const rect = this.options.container.getBoundingClientRect();
169
+ return progressFromRect(rect.top, rect.height, window.innerHeight);
170
+ }
171
+ applyCanvasSize() {
172
+ this.options.canvas.width = this.set.width;
173
+ this.options.canvas.height = this.set.height;
174
+ }
175
+ releaseFrames() {
176
+ this.frames = [];
177
+ }
178
+ schedule = () => {
179
+ if (this.rafId || this.destroyed) return;
180
+ this.rafId = requestAnimationFrame(() => {
181
+ this.rafId = 0;
182
+ this.render();
183
+ });
184
+ };
185
+ handleResize = () => {
186
+ const next = selectFrameSet(this.options.manifest, window.innerWidth);
187
+ if (next.name !== this.set.name) {
188
+ this.generation++;
189
+ this.releaseFrames();
190
+ this.set = next;
191
+ this.drawnIndex = -1;
192
+ this.preloading = false;
193
+ this.retries = 0;
194
+ clearTimeout(this.retryTimer);
195
+ this.applyCanvasSize();
196
+ if (this.near) this.preload();
197
+ }
198
+ this.schedule();
199
+ };
200
+ handleOnline = () => {
201
+ if (!this.near) return;
202
+ clearTimeout(this.retryTimer);
203
+ this.retries = 0;
204
+ this.preload();
205
+ };
206
+ scheduleRetry() {
207
+ const delay = RETRY_DELAYS_MS[this.retries];
208
+ if (delay === void 0 || this.destroyed) return;
209
+ this.retries++;
210
+ this.retryTimer = setTimeout(() => this.preload(), delay);
211
+ }
212
+ render() {
213
+ const progress = this.progress;
214
+ const { manifest, container, onProgress } = this.options;
215
+ const target = frameIndexFromProgress(progress, manifest.frameCount);
216
+ container.style.setProperty(PROGRESS_CSS_VAR, progress.toFixed(4));
217
+ onProgress?.(progress, target);
218
+ const index = nearestLoaded(target, manifest.frameCount, (i) => this.frames[i] != null);
219
+ if (index === -1 || index === this.drawnIndex || !this.ctx) return;
220
+ const frame = this.frames[index];
221
+ if (!frame) return;
222
+ this.ctx.drawImage(frame, 0, 0, this.set.width, this.set.height);
223
+ this.drawnIndex = index;
224
+ if (!this.ready) {
225
+ this.ready = true;
226
+ this.options.onReady?.();
227
+ }
228
+ }
229
+ preload() {
230
+ if (this.preloading || this.destroyed) return;
231
+ this.preloading = true;
232
+ const generation = this.generation;
233
+ const { manifest, baseUrl, concurrency } = this.options;
234
+ if (this.frames.length !== manifest.frameCount) this.frames = new Array(manifest.frameCount).fill(null);
235
+ const queue = coarseToFineOrder(manifest.frameCount).filter((index) => this.frames[index] == null);
236
+ let failed = 0;
237
+ const worker = async () => {
238
+ for (let index = queue.shift(); index !== void 0; index = queue.shift()) {
239
+ const url = frameUrl(manifest, this.set, index, baseUrl);
240
+ try {
241
+ const frame = await loadFrame(url);
242
+ if (generation !== this.generation) return;
243
+ this.frames[index] = frame;
244
+ this.schedule();
245
+ } catch {
246
+ failed++;
247
+ }
248
+ }
249
+ };
250
+ const workers = Array.from({ length: Math.min(concurrency, queue.length) }, worker);
251
+ void Promise.all(workers).then(() => {
252
+ if (generation !== this.generation) return;
253
+ this.preloading = false;
254
+ if (failed > 0) this.scheduleRetry();
255
+ else this.retries = 0;
256
+ });
257
+ }
258
+ };
259
+ async function loadFrame(url) {
260
+ const image = new Image();
261
+ image.decoding = "async";
262
+ image.src = url;
263
+ await image.decode();
264
+ return image;
265
+ }
266
+ export {
267
+ ManifestError,
268
+ PROGRESS_CSS_VAR,
269
+ ScrollSequence,
270
+ clamp,
271
+ coarseToFineOrder,
272
+ frameIndexFromProgress,
273
+ frameUrl,
274
+ nearestLoaded,
275
+ parseManifest,
276
+ posterUrl,
277
+ progressFromRect,
278
+ selectFrameSet,
279
+ sortSets
280
+ };
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@scrollframe/core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Framework-agnostic scroll-driven image sequence engine (canvas, lazy loading, Core Web Vitals friendly).",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/JavierCornejoLeal/scrollframe.git",
9
+ "directory": "packages/core"
10
+ },
11
+ "homepage": "https://github.com/JavierCornejoLeal/scrollframe#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/JavierCornejoLeal/scrollframe/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "main": "./dist/index.cjs",
18
+ "module": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "import": {
23
+ "types": "./dist/index.d.ts",
24
+ "default": "./dist/index.js"
25
+ },
26
+ "require": {
27
+ "types": "./dist/index.d.cts",
28
+ "default": "./dist/index.cjs"
29
+ }
30
+ }
31
+ },
32
+ "files": [
33
+ "dist"
34
+ ],
35
+ "keywords": [
36
+ "scroll",
37
+ "scrollytelling",
38
+ "image-sequence",
39
+ "canvas",
40
+ "storytelling"
41
+ ],
42
+ "scripts": {
43
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
44
+ "typecheck": "tsc --noEmit -p ."
45
+ }
6
46
  }