@cosmictraveler002/anim-kit 1.3.0 → 1.4.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.
@@ -6,7 +6,8 @@
6
6
  * The core barrel (`@cosmictraveler002/anim-kit`) never imports three, so
7
7
  * plain DOM/scroll users keep a gsap+lenis-only dependency tree.
8
8
  *
9
- * import { webglMedia } from "@cosmictraveler002/anim-kit/three";
9
+ * import { webglMedia, glRail } from "@cosmictraveler002/anim-kit/three";
10
10
  */
11
11
  export { webglMedia } from "./webgl-media.js";
12
+ export { glRail } from "./gl-rail.js";
12
13
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/three/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/three/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,EAAE,UAAU,EAAE,MAAM,kBAAkB,CAAC;AAE9C,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cosmictraveler002/anim-kit",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Modular, framework-agnostic animation library — GSAP + ScrollTrigger + Lenis effects packaged as composable ES modules.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Drag rail — the bounded, inertia-driven horizontal rail.
2
+ * Drag rail — the bounded, inertia-driven rail (horizontal or vertical).
3
3
  *
4
4
  * A grab-and-throw rail with real physics, extracted from the drag-driven
5
5
  * portfolio rail pattern: pointer drag, wheel and trackpad all feed one
@@ -29,11 +29,18 @@
29
29
  * - **Velocity-reactive items.** `tilt` rotates children proportionally to the
30
30
  * rendered per-frame velocity (the cards lean into motion and spring flat at
31
31
  * rest); `onTick` exposes pos/velocity for WebGL or custom consumers.
32
+ * - **Two axes.** `axis: "x"` (default), `"y"`, or `"auto"` — under `auto`
33
+ * the *layout* decides via `resolveRailAxis()` (only the column overflows →
34
+ * vertical, otherwise horizontal; the same rule glRail uses to pick its
35
+ * bend axis). touch-action claims the rail's own gesture axis (`pan-y` for
36
+ * a horizontal rail, `pan-x` for a vertical one) so the page never fights
37
+ * the rail for a swipe, and a mid-life flip re-keys the transform instead
38
+ * of leaving the stale axis behind.
32
39
  * - **Fidelity.** `destroy()` removes every listener + the ticker, kills the
33
40
  * tilt state and restores the inline cursor/user-select/touch-action the
34
41
  * effect had overwritten.
35
42
  *
36
- * dragRail(".ak-rail-track", { tilt: 0.05 })
43
+ * dragRail(".ak-rail-track", { tilt: 0.05, axis: "auto" })
37
44
  *
38
45
  * CSS: viewport `overflow: hidden`; track `display: flex; width: max-content;
39
46
  * gap: 1rem; cursor: grab; user-select: none; touch-action: pan-y`.
