Loading…
← All components

Extras · Control

3D Slider

A volumetric range control whose thumb squashes and stretches as you drag it, then snaps to the step.

40

<InteractiveSlider3D />Live

Customize

Fill#8b5cf6
Thumb#e4e4e7

Installation

Use it in your project

Or skip the copy-paste

One command: writes the file and installs the dependencies.

$ npx deepui-cli add interactive-slider
01

Install

The 3D packages this component is built on.

$ npm install three @react-three/fiber @react-three/drei && npm install -D @types/three
02

Add the component

One self-contained file: create components/InteractiveSlider3D.tsx and paste it in.

components/InteractiveSlider3D.tsx
1"use client";
2
3import {
4 memo,
5 useEffect,
6 useLayoutEffect,
7 useMemo,
8 useRef,
9 useState,
10 type CSSProperties,
11 type ReactNode,
12} from "react";
13import * as THREE from "three";
14import { Canvas, useFrame, useThree, type CanvasProps, type ThreeEvent } from "@react-three/fiber";
15import { Environment, Lightformer } from "@react-three/drei";
16
17/**
18 * The shared props API of DeepUI's individual 3D components (not the full-page templates, which keep
19 * their own tailored scenes).
20 *
21 * The props are grouped by concern. A component extends ONLY the groups it really applies, so its
22 * type never advertises a knob that does nothing (a card has no particles, a background has no tilt):
23 *
24 * interface MyCardProps extends CursorProps, TiltProps, MaterialProps, PerformanceProps { … }
25 *
26 * `Base3DComponentProps` is every group at once, for tooling that handles any component. Same name,
27 * same unit and same meaning everywhere; the default values live in DEFAULT_3D_PROPS. These files are
28 * inlined into each component's single-file bundle (lib/bundle-source.mjs), only what it uses.
29 */
30
31/** Which rotation axes follow the pointer. "x-only": the object nods (up / down); "y-only": it turns (left / right). */
32export type TiltAxis = "both" | "x-only" | "y-only" | "none";
33
34/** 1. Cursor: how the pointer pulls, pushes and drags the object. */
35interface CursorProps {
36 /** Reach of the pointer's influence, in the component's own space: CSS pixels for pixel-laid-out widgets, world units for 3D scenes (each component says which). Default 220 (px). */
37 cursorRadius?: number;
38 /** Positive pulls things towards the pointer, negative pushes them away (repulsion, shockwave). Default 1. */
39 cursorForce?: number;
40 /** How far the object slides towards the pointer, 0 (stays put) to 1 (follows closely). Default 0. */
41 magneticStrength?: number;
42 /** Share of the remaining distance the motion closes each frame (at 60 fps), 0.01 (heavy, slow) to 1 (instant). Default 0.1. */
43 cursorDamping?: number;
44}
45
46/** 2. Tilt and parallax: the object leans towards the pointer, its layers slide against each other. */
47interface TiltProps {
48 /** Largest lean towards the pointer, in degrees. Default 15. */
49 maxTiltAngle?: number;
50 /** Axes that follow the pointer. Default "both". */
51 tiltAxis?: TiltAxis;
52 /** Lean away from the pointer instead of towards it. Default false. */
53 invertTilt?: boolean;
54 /** How far apart the depth layers slide when the object tilts, 0 (flat) to 2. Default 1. */
55 parallaxOffset?: number;
56}
57
58/** 3. Text and 3D typography, for components that draw a label. */
59interface Text3DProps {
60 /** The label drawn by the component. */
61 text?: string;
62 /** Scale of the lettering. Default 1. */
63 fontSize?: number;
64 /** Extrusion depth of 3D letters. Default 0.2. */
65 textDepth?: number;
66 /** Bevelled, light-catching edges on 3D letters. Default true. */
67 bevelEnabled?: boolean;
68 /** Custom font: a .woff / .ttf (flat text) or a typeface .json (extruded text). */
69 fontUrl?: string;
70}
71
72/** 4. Rendering, materials and glow. */
73interface MaterialProps {
74 /** Main color of the object. Default "#6366f1". */
75 primaryColor?: string;
76 /** Color of the glow. Default "#00f0ff". */
77 emissiveColor?: string;
78 /** Strength of the glow, 0 (none) to 3. Default 1. */
79 emissiveIntensity?: number;
80 /** 0 (mirror, glass) to 1 (matte). Default 0.3. */
81 roughness?: number;
82 /** 0 (plastic, organic) to 1 (metal). Default 0.5. */
83 metalness?: number;
84 /** 0 (opaque) to 1 (clear glass): see-through, refracting surfaces. Default 0. */
85 transmission?: number;
86 /** Technical wireframe rendering. Default false. */
87 wireframe?: boolean;
88}
89
90/** 5. Particles, idle motion and shader animation. */
91interface MotionProps {
92 /** Number of instanced elements. Default depends on the component. */
93 particleCount?: number;
94 /** Spin on its own, in radians per second (negative: the other way; 0.5 ≈ one turn in 12 s). Default 0. */
95 autoRotateSpeed?: number;
96 /** Pulses or ripples per second. Default 1. */
97 pulseRate?: number;
98 /** Amplitude of the noise deformation, 0 (none) to 2. Default 1. */
99 displacementScale?: number;
100}
101
102/** 6. Environment and camera. */
103interface EnvironmentProps {
104 /** Camera field of view, in degrees. Default depends on the component. */
105 cameraFov?: number;
106 /** Color of the depth fog. Default "#0a0a0a". */
107 fogColor?: string;
108 /** Thickness of the fog, 0 (none) to 0.2. Default 0. */
109 fogDensity?: number;
110}
111
112/** 7. Performance and accessibility. */
113interface PerformanceProps {
114 /** Lighter rendering for weak devices: pixel ratio 1, fewer instances, smaller environment maps. Default false. */
115 lowPowerMode?: boolean;
116 /** Under the OS "reduce motion" setting, stop idle spin, pulses and deformation (pointer feedback stays). Default true. */
117 respectReducedMotion?: boolean;
118 /** Stop the render loop while the component is scrolled out of view. Default true. */
119 pauseWhenOffscreen?: boolean;
120}
121
122/** Every group at once. Components extend only the groups they apply (see the top of this file). */
123interface Base3DComponentProps
124 extends CursorProps,
125 TiltProps,
126 Text3DProps,
127 MaterialProps,
128 MotionProps,
129 EnvironmentProps,
130 PerformanceProps {}
131
132type Defaults = Required<Omit<Base3DComponentProps, "text" | "fontUrl" | "particleCount" | "cameraFov">>;
133
134/** The values a prop takes when it is left out. A component may override one, and then documents it. */
135const DEFAULT_3D_PROPS: Defaults = {
136 cursorRadius: 220,
137 cursorForce: 1,
138 magneticStrength: 0,
139 cursorDamping: 0.1,
140 maxTiltAngle: 15,
141 tiltAxis: "both",
142 invertTilt: false,
143 parallaxOffset: 1,
144 fontSize: 1,
145 textDepth: 0.2,
146 bevelEnabled: true,
147 primaryColor: "#6366f1",
148 emissiveColor: "#00f0ff",
149 emissiveIntensity: 1,
150 roughness: 0.3,
151 metalness: 0.5,
152 transmission: 0,
153 wireframe: false,
154 autoRotateSpeed: 0,
155 pulseRate: 1,
156 displacementScale: 1,
157 fogColor: "#0a0a0a",
158 fogDensity: 0,
159 lowPowerMode: false,
160 respectReducedMotion: true,
161 pauseWhenOffscreen: true,
162};
163
164/** Inline widget: fills its positioned parent and receives pointer events. */
165const FILL_STYLE: CSSProperties = { position: "absolute", top: 0, left: 0, width: "100%", height: "100%" };
166
167/** Cursor overlay: covers the viewport, above everything, never intercepts the page's events. */
168const OVERLAY_STYLE: CSSProperties = {
169 position: "fixed",
170 top: 0,
171 left: 0,
172 width: "100%",
173 height: "100%",
174 pointerEvents: "none",
175 zIndex: 9999,
176};
177
178/** Visually hidden but reachable by keyboard and screen readers. */
179const SR_ONLY: CSSProperties = {
180 position: "absolute",
181 width: 1,
182 height: 1,
183 padding: 0,
184 margin: -1,
185 overflow: "hidden",
186 clip: "rect(0, 0, 0, 0)",
187 whiteSpace: "nowrap",
188 border: 0,
189};
190
191interface UICanvasProps extends Omit<CanvasProps, "children" | "style" | "gl">, Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
192 children: ReactNode;
193 /** Full-viewport, click-through overlay (cursors) instead of an inline widget. */
194 overlay?: boolean;
195}
196
197/**
198 * Ready-to-use <Canvas>: pauses its render loop while scrolled out of view (pauseWhenOffscreen), pixel
199 * ratio 1 in lowPowerMode; R3F disposes the renderer and its WebGL context on unmount.
200 */
201function UICanvas({ children, overlay = false, dpr = [1, 2], pauseWhenOffscreen = DEFAULT_3D_PROPS.pauseWhenOffscreen, lowPowerMode = DEFAULT_3D_PROPS.lowPowerMode, ...canvasProps }: UICanvasProps) {
202 const containerRef = useRef<HTMLDivElement>(null);
203 // In view at first: the first frame is always drawn before the loop can be paused
204 const [inView, setInView] = useState(true);
205 useEffect(() => {
206 const el = containerRef.current;
207 if (!el || !pauseWhenOffscreen) return undefined;
208 const observer = new IntersectionObserver(([entry]) => setInView(entry.isIntersecting));
209 observer.observe(el);
210 return () => observer.disconnect();
211 }, [pauseWhenOffscreen]);
212 return (
213 <div ref={containerRef} style={overlay ? OVERLAY_STYLE : FILL_STYLE} aria-hidden="true">
214 <Canvas
215 dpr={lowPowerMode ? 1 : dpr}
216 frameloop={inView || !pauseWhenOffscreen ? "always" : "never"}
217 gl={{ antialias: true, alpha: true, powerPreference: "high-performance" }}
218 style={overlay ? { pointerEvents: "none" } : undefined}
219 {...canvasProps}
220 >
221 {children}
222 </Canvas>
223 </div>
224 );
225}
226
227/**
228 * Perspective camera placed so that 1 world unit = 1 CSS pixel on the z = 0 plane: widgets are laid
229 * out in pixels like the rest of the page, and still get real depth (presses, tilts, shadows).
230 */
231function PixelPerspective({ fov = 30 }: { fov?: number }) {
232 const camera = useThree((state) => state.camera) as THREE.PerspectiveCamera;
233 const size = useThree((state) => state.size);
234 useLayoutEffect(() => {
235 camera.fov = fov;
236 camera.near = 1;
237 camera.far = 20000;
238 camera.position.set(0, 0, size.height / 2 / Math.tan(THREE.MathUtils.degToRad(fov / 2)));
239 camera.lookAt(0, 0, 0);
240 camera.updateProjectionMatrix();
241 }, [camera, size, fov]);
242 return null;
243}
244
245function pageFontFamily() {
246 if (typeof document === "undefined") return "sans-serif";
247 return getComputedStyle(document.body).fontFamily || "sans-serif";
248}
249
250interface LabelOptions {
251 text: string;
252 /** Second, smaller line under the text. */
253 subtext?: string;
254 /** Glyph drawn before the text (emoji, arrow, symbol…). */
255 icon?: string;
256 width: number;
257 height: number;
258 color: string;
259 /** Face color; transparent when omitted. */
260 background?: string;
261 fontSize?: number;
262 fontWeight?: number;
263 /** Wrap the text over several lines within the width (minus padding). */
264 wrap?: boolean;
265 align?: "center" | "left";
266 /** Horizontal padding, in CSS pixels (used by wrapping and left alignment). Default 0. */
267 padding?: number;
268 /** Line height, as a multiple of the font size. Default 1.35. */
269 lineHeight?: number;
270}
271
272function wrapLines(ctx: CanvasRenderingContext2D, text: string, maxWidth: number) {
273 const lines: string[] = [];
274 let line = "";
275 for (const word of text.split(/\s+/)) {
276 const candidate = line ? `${line} ${word}` : word;
277 if (line && ctx.measureText(candidate).width > maxWidth) {
278 lines.push(line);
279 line = word;
280 } else {
281 line = candidate;
282 }
283 }
284 if (line) lines.push(line);
285 return lines;
286}
287
288function drawLabel(canvas: HTMLCanvasElement, o: LabelOptions) {
289 // Drawn at 2× (or the screen's ratio) so the text stays crisp once mapped on its plane
290 const scale = Math.min(Math.max(window.devicePixelRatio || 1, 2), 3);
291 canvas.width = Math.max(2, Math.ceil(o.width * scale));
292 canvas.height = Math.max(2, Math.ceil(o.height * scale));
293 const ctx = canvas.getContext("2d");
294 if (!ctx) return;
295 ctx.setTransform(scale, 0, 0, scale, 0, 0);
296 ctx.clearRect(0, 0, o.width, o.height);
297 if (o.background) {
298 ctx.fillStyle = o.background;
299 ctx.fillRect(0, 0, o.width, o.height);
300 }
301
302 const family = pageFontFamily();
303 const size = o.fontSize ?? 15;
304 const weight = o.fontWeight ?? 600;
305 ctx.fillStyle = o.color;
306 ctx.textBaseline = "middle";
307 ctx.textAlign = "center";
308
309 const padding = o.padding ?? 0;
310 const left = o.align === "left";
311 ctx.textAlign = left ? "left" : "center";
312 const x = left ? padding : o.width / 2;
313
314 let text = o.text;
315 if (o.icon) text = `${o.icon} ${text}`;
316 ctx.font = `${weight} ${size}px ${family}`;
317
318 if (o.wrap) {
319 const step = size * (o.lineHeight ?? 1.35);
320 const lines = wrapLines(ctx, text, o.width - padding * 2);
321 // Only as many lines as fit; the last one kept ends with an ellipsis
322 const maxLines = Math.max(1, Math.floor(o.height / step));
323 if (lines.length > maxLines) {
324 lines.length = maxLines;
325 let last = lines[maxLines - 1];
326 while (last && ctx.measureText(`${last}…`).width > o.width - padding * 2) last = last.slice(0, -1);
327 lines[maxLines - 1] = `${last.trimEnd()}…`;
328 }
329 const top = o.height / 2 - ((lines.length - 1) * step) / 2;
330 lines.forEach((line, i) => ctx.fillText(line, x, top + i * step));
331 return;
332 }
333
334 const mainY = o.subtext ? o.height * 0.4 : o.height / 2;
335 ctx.fillText(text, x, mainY);
336
337 if (o.subtext) {
338 ctx.globalAlpha = 0.7;
339 ctx.font = `500 ${Math.round(size * 0.72)}px ${family}`;
340 ctx.fillText(o.subtext, x, o.height * 0.7);
341 ctx.globalAlpha = 1;
342 }
343}
344
345/**
346 * Text drawn into a CanvasTexture, in the page's own font: no font file to download (unlike drei's
347 * <Text>). Redrawn once web fonts finish loading; disposed on unmount.
348 */
349function useLabelTexture(options: LabelOptions) {
350 const key = JSON.stringify(options);
351 const [fontsVersion, setFontsVersion] = useState(0);
352 useEffect(() => {
353 let alive = true;
354 document.fonts?.ready.then(() => {
355 if (alive) setFontsVersion((v) => v + 1);
356 });
357 return () => {
358 alive = false;
359 };
360 }, []);
361
362 const texture = useMemo(() => {
363 const t = new THREE.CanvasTexture(document.createElement("canvas"));
364 t.colorSpace = THREE.SRGBColorSpace;
365 t.anisotropy = 4;
366 return t;
367 }, []);
368
369 useLayoutEffect(() => {
370 drawLabel(texture.image as HTMLCanvasElement, JSON.parse(key) as LabelOptions);
371 texture.needsUpdate = true;
372 }, [texture, key, fontsVersion]);
373
374 useEffect(() => () => texture.dispose(), [texture]);
375 return texture;
376}
377
378/** Rounded-rectangle outline centered on the origin (radius clamped to a pill). */
379function roundedRectShape(width: number, height: number, radius: number) {
380 const r = Math.min(radius, width / 2, height / 2);
381 const x = -width / 2;
382 const y = -height / 2;
383 const shape = new THREE.Shape();
384 shape.moveTo(x + r, y);
385 shape.lineTo(x + width - r, y);
386 shape.quadraticCurveTo(x + width, y, x + width, y + r);
387 shape.lineTo(x + width, y + height - r);
388 shape.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
389 shape.lineTo(x + r, y + height);
390 shape.quadraticCurveTo(x, y + height, x, y + height - r);
391 shape.lineTo(x, y + r);
392 shape.quadraticCurveTo(x, y, x + r, y);
393 return shape;
394}
395
396/** Bevelled, extruded rounded rectangle, centered on the origin (front face at +depth/2 + bevel). */
397function createBevelledSlab(width: number, height: number, radius: number, depth: number, bevel: number) {
398 const geometry = new THREE.ExtrudeGeometry(roundedRectShape(width - bevel * 2, height - bevel * 2, Math.max(0, radius - bevel)), {
399 depth,
400 bevelEnabled: true,
401 bevelThickness: bevel,
402 bevelSize: bevel,
403 bevelSegments: 6,
404 curveSegments: 24,
405 });
406 geometry.translate(0, 0, -depth / 2);
407 return geometry;
408}
409
410interface Spring {
411 value: number;
412 velocity: number;
413}
414
415/** Damped spring step: overshoots a little, then settles. */
416function stepSpring(spring: Spring, target: number, stiffness: number, damping: number, dt: number) {
417 spring.velocity += (target - spring.value) * stiffness * dt;
418 spring.velocity *= Math.exp(-damping * dt);
419 spring.value += spring.velocity * dt;
420 return spring.value;
421}
422
423export interface InteractiveSliderProps extends Pick<PerformanceProps, "pauseWhenOffscreen" | "lowPowerMode"> {
424 min?: number;
425 max?: number;
426 step?: number;
427 value: number;
428 onChange: (value: number) => void;
429 trackColor?: string;
430 thumbColor?: string;
431 /** Color of the filled part of the track. */
432 fillColor?: string;
433 /** Accessible name. Default "Value". */
434 label?: string;
435}
436
437const TRACK_HEIGHT = 12;
438const TRACK_DEPTH = 8;
439const THUMB_RADIUS = 15;
440const FILL_RADIUS = TRACK_HEIGHT / 2 - 1.5;
441const BUBBLE_W = 64;
442const BUBBLE_H = 30;
443
444function snap(raw: number, min: number, max: number, step: number) {
445 const snapped = step > 0 ? Math.round((raw - min) / step) * step + min : raw;
446 return THREE.MathUtils.clamp(Number(snapped.toFixed(6)), min, max);
447}
448
449function format(value: number, step: number) {
450 const decimals = step > 0 && step < 1 ? Math.min(4, String(step).split(".")[1]?.length ?? 0) : 0;
451 return value.toFixed(decimals);
452}
453
454const Slider = memo(function Slider({ min = 0, max = 100, step = 1, value, onChange, trackColor = "#27272a", thumbColor = "#e4e4e7", fillColor = "#8b5cf6" }: InteractiveSliderProps) {
455 const size = useThree((state) => state.size);
456 const gl = useThree((state) => state.gl);
457 const thumbRef = useRef<THREE.Mesh>(null);
458 const fillBodyRef = useRef<THREE.Mesh>(null);
459 const fillCapRef = useRef<THREE.Mesh>(null);
460 const bubbleRef = useRef<THREE.Mesh>(null);
461 const onChangeRef = useRef(onChange);
462 useEffect(() => {
463 onChangeRef.current = onChange;
464 });
465
466 const width = Math.max(120, Math.min(size.width - 80, 560));
467 const toX = (v: number) => -width / 2 + ((v - min) / Math.max(1e-6, max - min)) * width;
468
469 const drag = useRef({ active: false, hovered: false, x: toX(value), lastX: toX(value) });
470 const thumbX = useRef<Spring>({ value: toX(value), velocity: 0 });
471 const stretch = useRef(0);
472 const press = useRef(0);
473 const bubble = useRef(0);
474 const scratch = useMemo(() => ({ plane: new THREE.Plane(new THREE.Vector3(0, 0, 1), 0), hit: new THREE.Vector3() }), []);
475
476 const bubbleTexture = useLabelTexture({ text: format(value, step), width: BUBBLE_W, height: BUBBLE_H, color: "#0a0a0a", background: "#f4f4f5", fontSize: 13, fontWeight: 700 });
477
478 const geometries = useMemo(
479 () => ({
480 track: createBevelledSlab(width + TRACK_HEIGHT, TRACK_HEIGHT, TRACK_HEIGHT / 2, TRACK_DEPTH, 2),
481 thumb: new THREE.SphereGeometry(THUMB_RADIUS, 48, 32),
482 cap: new THREE.SphereGeometry(FILL_RADIUS, 24, 16),
483 body: (() => {
484 // Unit-length cylinder along X starting at 0: scaled in length only, round ends untouched
485 const g = new THREE.CylinderGeometry(FILL_RADIUS, FILL_RADIUS, 1, 24, 1, true);
486 g.rotateZ(Math.PI / 2);
487 g.translate(0.5, 0, 0);
488 return g;
489 })(),
490 plane: new THREE.PlaneGeometry(1, 1),
491 dot: new THREE.CircleGeometry(1.6, 12),
492 }),
493 [width]
494 );
495 const materials = useMemo(
496 () => ({
497 track: new THREE.MeshPhysicalMaterial({ metalness: 0.4, roughness: 0.45, clearcoat: 0.6 }),
498 fill: new THREE.MeshStandardMaterial({ roughness: 0.3, emissiveIntensity: 1.1, toneMapped: false }),
499 thumb: new THREE.MeshPhysicalMaterial({ metalness: 1, roughness: 0.12, clearcoat: 1 }),
500 bubble: new THREE.MeshBasicMaterial({ transparent: true, depthWrite: false, toneMapped: false }),
501 dot: new THREE.MeshBasicMaterial({ color: "#52525b" }),
502 hit: new THREE.MeshBasicMaterial({ transparent: true, opacity: 0, depthWrite: false }),
503 }),
504 []
505 );
506
507 useEffect(() => {
508 materials.track.color.set(trackColor);
509 materials.thumb.color.set(thumbColor);
510 materials.fill.color.set(fillColor);
511 materials.fill.emissive.set(fillColor);
512 }, [materials, trackColor, thumbColor, fillColor]);
513 useEffect(() => {
514 materials.bubble.map = bubbleTexture;
515 materials.bubble.needsUpdate = true;
516 }, [materials, bubbleTexture]);
517 useEffect(() => () => Object.values(geometries).forEach((g) => g.dispose()), [geometries]);
518 useEffect(() => () => Object.values(materials).forEach((m) => m.dispose()), [materials]);
519
520 // Step ticks (only when they stay readable)
521 const steps = step > 0 ? Math.round((max - min) / step) : 0;
522 const tickXs = steps > 0 && steps <= 20 ? Array.from({ length: steps + 1 }, (_, i) => toX(min + i * step)) : [];
523
524 const pick = (e: ThreeEvent<PointerEvent>) => {
525 // Pointer → the slider's plane (also works once the pointer has left the meshes, under capture)
526 if (!e.ray.intersectPlane(scratch.plane, scratch.hit)) return;
527 const x = THREE.MathUtils.clamp(scratch.hit.x, -width / 2, width / 2);
528 drag.current.x = x;
529 const next = snap(min + ((x + width / 2) / width) * (max - min), min, max, step);
530 if (next !== value) onChangeRef.current(next);
531 };
532
533 useFrame((_, delta) => {
534 const dt = Math.min(delta, 1 / 30);
535 const d = drag.current;
536 // Dragging: the thumb follows the pointer; released: it springs to the snapped value
537 const target = d.active ? d.x : toX(value);
538 const prev = thumbX.current.value;
539 stepSpring(thumbX.current, target, d.active ? 900 : 260, d.active ? 38 : 16, dt);
540 const x = thumbX.current.value;
541 const speed = (x - prev) / Math.max(dt, 1e-4);
542
543 // Squash & stretch: elongated along the motion, thinner across, back to round when it stops
544 stretch.current = THREE.MathUtils.damp(stretch.current, Math.min(Math.abs(speed) / 900, 0.7), 14, dt);
545 press.current = THREE.MathUtils.damp(press.current, d.active ? 1 : d.hovered ? 0.5 : 0, 12, dt);
546 const sx = 1 + stretch.current;
547 const sy = 1 / Math.sqrt(sx);
548 const thumb = thumbRef.current;
549 if (thumb) {
550 thumb.position.set(x, 0, THUMB_RADIUS * 0.5 - press.current * 4);
551 thumb.scale.set(sx * (1 + press.current * 0.12), sy * (1 + press.current * 0.12), sy);
552 }
553
554 // Filled part of the track, up to the thumb
555 const fillLength = Math.max(0, x + width / 2);
556 if (fillBodyRef.current) {
557 fillBodyRef.current.scale.set(fillLength || 0.0001, 1, 1);
558 fillBodyRef.current.visible = fillLength > 0.5;
559 }
560 if (fillCapRef.current) fillCapRef.current.position.x = -width / 2 + fillLength;
561
562 // Value bubble above the thumb while hovering or dragging
563 bubble.current = THREE.MathUtils.damp(bubble.current, d.active || d.hovered ? 1 : 0, 10, dt);
564 const b = bubbleRef.current;
565 if (b) {
566 b.position.set(x, THUMB_RADIUS + 14 + bubble.current * 10, 20);
567 b.scale.set(BUBBLE_W * (0.6 + bubble.current * 0.4), BUBBLE_H * (0.6 + bubble.current * 0.4), 1);
568 materials.bubble.opacity = bubble.current;
569 }
570 d.lastX = x;
571 });
572
573 return (
574 <group>
575 <mesh geometry={geometries.track} material={materials.track} position={[0, 0, -TRACK_DEPTH / 2]} />
576 <group position={[-width / 2, 0, 1]}>
577 <mesh geometry={geometries.cap} material={materials.fill} />
578 <mesh ref={fillBodyRef} geometry={geometries.body} material={materials.fill} />
579 </group>
580 <mesh ref={fillCapRef} geometry={geometries.cap} material={materials.fill} position={[-width / 2, 0, 1]} />
581 {tickXs.map((tx, i) => (
582 <mesh key={i} geometry={geometries.dot} material={materials.dot} position={[tx, -TRACK_HEIGHT - 6, 0]} />
583 ))}
584 <mesh ref={thumbRef} geometry={geometries.thumb} material={materials.thumb} />
585 <mesh ref={bubbleRef} geometry={geometries.plane} material={materials.bubble} />
586 {/* Hit area over the whole slider: press anywhere on the track to jump, then drag */}
587 <mesh
588 geometry={geometries.plane}
589 material={materials.hit}
590 position={[0, 0, THUMB_RADIUS + 2]}
591 scale={[width + THUMB_RADIUS * 2, THUMB_RADIUS * 3, 1]}
592 onPointerOver={() => {
593 drag.current.hovered = true;
594 gl.domElement.style.cursor = "grab";
595 }}
596 onPointerOut={() => {
597 drag.current.hovered = false;
598 if (!drag.current.active) gl.domElement.style.cursor = "";
599 }}
600 onPointerDown={(e: ThreeEvent<PointerEvent>) => {
601 e.stopPropagation();
602 (e.target as Element).setPointerCapture?.(e.pointerId);
603 drag.current.active = true;
604 gl.domElement.style.cursor = "grabbing";
605 pick(e);
606 }}
607 onPointerMove={(e: ThreeEvent<PointerEvent>) => {
608 if (drag.current.active) pick(e);
609 }}
610 onPointerUp={(e: ThreeEvent<PointerEvent>) => {
611 (e.target as Element).releasePointerCapture?.(e.pointerId);
612 drag.current.active = false;
613 gl.domElement.style.cursor = drag.current.hovered ? "grab" : "";
614 }}
615 />
616 </group>
617 );
618});
619
620/** Self-contained slider: fills its positioned parent (~100px high), controlled through value / onChange. */
621function InteractiveSlider3D(props: InteractiveSliderProps) {
622 const { min = 0, max = 100, step = 1, value, onChange, label = "Value" } = props;
623 const [focused, setFocused] = useState(false);
624 return (
625 <>
626 <UICanvas pauseWhenOffscreen={props.pauseWhenOffscreen} lowPowerMode={props.lowPowerMode}>
627 <PixelPerspective />
628 <ambientLight intensity={0.5} />
629 <directionalLight position={[-200, 300, 500]} intensity={1.8} />
630 <Environment resolution={128} frames={1}>
631 <Lightformer form="rect" intensity={3} position={[0, 5, 3]} rotation-x={Math.PI / 2} scale={[10, 2, 1]} />
632 <Lightformer form="rect" intensity={1.5} position={[-5, 0, 3]} rotation-y={Math.PI / 2} scale={[2, 6, 1]} />
633 <Lightformer form="ring" intensity={3} position={[4, -1, 4]} scale={2} />
634 </Environment>
635 <Slider {...props} />
636 </UICanvas>
637 {/* Native range input for keyboard and assistive tech, kept in sync */}
638 <input
639 type="range"
640 aria-label={label}
641 min={min}
642 max={max}
643 step={step}
644 value={value}
645 onChange={(e) => onChange(Number(e.target.value))}
646 onFocus={() => setFocused(true)}
647 onBlur={() => setFocused(false)}
648 style={SR_ONLY}
649 />
650 {focused ? (
651 <span aria-hidden="true" style={{ position: "absolute", inset: 4, borderRadius: 16, outline: "2px solid rgba(255,255,255,0.6)", pointerEvents: "none" }} />
652 ) : null}
653 </>
654 );
655}
656
657export default memo(InteractiveSlider3D);
03

Drop it in a page

Updated live with the settings above.

app/page.tsx
1import InteractiveSlider3D from "@/components/InteractiveSlider3D";
2
3export default function Section() {
4 return (
5 // The component fills this box: give it a position and a height
6 <div style={{ position: "relative", width: "100%", height: "100vh" }}>
7 <InteractiveSlider3D
8 step={10}
9 fillColor="#8b5cf6"
10 thumbColor="#e4e4e7"
11 />
12 </div>
13 );
14}
Next componentInteractive Globe→