@@ -46,6 +53,8 @@ import type { CommonOptions, Destroy, TargetLike } from "../core/types.js";
46
53
  export interface DragRailOptions extends CommonOptions {
47
54
  /** Scroll viewport around the track — defaults to `track.parentElement`. */
48
55
  viewport?: TargetLike;
56
+ /** Motion axis — `"auto"` flips vertical when only the column overflows. @default `"x"` */
57
+ axis?: "x" | "y" | "auto";
49
58
  /** Children that tilt with velocity. @default `":scope > *"` */
50
59
  item?: string;
51
60
  /** Follow speed toward the intent, per 60fps frame (0..1). @default 0.1 */
@@ -60,10 +69,26 @@ export interface DragRailOptions extends CommonOptions {
60
69
  tilt?: number;
61
70
  /** Tilt clamp, degrees. @default 8 */
62
71
  tiltMax?: number;
63
- /** `(pos, velocity) => {}` called every rendered frame while mounted. */
72
+ /** `(pos, velocity) => {}` called every rendered frame while mounted (pos along the active axis). */
64
73
  onTick?: (pos: number, velocity: number) => void;
65
74
  }
66
75
 
76
+ /**
77
+ * The axis rule shared by `dragRail` and `glRail`: fixed when asked, otherwise
78
+ * the layout decides — a rail only runs vertical when the *column* overflows
79
+ * and the row doesn't (a mobile stack), everything else is horizontal.
80
+ */
81
+ export function resolveRailAxis(
82
+ track: HTMLElement,
83
+ viewport: HTMLElement,
84
+ pref: "x" | "y" | "auto",
85
+ ): "x" | "y" {
86
+ if (pref !== "auto") return pref;
87
+ const overflowY = track.scrollHeight - viewport.clientHeight;
88
+ const overflowX = track.scrollWidth - viewport.clientWidth;
89
+ return overflowY > 0 && overflowX <= 0 ? "y" : "x";
90
+ }
91
+
67
92
  export function dragRail(target: TargetLike, options: DragRailOptions = {}): Destroy {
68
93
  initGSAP();
69
94
 
@@ -72,6 +97,7 @@ export function dragRail(target: TargetLike, options: DragRailOptions = {}): Des
72
97
 
73
98
  const {
74
99
  viewport,
100
+ axis: axisOpt = "x",
75
101
  item = ":scope > *",
76
102
  lerp = 0.1,
77
103
  edge = 140,
@@ -92,14 +118,26 @@ export function dragRail(target: TargetLike, options: DragRailOptions = {}): Des
92
118
 
93
119
  /* ---------------- bounds ---------------- */
94
120
 
95
- let min = 0; // most-negative resting x (content overflows left)
121
+ let axis: "x" | "y" = resolveRailAxis(track, vp, axisOpt);
122
+ let flipped = false; // axis changed mid-life → force a transform re-key
123
+ let min = 0; // most-negative resting position (content overflows)
96
124
  let max = 0; // start of the rail
97
- let pos = 0; // rendered x
98
- let intent = 0; // wanted x (drag/wheel/throw feed this)
125
+ let pos = 0; // rendered position
126
+ let intent = 0; // wanted position (drag/wheel/throw feed this)
99
127
 
100
128
  const measure = () => {
101
- const overflow = Math.max(0, track.scrollWidth - vp.clientWidth);
102
- min = -overflow;
129
+ const next = resolveRailAxis(track, vp, axisOpt);
130
+ if (next !== axis) {
131
+ axis = next;
132
+ flipped = true;
133
+ // Claim the rail's own gesture axis; the other one belongs to the page.
134
+ track.style.touchAction = axis === "x" ? "pan-y" : "pan-x";
135
+ }
136
+ const overflow =
137
+ axis === "x"
138
+ ? track.scrollWidth - vp.clientWidth
139
+ : track.scrollHeight - vp.clientHeight;
140
+ min = -Math.max(0, overflow);
103
141
  max = 0;
104
142
  // Fold an out-of-range position back through the soft edge (no jump).
105
143
  intent = soft(intent);
@@ -116,14 +154,17 @@ export function dragRail(target: TargetLike, options: DragRailOptions = {}): Des
116
154
  /* ---------------- pointer drag ---------------- */
117
155
 
118
156
  let dragging = false;
119
- let lastX = 0;
157
+ let last = 0; // last pointer coordinate along the active axis
120
158
  let velocity = 0; // smoothed pointer delta (px/frame-ish)
121
159
  let renderedVel = 0; // rendered per-frame velocity (drives tilt/onTick)
122
160
 
161
+ const along = (e: { clientX: number; clientY: number }) =>
162
+ axis === "x" ? e.clientX : e.clientY;
163
+
123
164
  const onPointerDown = (e: PointerEvent) => {
124
165
  if (e.pointerType === "mouse" && e.button !== 0) return;
125
166
  dragging = true;
126
- lastX = e.clientX;
167
+ last = along(e);
127
168
  velocity = 0;
128
169
  try {
129
170
  vp.setPointerCapture(e.pointerId);
@@ -135,10 +176,10 @@ export function dragRail(target: TargetLike, options: DragRailOptions = {}): Des
135
176
 
136
177
  const onPointerMove = (e: PointerEvent) => {
137
178
  if (!dragging) return;
138
- const dx = e.clientX - lastX;
139
- lastX = e.clientX;
140
- velocity = velocity * 0.7 + dx * 0.3; // smooth out event-rate jitter
141
- intent = soft(intent + dx);
179
+ const delta = along(e) - last;
180
+ last = along(e);
181
+ velocity = velocity * 0.7 + delta * 0.3; // smooth out event-rate jitter
182
+ intent = soft(intent + delta);
142
183
  };
143
184
 
144
185
  const endDrag = (e?: PointerEvent) => {
@@ -164,7 +205,13 @@ export function dragRail(target: TargetLike, options: DragRailOptions = {}): Des
164
205
 
165
206
  const onWheel = (e: WheelEvent) => {
166
207
  if (!wheel) return;
167
- const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
208
+ const delta =
209
+ axis === "x"
210
+ ? Math.abs(e.deltaX) > Math.abs(e.deltaY)
211
+ ? e.deltaX
212
+ : e.deltaY
213
+ : e.deltaY;
214
+ if (!delta) return;
168
215
  const bound = delta > 0 ? max : min;
169
216
  const outward = (intent - bound) * (delta > 0 ? 1 : -1);
170
217
  if (outward > edge) return; // over-extended — hand the scroll back to the page
@@ -188,8 +235,10 @@ export function dragRail(target: TargetLike, options: DragRailOptions = {}): Des
188
235
  const prev = pos;
189
236
  pos += (intent - pos) * Math.min(1, lerp * ratio);
190
237
  renderedVel = pos - prev;
191
- if (renderedVel === 0 && pos === intent) return; // idle: skip the write
192
- gsap.set(track, { x: pos });
238
+ if (renderedVel === 0 && pos === intent && !flipped) return; // idle: skip the write
239
+ flipped = false;
240
+ // Re-key both axes: a flip must clear the stale one, never leave it behind.
241
+ gsap.set(track, axis === "x" ? { x: pos, y: 0 } : { x: 0, y: pos });
193
242
  if (items.length) {
194
243
  gsap.set(items, {
195
244
  rotation: gsap.utils.clamp(-tiltMax, tiltMax, renderedVel * tilt),
@@ -204,7 +253,7 @@ export function dragRail(target: TargetLike, options: DragRailOptions = {}): Des
204
253
  track.dataset.akRail = "true";
205
254
  track.style.cursor = "grab";
206
255
  track.style.userSelect = "none";
207
- track.style.touchAction = "pan-y";
256
+ track.style.touchAction = axis === "x" ? "pan-y" : "pan-x";
208
257
 
209
258
  vp.addEventListener("pointerdown", onPointerDown);
210
259
  vp.addEventListener("pointermove", onPointerMove);
@@ -0,0 +1,437 @@
1
+ /**
2
+ * GL rail — the WebGL overlay rail: physics below, bent cards above.
3
+ *
4
+ * `dragRail` owns the motion (intent/pos ticker, tanh rubber-band, throw
5
+ * momentum, Lenis-safe wheel, auto axis); this effect adds the GPU layer the
6
+ * flat DOM can't draw: every card re-rendered onto **one fixed canvas** whose
7
+ * surfaces bend around an invisible cylinder, over a perspective grid floor.
8
+ * Why it is shaped this way (audit notes):
9
+ *
10
+ * - **The DOM stays the source of truth.** Cards keep owning layout, labels,
11
+ * hit areas and alt text; each frame reads their viewport rects and the
12
+ * shader re-creates the pixels *beneath* the labels. A label never drifts
13
+ * off its card, because the card **is** the rect the label sits in — only
14
+ * the picture curves.
15
+ * - **The bend lives in the vertex shader.** Each vertex takes its offset
16
+ * along the rail axis (`uOffset + local`), maps it onto a cylinder of
17
+ * `uRadius` (`a = o / R`, `x = R·sin a`, `z = −R·(1−cos a)`) and re-centres
18
+ * so the card's middle stays glued to its DOM position while its edges
19
+ * foreshorten onto the curve. One uniform per card, no per-vertex CPU work
20
+ * — and the rotation the cards need arrives free from the bend itself.
21
+ * - **One renderer for the whole rail.** A single alpha canvas inserted
22
+ * *under* the track (the track's transform creates a stacking context that
23
+ * paints above it): labels stay DOM, card backgrounds stay transparent, and
24
+ * the only pixels the canvas needs are the `<img>`s it hides — each one
25
+ * only after its texture has actually loaded.
26
+ * - **The axis follows the layout.** `axis: "auto"` hands the same
27
+ * `resolveRailAxis()` rule to the physics *and* the bend: row overflows →
28
+ * horizontal rail + bend around Y, only the column overflows (mobile
29
+ * stack) → vertical rail + bend around X. One init serves both.
30
+ * - **Silent no-op ladder.** Missing target → no-op. No
31
+ * `WebGLRenderingContext` (jsdom, SSR, WebGL-disabled browsers) → the flat
32
+ * `dragRail` rail alone, *before* any context is requested (a probe call
33
+ * would itself log). Renderer construction throws → flat rail. Texture 404
34
+ * → that one card's `<img>` stays visible. Under `prefers-reduced-motion`
35
+ * nothing mounts at all (the outer `guard` owns that decision). Nothing
36
+ * ever logs.
37
+ * - **Fidelity.** `destroy()` unwinds the physics, then the GPU: ticker,
38
+ * observers, geometry, materials, textures and the renderer are disposed,
39
+ * the canvas is removed and image opacities + the stage's inline position
40
+ * are restored.
41
+ *
42
+ * glRail("[data-rail]", { radius: 1200, grid: true })
43
+ *
44
+ * CSS: the stage (viewport) `position: relative; overflow: hidden` — the
45
+ * canvas covers it; the track `display: flex; width: max-content; gap: 1rem;
46
+ * cursor: grab; user-select: none; touch-action: pan-y` (flip to a column +
47
+ * `width: 100%; height: max-content` for the vertical layout). Cards
48
+ * `position: relative` with a **transparent background** — labels paint above
49
+ * the canvas for free, the effect hides only the media.
50
+ */
51
+ import * as THREE from "three";
52
+ import { gsap, initGSAP } from "../core/gsap.js";
53
+ import { guard } from "../core/guard.js";
54
+ import { one, toArray } from "../core/util.js";
55
+ import { dragRail, resolveRailAxis } from "../effects/drag-rail.js";
56
+ import type { CommonOptions, Destroy, TargetLike } from "../core/types.js";
57
+
58
+ export interface GlRailOptions extends CommonOptions {
59
+ /** Stage around the track — the canvas covers it. Defaults to `track.parentElement`. */
60
+ viewport?: TargetLike;
61
+ /** Cards re-rendered on the canvas — each needs an `<img>`. @default `":scope > *"` */
62
+ card?: string;
63
+ /** Motion + bend axis: `"x"`, `"y"`, or the layout's choice. @default `"auto"` */
64
+ axis?: "x" | "y" | "auto";
65
+ /** Cylinder radius the cards bend around, px — smaller = stronger bend. @default 1200 */
66
+ radius?: number;
67
+ /** Corner radius, px (rounded-box SDF in the fragment shader). @default 16 */
68
+ corner?: number;
69
+ /** Perspective grid floor under the cards. @default true */
70
+ grid?: boolean;
71
+ /** Device-pixel-ratio cap. @default 2 */
72
+ dpr?: number;
73
+ /** Follow speed toward the intent, per 60fps frame (0..1). @default 0.1 */
74
+ lerp?: number;
75
+ /** Rubber-band resistance distance past the ends, px. @default 140 */
76
+ edge?: number;
77
+ /** Momentum multiplier on release. @default 14 */
78
+ throwScale?: number;
79
+ /** Wheel / trackpad drives the rail (consumed while it can still move). @default true */
80
+ wheel?: boolean;
81
+ /** `(pos, velocity) => {}` called every rendered frame while mounted. */
82
+ onTick?: (pos: number, velocity: number) => void;
83
+ }
84
+
85
+ /* Card: the cylinder bend in the vertex shader, cover-crop + SDF corners in
86
+ the fragment — the pixel contract is webglMedia's, bent to the rail. */
87
+ const CARD_VERT = /* glsl */ `
88
+ varying vec2 vUv;
89
+ uniform vec2 uSize; // card size, px
90
+ uniform float uOffset; // centre offset from the stage centre along the rail axis, px
91
+ uniform float uRadius; // cylinder radius, px
92
+ uniform float uAxis; // 0 = rail runs x (bend around Y), 1 = rail runs y (bend around X)
93
+
94
+ void main() {
95
+ vUv = uv;
96
+ vec3 p = vec3(position.xy * uSize, 0.0);
97
+ float along = uAxis < 0.5 ? p.x : p.y;
98
+ float a = (uOffset + along) / uRadius;
99
+ // Re-centre on the card's own middle: the centre stays glued to the DOM
100
+ // rect while the edges foreshorten onto the cylinder.
101
+ float bent = uRadius * sin(a) - uRadius * sin(uOffset / uRadius) + uOffset;
102
+ if (uAxis < 0.5) p.x = bent; else p.y = bent;
103
+ p.z = -uRadius * (1.0 - cos(a));
104
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(p, 1.0);
105
+ }
106
+ `;
107
+
108
+ const CARD_FRAG = /* glsl */ `
109
+ precision highp float;
110
+ varying vec2 vUv;
111
+ uniform sampler2D uTex;
112
+ uniform vec2 uRes;
113
+ uniform vec2 uTexSize;
114
+ uniform float uCorner;
115
+
116
+ float sdRoundBox(vec2 p, vec2 b, float r) {
117
+ vec2 q = abs(p) - b + r;
118
+ return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;
119
+ }
120
+
121
+ void main() {
122
+ vec2 px = (vUv - 0.5) * uRes;
123
+ float d = sdRoundBox(px, uRes * 0.5, uCorner);
124
+ float alpha = 1.0 - smoothstep(-1.0, 1.0, d); // 1px-ish AA on the corner
125
+ if (alpha < 0.003) discard;
126
+
127
+ // object-fit: cover — window the texture around its centre.
128
+ vec2 scale = uRes / max(uTexSize, vec2(1.0));
129
+ vec2 cover = (vUv - 0.5) * (scale / max(scale.x, scale.y)) + 0.5;
130
+ gl_FragColor = vec4(texture2D(uTex, cover).rgb, alpha);
131
+ }
132
+ `;
133
+
134
+ /* Floor: one plane lying at the bottom of the stage, lines in world space,
135
+ fading toward the horizon and the sides, drifting slightly with the rail. */
136
+ const GRID_VERT = /* glsl */ `
137
+ varying vec2 vWorld; // world xz under this fragment
138
+ void main() {
139
+ vec4 wp = modelMatrix * vec4(position, 1.0);
140
+ vWorld = wp.xz;
141
+ gl_Position = projectionMatrix * viewMatrix * wp;
142
+ }
143
+ `;
144
+
145
+ const GRID_FRAG = /* glsl */ `
146
+ precision highp float;
147
+ varying vec2 vWorld;
148
+ uniform vec2 uShift; // parallax drift with the rail position, px
149
+ uniform vec3 uColor;
150
+ uniform float uOpacity;
151
+ uniform float uSpacing;
152
+
153
+ void main() {
154
+ vec2 cell = (vWorld + uShift) / uSpacing;
155
+ vec2 grad = abs(fract(cell - 0.5) - 0.5) / max(fwidth(cell), 1e-5);
156
+ float line = 1.0 - min(min(grad.x, grad.y), 1.0);
157
+ float depth = smoothstep(-5200.0, -400.0, vWorld.y); // melt into the horizon
158
+ float side = 1.0 - smoothstep(1300.0, 3600.0, abs(vWorld.x));
159
+ gl_FragColor = vec4(uColor, line * uOpacity * depth * side);
160
+ }
161
+ `;
162
+
163
+ /** Floor geometry constants — near edge slightly in front of the cards, far
164
+ edge past the horizon; the stage bottom sits where the z=0 plane ends. */
165
+ const GRID_SPAN = 7200;
166
+ const GRID_DEPTH = 6000;
167
+ const GRID_NEAR_Z = 520;
168
+
169
+ export function glRail(target: TargetLike, options: GlRailOptions = {}): Destroy {
170
+ initGSAP();
171
+
172
+ const track = one<HTMLElement>(target);
173
+ if (!track) return () => {};
174
+
175
+ const {
176
+ viewport,
177
+ card = ":scope > *",
178
+ axis = "auto",
179
+ radius = 1200,
180
+ corner = 16,
181
+ grid = true,
182
+ dpr = 2,
183
+ lerp,
184
+ edge,
185
+ throwScale,
186
+ wheel,
187
+ onTick,
188
+ } = options;
189
+
190
+ return guard(options, () => {
191
+ const vp = one<HTMLElement>(viewport) ?? track.parentElement ?? track;
192
+
193
+ /* ---------------- physics first: the rail works with or without a GPU ---------------- */
194
+
195
+ let lastPos = 0;
196
+ const stopPhysics = dragRail(track, {
197
+ viewport: vp,
198
+ axis,
199
+ lerp,
200
+ edge,
201
+ throwScale,
202
+ wheel,
203
+ // The outer guard already decided about reduced motion for both of us.
204
+ force: true,
205
+ onTick: (pos, velocity) => {
206
+ lastPos = pos;
207
+ onTick?.(pos, velocity);
208
+ },
209
+ });
210
+
211
+ /* ---------------- availability ladder (silent, no probes) ---------------- */
212
+
213
+ if (typeof window === "undefined" || !("WebGLRenderingContext" in window)) return stopPhysics;
214
+
215
+ let renderer: THREE.WebGLRenderer;
216
+ try {
217
+ renderer = new THREE.WebGLRenderer({ alpha: true, antialias: true });
218
+ } catch {
219
+ return stopPhysics; // context refused — the flat DOM rail is the fallback
220
+ }
221
+
222
+ /* ---------------- stage + camera ---------------- */
223
+
224
+ const prevPosition = vp.style.position;
225
+ if (!prevPosition && getComputedStyle(vp).position === "static") {
226
+ vp.style.position = "relative";
227
+ }
228
+
229
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, dpr));
230
+ const scene = new THREE.Scene();
231
+ const camera = new THREE.PerspectiveCamera(45, 1, 10, 14000);
232
+
233
+ // Pixel-space at z = 0: the z=0 plane exactly fills the stage.
234
+ const fitCamera = (w: number, h: number) => {
235
+ camera.aspect = w / h;
236
+ camera.position.set(0, 0, h / 2 / Math.tan((camera.fov * Math.PI) / 360));
237
+ camera.updateProjectionMatrix();
238
+ };
239
+
240
+ /* ---------------- grid floor ---------------- */
241
+
242
+ let gridMesh: THREE.Mesh | null = null;
243
+ let gridShift: THREE.Vector2 | null = null;
244
+ if (grid) {
245
+ gridShift = new THREE.Vector2();
246
+ const material = new THREE.ShaderMaterial({
247
+ vertexShader: GRID_VERT,
248
+ fragmentShader: GRID_FRAG,
249
+ uniforms: {
250
+ uShift: { value: gridShift },
251
+ uColor: { value: new THREE.Color(0.66, 0.7, 0.78) },
252
+ uOpacity: { value: 0.24 },
253
+ uSpacing: { value: 150 },
254
+ },
255
+ transparent: true,
256
+ depthWrite: false,
257
+ depthTest: false,
258
+ });
259
+ gridMesh = new THREE.Mesh(new THREE.PlaneGeometry(1, 1), material);
260
+ gridMesh.rotation.x = -Math.PI / 2;
261
+ gridMesh.renderOrder = -1; // floor first, cards over it
262
+ scene.add(gridMesh);
263
+ }
264
+
265
+ /* ---------------- cards ---------------- */
266
+
267
+ type Entry = {
268
+ el: HTMLElement;
269
+ img: HTMLImageElement;
270
+ mesh: THREE.Mesh;
271
+ material: THREE.ShaderMaterial;
272
+ prevOpacity: string;
273
+ };
274
+
275
+ const geometry = new THREE.PlaneGeometry(1, 1, 24, 12);
276
+ const entries: Entry[] = [];
277
+ const loader = new THREE.TextureLoader();
278
+ let disposed = false;
279
+
280
+ for (const el of toArray<HTMLElement>(card, track)) {
281
+ const img = el.querySelector("img") as HTMLImageElement | null;
282
+ const src = img?.currentSrc || img?.src;
283
+ if (!img || !src) continue; // label-only card — nothing to paint
284
+
285
+ const uniforms = {
286
+ uTex: { value: null as THREE.Texture | null },
287
+ uRes: { value: new THREE.Vector2(1, 1) },
288
+ uTexSize: { value: new THREE.Vector2(1, 1) },
289
+ uCorner: { value: corner },
290
+ uSize: { value: new THREE.Vector2(1, 1) },
291
+ uOffset: { value: 0 },
292
+ uRadius: { value: radius },
293
+ uAxis: { value: 0 },
294
+ };
295
+ const material = new THREE.ShaderMaterial({
296
+ vertexShader: CARD_VERT,
297
+ fragmentShader: CARD_FRAG,
298
+ uniforms,
299
+ transparent: true,
300
+ depthWrite: false,
301
+ depthTest: false,
302
+ });
303
+ // Positions come from the shader (uOffset/uSize), not the 1×1 geometry —
304
+ // the default bounding sphere would cull every card off-screen.
305
+ const mesh = new THREE.Mesh(geometry, material);
306
+ mesh.frustumCulled = false;
307
+ mesh.visible = false;
308
+ scene.add(mesh);
309
+
310
+ const prevOpacity = img.style.opacity;
311
+ entries.push({ el, img, mesh, material, prevOpacity });
312
+
313
+ loader.load(
314
+ src,
315
+ (texture) => {
316
+ if (disposed) {
317
+ texture.dispose();
318
+ return;
319
+ }
320
+ texture.minFilter = THREE.LinearFilter;
321
+ texture.magFilter = THREE.LinearFilter;
322
+ // No sRGB decode: the raw shader passes sampled values through, so
323
+ // the texture stays an ordinary RGBA8 upload (same contract as
324
+ // webglMedia — built-in colourSpace conversion only happens inside
325
+ // three's own material chunks).
326
+ uniforms.uTex.value = texture;
327
+ uniforms.uTexSize.value.set(texture.image?.width || 1, texture.image?.height || 1);
328
+ mesh.visible = true;
329
+ img.style.opacity = "0"; // the canvas owns these pixels from here
330
+ },
331
+ undefined,
332
+ () => {
333
+ /* 404 / decode failure — this card's <img> was never hidden. */
334
+ },
335
+ );
336
+ }
337
+
338
+ if (!entries.length) {
339
+ // Nothing renderable — plain dragRail is the whole effect.
340
+ geometry.dispose();
341
+ gridMesh?.geometry.dispose();
342
+ (gridMesh?.material as THREE.Material | undefined)?.dispose();
343
+ renderer.dispose();
344
+ return stopPhysics;
345
+ }
346
+
347
+ /* ---------------- canvas: under the track, over the stage ---------------- */
348
+
349
+ const canvas = renderer.domElement;
350
+ canvas.style.cssText =
351
+ "position:absolute;inset:0;width:100%;height:100%;display:block;pointer-events:none;";
352
+ vp.insertBefore(canvas, track);
353
+ vp.dataset.akGlRail = "true";
354
+
355
+ /* ---------------- sizing ---------------- */
356
+
357
+ const resize = () => {
358
+ const w = Math.max(1, vp.clientWidth);
359
+ const h = Math.max(1, vp.clientHeight);
360
+ renderer.setSize(w, h, false);
361
+ fitCamera(w, h);
362
+ if (gridMesh) {
363
+ gridMesh.scale.set(GRID_SPAN, GRID_DEPTH, 1);
364
+ // Local +y maps to world −z, so centre the plane to span
365
+ // [GRID_NEAR_Z − GRID_DEPTH, GRID_NEAR_Z] in z.
366
+ gridMesh.position.set(0, -h / 2 + 2, GRID_NEAR_Z - GRID_DEPTH / 2);
367
+ }
368
+ };
369
+ resize();
370
+
371
+ let ro: ResizeObserver | null = null;
372
+ if (typeof ResizeObserver === "function") {
373
+ ro = new ResizeObserver(resize);
374
+ ro.observe(vp);
375
+ }
376
+
377
+ /* ---------------- loop ---------------- */
378
+
379
+ let visible = true;
380
+ let io: IntersectionObserver | null = null;
381
+ if (typeof IntersectionObserver === "function") {
382
+ io = new IntersectionObserver(([entry]) => (visible = entry.isIntersecting), {
383
+ rootMargin: "120px",
384
+ });
385
+ io.observe(vp);
386
+ }
387
+
388
+ const sync = () => {
389
+ const stage = vp.getBoundingClientRect();
390
+ const cx = stage.left + stage.width / 2;
391
+ const cy = stage.top + stage.height / 2;
392
+ const vertical = resolveRailAxis(track, vp, axis) === "y";
393
+ for (const entry of entries) {
394
+ const rect = entry.el.getBoundingClientRect();
395
+ const u = entry.material.uniforms;
396
+ u.uOffset.value = vertical
397
+ ? cy - (rect.top + rect.height / 2)
398
+ : rect.left + rect.width / 2 - cx;
399
+ u.uSize.value.set(rect.width, rect.height);
400
+ u.uRes.value.set(rect.width, rect.height);
401
+ u.uAxis.value = vertical ? 1 : 0;
402
+ }
403
+ };
404
+
405
+ const render = () => {
406
+ if (!visible) return;
407
+ sync();
408
+ gridShift?.set(lastPos * 0.1, 0); // subtle parallax: the floor trails the rail
409
+ renderer.render(scene, camera);
410
+ };
411
+ gsap.ticker.add(render);
412
+
413
+ /* ---------------- teardown ---------------- */
414
+
415
+ return () => {
416
+ disposed = true;
417
+ stopPhysics();
418
+ gsap.ticker.remove(render);
419
+ io?.disconnect();
420
+ ro?.disconnect();
421
+ for (const entry of entries) {
422
+ (entry.material.uniforms.uTex.value as THREE.Texture | null)?.dispose();
423
+ entry.material.dispose();
424
+ entry.img.style.opacity = entry.prevOpacity;
425
+ }
426
+ geometry.dispose();
427
+ if (gridMesh) {
428
+ gridMesh.geometry.dispose();
429
+ (gridMesh.material as THREE.Material).dispose();
430
+ }
431
+ renderer.dispose();
432
+ canvas.remove();
433
+ delete vp.dataset.akGlRail;
434
+ vp.style.position = prevPosition;
435
+ };
436
+ });
437
+ }
@@ -6,7 +6,9 @@
6
6
  * The core barrel (`@cosmictraveler002/anim-kit`) never imports three, so
7
7
  * plain DOM/scroll users keep a gsap+lenis-only dependency tree.
8
8
  *
9
- * import { webglMedia } from "@cosmictraveler002/anim-kit/three";
9
+ * import { webglMedia, glRail } from "@cosmictraveler002/anim-kit/three";
10
10
  */
11
11
  export { webglMedia } from "./webgl-media.js";
12
12
  export type { WebglMediaOptions } from "./webgl-media.js";
13
+ export { glRail } from "./gl-rail.js";
14
+ export type { GlRailOptions } from "./gl-rail.js";