@jsb188/gfx 1.1.11 → 1.1.12
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/README.md +248 -54
- package/elements/Shapes.helpers.ts +204 -0
- package/elements/Shapes.hooks.ts +171 -0
- package/elements/Shapes.tsx +505 -0
- package/elements/Shapes.types.ts +81 -0
- package/elements/Stack.helpers.ts +42 -0
- package/elements/Stack.tsx +143 -0
- package/elements/Text.helpers.ts +45 -0
- package/elements/Text.hooks.ts +197 -0
- package/elements/Text.tsx +98 -0
- package/libs/dotGrid.helpers.ts +53 -0
- package/libs/dotGrid.ts +480 -77
- package/libs/effects/dotEffects.ts +136 -0
- package/libs/effects/effectQuad.ts +8 -2
- package/libs/pointer.ts +6 -0
- package/libs/runtime.ts +6 -4
- package/libs/types.ts +8 -1
- package/main.ts +2 -0
- package/modules/Carousel.helpers.ts +234 -0
- package/modules/Carousel.hooks.ts +520 -0
- package/modules/Carousel.tsx +135 -29
- package/modules/Dots.tsx +269 -0
- package/modules/DotsBoard.helpers.ts +388 -0
- package/modules/DotsBoard.hooks.ts +144 -0
- package/modules/DotsBoard.strings.ts +649 -0
- package/modules/DotsBoard.types.ts +240 -0
- package/modules/DotsBoardCanvas.hooks.ts +49 -0
- package/modules/DotsBoardCanvas.tsx +190 -0
- package/modules/DotsBoardElements.tsx +330 -0
- package/modules/Gallery.helpers.ts +32 -0
- package/modules/Gallery.hooks.ts +149 -0
- package/modules/Gallery.tsx +194 -0
- package/modules/GfxCanvas.tsx +10 -2
- package/modules/KineticHeader.helpers.ts +44 -0
- package/modules/KineticHeader.hooks.ts +206 -0
- package/modules/KineticHeader.tsx +305 -0
- package/modules/KineticHeader.types.ts +56 -0
- package/modules/ScrollSteps.hooks.ts +138 -0
- package/modules/ScrollSteps.tsx +7 -52
- package/package.json +15 -5
- package/scenes/Carousel.ts +99 -18
- package/scenes/DotsBoard.helpers.ts +12 -0
- package/scenes/DotsBoard.ts +245 -0
- package/tsconfig.json +1 -1
- package/utils/align.ts +18 -0
- package/utils/color.ts +64 -2
- package/utils/dotEffectSpecs.ts +79 -0
- package/utils/dotGridSpecs.ts +304 -46
- package/utils/motion.ts +88 -0
- package/utils/random.ts +22 -0
- package/utils/strings.ts +116 -0
- package/modules/DotsArea.tsx +0 -120
- package/modules/VisionBoard.helpers.ts +0 -561
- package/modules/VisionBoard.tsx +0 -358
- package/modules/VisionBoard.types.ts +0 -88
- package/scenes/DotsArea.ts +0 -208
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { hexToRgb } from '../../utils/color.ts';
|
|
2
|
+
import { DOT_EFFECTS, DOT_SHAPES, getDotEffectId } from '../../utils/dotEffectSpecs.ts';
|
|
3
|
+
import type { ResolvedDotEffectOptions } from '../../utils/dotEffectSpecs.ts';
|
|
4
|
+
import type { UniformValues } from '../uniforms.ts';
|
|
5
|
+
|
|
6
|
+
/*
|
|
7
|
+
* Declare one trigger's settings; click, pulse, and rest all use the same shader evaluator.
|
|
8
|
+
*/
|
|
9
|
+
export function dotEffectDeclarations(prefix: string) {
|
|
10
|
+
return `
|
|
11
|
+
uniform int ${prefix}Effect;
|
|
12
|
+
uniform int ${prefix}Shape;
|
|
13
|
+
uniform float ${prefix}Radius;
|
|
14
|
+
uniform float ${prefix}Width;
|
|
15
|
+
uniform float ${prefix}Duration;
|
|
16
|
+
uniform float ${prefix}Strength;
|
|
17
|
+
uniform float ${prefix}Scale;
|
|
18
|
+
uniform float ${prefix}Opacity;
|
|
19
|
+
uniform float ${prefix}ColorOn;
|
|
20
|
+
uniform vec3 ${prefix}Color;
|
|
21
|
+
`;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/*
|
|
25
|
+
* Create uniform slots with safe values, without requiring an enabled effect.
|
|
26
|
+
*/
|
|
27
|
+
export function createDotEffectUniforms(prefix: string): UniformValues {
|
|
28
|
+
return {
|
|
29
|
+
[`${prefix}Effect`]: { value: 0 },
|
|
30
|
+
[`${prefix}Shape`]: { value: 0 },
|
|
31
|
+
[`${prefix}Radius`]: { value: 1 },
|
|
32
|
+
[`${prefix}Width`]: { value: 1 },
|
|
33
|
+
[`${prefix}Duration`]: { value: 1 },
|
|
34
|
+
[`${prefix}Strength`]: { value: 0 },
|
|
35
|
+
[`${prefix}Scale`]: { value: 1 },
|
|
36
|
+
[`${prefix}Opacity`]: { value: 1 },
|
|
37
|
+
[`${prefix}ColorOn`]: { value: 0 },
|
|
38
|
+
[`${prefix}Color`]: { value: [1, 1, 1] },
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/*
|
|
43
|
+
* Apply resolved appearance and movement settings; only parameter changes do this work.
|
|
44
|
+
*/
|
|
45
|
+
export function setDotEffectUniforms(uniforms: UniformValues, prefix: string, options: ResolvedDotEffectOptions | null) {
|
|
46
|
+
uniforms[`${prefix}Effect`].value = getDotEffectId(options?.effect ?? 'swell');
|
|
47
|
+
uniforms[`${prefix}Shape`].value = DOT_SHAPES.indexOf(options?.shape ?? 'circle');
|
|
48
|
+
uniforms[`${prefix}Radius`].value = options?.radius ?? 1;
|
|
49
|
+
uniforms[`${prefix}Width`].value = options?.width ?? 1;
|
|
50
|
+
uniforms[`${prefix}Duration`].value = (options?.duration ?? 1000) / 1000;
|
|
51
|
+
uniforms[`${prefix}Strength`].value = options?.strength ?? 0;
|
|
52
|
+
uniforms[`${prefix}Scale`].value = options?.scale ?? 1;
|
|
53
|
+
uniforms[`${prefix}Opacity`].value = options?.opacity ?? 1;
|
|
54
|
+
uniforms[`${prefix}ColorOn`].value = options?.color ? 1 : 0;
|
|
55
|
+
uniforms[`${prefix}Color`].value = hexToRgb(options?.color ?? '#ffffff');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Stateless effect math, composed with GLSL_CONSTANTS for PI; no extra render pass or per-frame allocations. */
|
|
59
|
+
export const GLSL_DOT_EFFECTS = `
|
|
60
|
+
struct DotEffectSample {
|
|
61
|
+
vec2 offset;
|
|
62
|
+
float amount;
|
|
63
|
+
float tint;
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/*
|
|
67
|
+
* Zero influence, including at the end of a timeline, so every effect returns home exactly.
|
|
68
|
+
*/
|
|
69
|
+
DotEffectSample noDotEffect() {
|
|
70
|
+
return DotEffectSample(vec2(0.0), 0.0, 0.0);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/*
|
|
74
|
+
* Resolve random from a seed that the trigger holds constant throughout its animation.
|
|
75
|
+
*/
|
|
76
|
+
int selectDotEffect(int effect, float seed) {
|
|
77
|
+
return effect < 0 ? min(${DOT_EFFECTS.length - 1}, int(floor(seed * ${DOT_EFFECTS.length}.0))) : effect;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/*
|
|
81
|
+
* A smooth rise and fall with zero slope at both ends.
|
|
82
|
+
*/
|
|
83
|
+
float dotEffectBump(float phase) {
|
|
84
|
+
float bump = sin(PI * clamp(phase, 0.0, 1.0));
|
|
85
|
+
return bump * bump;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/*
|
|
89
|
+
* Evaluate any effect relative to its origin. Triggers supply coordinates, a normalized
|
|
90
|
+
* lifetime, and a stable per-dot seed; movement is added to the cursor spring independently.
|
|
91
|
+
*/
|
|
92
|
+
DotEffectSample sampleDotEffect(int effect, vec2 away, float phase, float seed, float radius, float width, float strength) {
|
|
93
|
+
if (phase < 0.0 || phase >= 1.0) return noDotEffect();
|
|
94
|
+
float distance = length(away);
|
|
95
|
+
if (distance >= radius) return noDotEffect();
|
|
96
|
+
float fade = 1.0 - smoothstep(radius * 0.65, radius, distance);
|
|
97
|
+
float bump = dotEffectBump(phase);
|
|
98
|
+
DotEffectSample result = DotEffectSample(vec2(0.0), bump * fade, 0.0);
|
|
99
|
+
if (effect == ${getDotEffectId('ripple')} || effect == ${getDotEffectId('color_wave')}) {
|
|
100
|
+
float crest = phase * (radius + width);
|
|
101
|
+
result.amount = (1.0 - smoothstep(0.0, width, abs(distance - crest))) * fade;
|
|
102
|
+
result.tint = effect == ${getDotEffectId('color_wave')} ? 1.0 : 0.0;
|
|
103
|
+
} else if (effect == ${getDotEffectId('vortex')}) {
|
|
104
|
+
float angle = bump * fade * strength * 2.0 * PI;
|
|
105
|
+
float c = cos(angle);
|
|
106
|
+
float s = sin(angle);
|
|
107
|
+
result.offset = vec2(c * away.x - s * away.y, s * away.x + c * away.y) - away;
|
|
108
|
+
} else if (effect == ${getDotEffectId('magnet')}) {
|
|
109
|
+
result.offset = -away * min(0.95, strength * 2.0) * bump * fade;
|
|
110
|
+
} else if (effect == ${getDotEffectId('sparkle')}) {
|
|
111
|
+
float start = seed * 0.6;
|
|
112
|
+
float local = (phase - start) / 0.3;
|
|
113
|
+
result.amount = local > 0.0 && local < 1.0 ? dotEffectBump(local) * fade : 0.0;
|
|
114
|
+
result.tint = 1.0;
|
|
115
|
+
}
|
|
116
|
+
return result;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/*
|
|
120
|
+
* A stable accent palette for color wave and sparkle when no explicit tint was supplied.
|
|
121
|
+
*/
|
|
122
|
+
vec3 dotEffectPalette(float seed) {
|
|
123
|
+
return 0.55 + 0.4 * cos(2.0 * PI * (seed + vec3(0.0, 0.33, 0.67)));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/*
|
|
127
|
+
* Composite a trigger's tint in premultiplied form; later triggers can override earlier ones.
|
|
128
|
+
*/
|
|
129
|
+
void addDotEffectTint(inout vec4 tint, DotEffectSample effectSample, vec3 color, float colorOn, float seed) {
|
|
130
|
+
float alpha = effectSample.amount * max(colorOn, effectSample.tint);
|
|
131
|
+
if (alpha <= 0.0) return;
|
|
132
|
+
vec3 target = colorOn > 0.5 ? color : dotEffectPalette(seed);
|
|
133
|
+
tint.rgb = tint.rgb * (1.0 - alpha) + target * alpha;
|
|
134
|
+
tint.a += (1.0 - tint.a) * alpha;
|
|
135
|
+
}
|
|
136
|
+
`;
|
|
@@ -35,6 +35,8 @@ export interface EffectQuadDraw {
|
|
|
35
35
|
radius: number;
|
|
36
36
|
/** 0..1 opacity of the drawn image over `backdrop`; the rectangle itself stays opaque. */
|
|
37
37
|
opacity: number;
|
|
38
|
+
/** Overall alpha of the image and its backdrop; defaults to 1. */
|
|
39
|
+
alpha?: number;
|
|
38
40
|
/** Color seen through a translucent image, as if the rectangle had that background. */
|
|
39
41
|
backdrop: RGB;
|
|
40
42
|
}
|
|
@@ -75,6 +77,7 @@ export function createEffectQuad(gl: OGLRenderingContext, effects: ImageEffectIn
|
|
|
75
77
|
`
|
|
76
78
|
uniform float uRadius;
|
|
77
79
|
uniform float uOpacity;
|
|
80
|
+
uniform float uAlpha;
|
|
78
81
|
uniform vec3 uBackdrop;
|
|
79
82
|
void main() {
|
|
80
83
|
${parts.body}
|
|
@@ -82,7 +85,8 @@ void main() {
|
|
|
82
85
|
vec2 corner = abs(vUv - 0.5) * uResolution - (uResolution * 0.5 - uRadius);
|
|
83
86
|
float dist = length(max(corner, 0.0)) + min(max(corner.x, corner.y), 0.0) - uRadius;
|
|
84
87
|
float coverage = 1.0 - clamp(dist + 0.5, 0.0, 1.0);
|
|
85
|
-
//
|
|
88
|
+
// Mix the image over its backdrop, then apply overall alpha to the premultiplied result.
|
|
89
|
+
coverage *= uAlpha;
|
|
86
90
|
fragColor = vec4(mix(uBackdrop, image, uOpacity) * coverage, coverage);
|
|
87
91
|
}
|
|
88
92
|
`,
|
|
@@ -97,6 +101,7 @@ void main() {
|
|
|
97
101
|
uRect: { value: [0, 0, 1, 1] },
|
|
98
102
|
uRadius: { value: 0 },
|
|
99
103
|
uOpacity: { value: 1 },
|
|
104
|
+
uAlpha: { value: 1 },
|
|
100
105
|
uBackdrop: { value: [1, 1, 1] },
|
|
101
106
|
},
|
|
102
107
|
transparent: true,
|
|
@@ -114,7 +119,7 @@ void main() {
|
|
|
114
119
|
|
|
115
120
|
return {
|
|
116
121
|
program,
|
|
117
|
-
draw({ image, imageSize, rect, canvas, amount, pointer, time, radius, opacity, backdrop }) {
|
|
122
|
+
draw({ image, imageSize, rect, canvas, amount, pointer, time, radius, opacity, alpha = 1, backdrop }) {
|
|
118
123
|
uniforms.tImage.value = image;
|
|
119
124
|
setVec2(uniforms.uImageSize, imageSize[0], imageSize[1]);
|
|
120
125
|
setVec2(uniforms.uResolution, rect.width * canvas.pixelRatio, rect.height * canvas.pixelRatio);
|
|
@@ -129,6 +134,7 @@ void main() {
|
|
|
129
134
|
uniforms.uTime.value = time;
|
|
130
135
|
uniforms.uRadius.value = radius * canvas.pixelRatio;
|
|
131
136
|
uniforms.uOpacity.value = opacity;
|
|
137
|
+
uniforms.uAlpha.value = alpha;
|
|
132
138
|
setVec3(uniforms.uBackdrop, backdrop);
|
|
133
139
|
gl.renderer.render({ scene: mesh, clear: false, sort: false, frustumCull: false, update: false });
|
|
134
140
|
},
|
package/libs/pointer.ts
CHANGED
|
@@ -79,7 +79,10 @@ export function createPointerTracker(canvas: HTMLCanvasElement, onMove: () => vo
|
|
|
79
79
|
y: 0.5,
|
|
80
80
|
targetX: 0.5,
|
|
81
81
|
targetY: 0.5,
|
|
82
|
+
clientX: 0,
|
|
83
|
+
clientY: 0,
|
|
82
84
|
active: false,
|
|
85
|
+
present: false,
|
|
83
86
|
hover: false,
|
|
84
87
|
hoverAmount: 0,
|
|
85
88
|
};
|
|
@@ -101,7 +104,10 @@ export function createPointerTracker(canvas: HTMLCanvasElement, onMove: () => vo
|
|
|
101
104
|
const y = 1 - (page.clientY - rect.top) / rect.height;
|
|
102
105
|
pointer.targetX = x;
|
|
103
106
|
pointer.targetY = y;
|
|
107
|
+
pointer.clientX = page.clientX;
|
|
108
|
+
pointer.clientY = page.clientY;
|
|
104
109
|
pointer.active = true;
|
|
110
|
+
pointer.present = page.present;
|
|
105
111
|
pointer.hover = page.present && x >= 0 && x <= 1 && y >= 0 && y <= 1;
|
|
106
112
|
}
|
|
107
113
|
|
package/libs/runtime.ts
CHANGED
|
@@ -215,7 +215,7 @@ export function createGfxRuntime<P>({
|
|
|
215
215
|
ready = true;
|
|
216
216
|
onReady?.();
|
|
217
217
|
}
|
|
218
|
-
const continuous = scene.frameloop === 'always' && !reducedMotion;
|
|
218
|
+
const continuous = scene.frameloop === 'always' && (!reducedMotion || scene.pauseForReducedMotion === false);
|
|
219
219
|
if (continuous || !settled) scheduleNext(time);
|
|
220
220
|
// A demand scene that asked for another frame (invalidate during update/render) keeps
|
|
221
221
|
// its clock; resetting it here would hand that frame a zero delta and stall its animation.
|
|
@@ -246,9 +246,11 @@ export function createGfxRuntime<P>({
|
|
|
246
246
|
try {
|
|
247
247
|
canvas.width = Math.max(1, Math.round(width * pixelRatio));
|
|
248
248
|
canvas.height = Math.max(1, Math.round(height * pixelRatio));
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
renderer.
|
|
249
|
+
// In drawing-buffer pixels with a ratio of 1, so the viewport OGL derives (width × dpr) is the
|
|
250
|
+
// buffer exactly; a fractional ratio would round it a pixel short at some sizes.
|
|
251
|
+
renderer.dpr = 1;
|
|
252
|
+
renderer.width = canvas.width;
|
|
253
|
+
renderer.height = canvas.height;
|
|
252
254
|
scene.resize({ width, height, pixelRatio });
|
|
253
255
|
activity();
|
|
254
256
|
} catch (error) {
|
package/libs/types.ts
CHANGED
|
@@ -16,8 +16,13 @@ export interface ScenePointer {
|
|
|
16
16
|
/** Raw position the smoothed value eases toward. */
|
|
17
17
|
targetX: number;
|
|
18
18
|
targetY: number;
|
|
19
|
+
/** Raw position in viewport CSS pixels; unlike the UVs it stays put when the canvas scrolls under a still pointer. */
|
|
20
|
+
clientX: number;
|
|
21
|
+
clientY: number;
|
|
19
22
|
/** False until the first pointer event; the position rests at the center before then. */
|
|
20
23
|
active: boolean;
|
|
24
|
+
/** True while the last mouse or pen position is present in the window. */
|
|
25
|
+
present: boolean;
|
|
21
26
|
/** True while the pointer is inside the canvas rect (over children included). */
|
|
22
27
|
hover: boolean;
|
|
23
28
|
/** Eased 0..1 version of `hover`; drive hover effects from this. */
|
|
@@ -46,8 +51,10 @@ export interface SceneContext {
|
|
|
46
51
|
}
|
|
47
52
|
|
|
48
53
|
export interface Scene<P = void> {
|
|
49
|
-
/** Defaults to demand. Always mode pauses when hidden
|
|
54
|
+
/** Defaults to demand. Always mode pauses when hidden, and while reduced motion is enabled unless `pauseForReducedMotion` is false. */
|
|
50
55
|
frameloop?: 'always' | 'demand';
|
|
56
|
+
/** False keeps an always-running scene drawing while the visitor prefers reduced motion, for frames that are content (video) rather than decoration; true by default. */
|
|
57
|
+
pauseForReducedMotion?: boolean;
|
|
51
58
|
/** False for a scene nothing in which reacts to the pointer: moves no longer wake the loop or ease the pointer. Read live, so it may change. */
|
|
52
59
|
followsPointer?: boolean;
|
|
53
60
|
/** Per-second easing rate for the pointer; 6 (the default) is roughly 10% per frame at 60fps. */
|
package/main.ts
CHANGED
|
@@ -80,3 +80,237 @@ export function getVirtualPositions(position: number, containerWidth: number, mi
|
|
|
80
80
|
for (let v = position - sideCount; v <= position + sideCount; v++) positions.push(v);
|
|
81
81
|
return positions;
|
|
82
82
|
}
|
|
83
|
+
|
|
84
|
+
/**
|
|
85
|
+
* Blocks carousel
|
|
86
|
+
*/
|
|
87
|
+
|
|
88
|
+
/** Where a block rests when the track snaps to it. */
|
|
89
|
+
export type BlocksAlign = 'start' | 'center';
|
|
90
|
+
|
|
91
|
+
/** What a press on the blocks starts: a drag of the track, a text selection, or a form field's own handling. */
|
|
92
|
+
export type BlocksPressKind = 'drag' | 'text' | 'native';
|
|
93
|
+
|
|
94
|
+
/** `Document` with the caret API Safari and older Chromium have instead of `caretPositionFromPoint`. */
|
|
95
|
+
type DocumentWithCaretRange = Document & {
|
|
96
|
+
caretRangeFromPoint?: (x: number, y: number) => Range | null;
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
/** One moment of a drag: when it was, and where the pointer had put the track (before any edge resistance). */
|
|
100
|
+
export interface DragSample {
|
|
101
|
+
time: number;
|
|
102
|
+
offset: number;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The blocks track measured: the viewport it scrolls in, how far it can go, and where each block snaps. */
|
|
106
|
+
export interface BlocksTrackMeasure {
|
|
107
|
+
/** Width of the container's content box, in CSS pixels. */
|
|
108
|
+
viewportWidth: number;
|
|
109
|
+
/** The track's resting offset at its start: 0, less the content offset. */
|
|
110
|
+
minOffset: number;
|
|
111
|
+
/** The furthest the track can move: its width past the viewport's (or 0 when it all fits), less the content offset. */
|
|
112
|
+
maxOffset: number;
|
|
113
|
+
/** Track offset that puts each block at its snap position, in block order. */
|
|
114
|
+
offsets: number[];
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** The iOS scroll view constant: how quickly a drag past an edge stiffens. */
|
|
118
|
+
const RUBBER_BAND_COEFFICIENT = 0.55;
|
|
119
|
+
|
|
120
|
+
/** Pixels per line for a wheel that reports lines instead of pixels (Firefox with a mouse wheel). */
|
|
121
|
+
const WHEEL_LINE_PX = 16;
|
|
122
|
+
|
|
123
|
+
/*
|
|
124
|
+
* Track offset that brings each block to rest: its left edge at the viewport's left edge
|
|
125
|
+
* (`start`), or its middle at the viewport's middle (`center`), never past either end of the
|
|
126
|
+
* track. Blocks that would need more than the track can give all share `maxOffset`, so the last
|
|
127
|
+
* blocks are reached at one and the same position.
|
|
128
|
+
*/
|
|
129
|
+
export function getBlockSnapOffsets(
|
|
130
|
+
blocks: { left: number; width: number }[],
|
|
131
|
+
viewportWidth: number,
|
|
132
|
+
maxOffset: number,
|
|
133
|
+
align: BlocksAlign,
|
|
134
|
+
) {
|
|
135
|
+
return blocks.map(({ left, width }) => {
|
|
136
|
+
const wanted = align === 'center' ? left + width / 2 - viewportWidth / 2 : left;
|
|
137
|
+
return Math.min(maxOffset, Math.max(0, wanted));
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/*
|
|
142
|
+
* Index of the snap offset nearest to `offset`; the lower index on a tie, so of the blocks sharing
|
|
143
|
+
* the end offset the first is the one reported.
|
|
144
|
+
*/
|
|
145
|
+
export function getNearestBlockIndex(offsets: number[], offset: number) {
|
|
146
|
+
let nearest = 0;
|
|
147
|
+
for (let i = 1; i < offsets.length; i++) {
|
|
148
|
+
if (Math.abs(offsets[i] - offset) < Math.abs(offsets[nearest] - offset)) nearest = i;
|
|
149
|
+
}
|
|
150
|
+
return nearest;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/*
|
|
154
|
+
* The block a finished gesture lands on: the one whose snap offset is nearest to where the track
|
|
155
|
+
* would coast (`offset` plus `projection`), so a flick carries on a little. A gesture that clearly
|
|
156
|
+
* meant to move on (`intent` is its direction: a flick's, or a wheel's after enough travel) but
|
|
157
|
+
* rounds back onto the block it started from, having moved past that block's offset in its
|
|
158
|
+
* direction, still advances to the next block with a different offset; so a mouse wheel's notch
|
|
159
|
+
* or a short flick never leaves the carousel where it was. Going back and then flicking forward
|
|
160
|
+
* is not such a case (the track is behind its start), and returns to the start block.
|
|
161
|
+
*/
|
|
162
|
+
export function getSettleIndex(offsets: number[], offset: number, projection: number, startIndex: number, intent: -1 | 0 | 1) {
|
|
163
|
+
const nearest = getNearestBlockIndex(offsets, offset + projection);
|
|
164
|
+
if (nearest !== startIndex || intent === 0 || (offset - offsets[startIndex]) * intent <= 0) return nearest;
|
|
165
|
+
let next = startIndex;
|
|
166
|
+
// Skip blocks that rest at the same offset as the start block (those sharing the track's end).
|
|
167
|
+
while (next + intent >= 0 && next + intent < offsets.length) {
|
|
168
|
+
next += intent;
|
|
169
|
+
if (offsets[next] !== offsets[startIndex]) return next;
|
|
170
|
+
}
|
|
171
|
+
return startIndex;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/*
|
|
175
|
+
* How fast the pointer was moving the track at release, in CSS pixels per second, from the samples
|
|
176
|
+
* of the last `windowMs`; 0 when it held still that long (a slow release is not a flick).
|
|
177
|
+
*/
|
|
178
|
+
export function getDragVelocity(samples: DragSample[], now: number, windowMs: number) {
|
|
179
|
+
const recent = samples.filter((sample) => now - sample.time <= windowMs);
|
|
180
|
+
if (recent.length < 2) return 0;
|
|
181
|
+
const first = recent[0];
|
|
182
|
+
const last = recent[recent.length - 1];
|
|
183
|
+
const dt = last.time - first.time;
|
|
184
|
+
return dt > 0 ? ((last.offset - first.offset) / dt) * 1000 : 0;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/*
|
|
188
|
+
* Soften a track offset dragged past `min` or `max`: the excess is compressed the way iOS scroll
|
|
189
|
+
* views do it, so the track follows the pointer less and less and never gets as far as `size` (the
|
|
190
|
+
* viewport width) from its edge. Inside the range the offset is returned as is.
|
|
191
|
+
*/
|
|
192
|
+
export function getRubberBandOffset(offset: number, min: number, max: number, size: number) {
|
|
193
|
+
if (offset >= min && offset <= max) return offset;
|
|
194
|
+
const edge = offset < min ? min : max;
|
|
195
|
+
if (size <= 0) return edge;
|
|
196
|
+
const excess = Math.abs(offset - edge);
|
|
197
|
+
const soft = (1 - 1 / ((excess * RUBBER_BAND_COEFFICIENT) / size + 1)) * size;
|
|
198
|
+
return edge + Math.sign(offset - edge) * soft;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/*
|
|
202
|
+
* Sideways wheel movement in CSS pixels, whatever unit the event reports in: lines are taken as
|
|
203
|
+
* `WHEEL_LINE_PX` each, pages as the viewport width.
|
|
204
|
+
*/
|
|
205
|
+
export function getWheelDeltaX(event: WheelEvent, viewportWidth: number) {
|
|
206
|
+
if (event.deltaMode === event.DOM_DELTA_LINE) return event.deltaX * WHEEL_LINE_PX;
|
|
207
|
+
if (event.deltaMode === event.DOM_DELTA_PAGE) return event.deltaX * viewportWidth;
|
|
208
|
+
return event.deltaX;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/*
|
|
212
|
+
* Measure the blocks track in one pass of layout reads: the viewport is the container's content
|
|
213
|
+
* box (padding shows the neighbouring blocks under it), the blocks are the track's children,
|
|
214
|
+
* with edges taken from their rectangles so fractional widths and gaps stay exact. Only the
|
|
215
|
+
* track's translation moves the rectangles, and every one by the same amount, so their
|
|
216
|
+
* differences are unaffected by it. `contentOffset` shifts the whole range the track rests in
|
|
217
|
+
* (its ends and every snap position) by that many CSS pixels: -20 shows the content 20px
|
|
218
|
+
* further left than the container's content box, at the start and everywhere after.
|
|
219
|
+
*/
|
|
220
|
+
export function measureBlocksTrack(
|
|
221
|
+
container: HTMLElement,
|
|
222
|
+
track: HTMLElement,
|
|
223
|
+
align: BlocksAlign,
|
|
224
|
+
contentOffset: number,
|
|
225
|
+
): BlocksTrackMeasure {
|
|
226
|
+
const style = getComputedStyle(container);
|
|
227
|
+
const viewportWidth = container.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
|
|
228
|
+
const trackRect = track.getBoundingClientRect();
|
|
229
|
+
const blocks = Array.from(track.children, (child) => {
|
|
230
|
+
const rect = child.getBoundingClientRect();
|
|
231
|
+
return { left: rect.left - trackRect.left, width: rect.width };
|
|
232
|
+
});
|
|
233
|
+
const maxOffset = Math.max(0, trackRect.width - viewportWidth);
|
|
234
|
+
// The track's offset is how far it has moved left, so content shifted left by 20 is an offset of +20.
|
|
235
|
+
const shift = -contentOffset;
|
|
236
|
+
return {
|
|
237
|
+
viewportWidth,
|
|
238
|
+
minOffset: shift,
|
|
239
|
+
maxOffset: maxOffset + shift,
|
|
240
|
+
offsets: getBlockSnapOffsets(blocks, viewportWidth, maxOffset, align).map((offset) => offset + shift),
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/*
|
|
245
|
+
* The element nearest `target` (itself included) that matches `selector`, only if it is inside
|
|
246
|
+
* `container`, so a carousel placed inside a link or an editor is not mistaken for one.
|
|
247
|
+
*/
|
|
248
|
+
function closestWithin(target: Element, container: Element, selector: string) {
|
|
249
|
+
const match = target.closest(selector);
|
|
250
|
+
return match && container.contains(match) ? match : null;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/*
|
|
254
|
+
* The text node the caret would land in at a viewport point, through whichever caret API the
|
|
255
|
+
* browser has; null when the point is nearest to something other than text.
|
|
256
|
+
*/
|
|
257
|
+
function getTextNodeAtPoint(x: number, y: number) {
|
|
258
|
+
const doc = document as DocumentWithCaretRange;
|
|
259
|
+
const node =
|
|
260
|
+
typeof doc.caretPositionFromPoint === 'function'
|
|
261
|
+
? doc.caretPositionFromPoint(x, y)?.offsetNode
|
|
262
|
+
: doc.caretRangeFromPoint?.(x, y)?.startContainer;
|
|
263
|
+
return node?.nodeType === Node.TEXT_NODE ? (node as Text) : null;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/*
|
|
267
|
+
* Whether a viewport point lies on the glyphs of selectable text inside `container`. The caret
|
|
268
|
+
* APIs answer with the nearest text even from blank space (the empty right side of a paragraph,
|
|
269
|
+
* a block's padding), so the text node's own line boxes decide; text under `user-select: none`
|
|
270
|
+
* (on its element or any ancestor up to the container) does not count.
|
|
271
|
+
*/
|
|
272
|
+
function isSelectableTextAtPoint(container: Element, x: number, y: number) {
|
|
273
|
+
const node = getTextNodeAtPoint(x, y);
|
|
274
|
+
if (!node?.data.trim() || !container.contains(node)) return false;
|
|
275
|
+
const range = document.createRange();
|
|
276
|
+
range.selectNodeContents(node);
|
|
277
|
+
const onGlyphs = Array.from(range.getClientRects()).some(
|
|
278
|
+
(rect) => x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom,
|
|
279
|
+
);
|
|
280
|
+
if (!onGlyphs) return false;
|
|
281
|
+
for (let el = node.parentElement; el; el = el === container ? null : el.parentElement) {
|
|
282
|
+
const style = getComputedStyle(el);
|
|
283
|
+
if ((style.userSelect || style.webkitUserSelect) === 'none') return false;
|
|
284
|
+
}
|
|
285
|
+
return true;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
/*
|
|
289
|
+
* What a press at a viewport point on `target` starts. A form field keeps its press (typing, its
|
|
290
|
+
* own selection, a slider's thumb). Links, buttons, draggables, and blank space drag the track;
|
|
291
|
+
* a press there that does not move is still their click. Text is selected, as anywhere else on
|
|
292
|
+
* the page, when `selectText` allows it (the caller turns it off for touch, where a long press
|
|
293
|
+
* is what selects).
|
|
294
|
+
*/
|
|
295
|
+
export function getBlocksPressKind(target: Element, container: Element, x: number, y: number, selectText: boolean): BlocksPressKind {
|
|
296
|
+
if (closestWithin(target, container, 'input, textarea, select, [contenteditable]:not([contenteditable="false"])')) {
|
|
297
|
+
return 'native';
|
|
298
|
+
}
|
|
299
|
+
if (!selectText || closestWithin(target, container, 'a[href], button, [role="button"], [draggable="true"]')) return 'drag';
|
|
300
|
+
return isSelectableTextAtPoint(container, x, y) ? 'text' : 'drag';
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/*
|
|
304
|
+
* Whether an element from `target` up to (not including) `container` can itself scroll further
|
|
305
|
+
* sideways in the direction of `deltaX` (a wide table or code block inside a block), so the wheel
|
|
306
|
+
* is that element's and not the carousel's.
|
|
307
|
+
*/
|
|
308
|
+
export function canScrollSideways(target: Element, container: Element, deltaX: number) {
|
|
309
|
+
for (let el: Element | null = target; el && el !== container; el = el.parentElement) {
|
|
310
|
+
if (el.scrollWidth <= el.clientWidth) continue;
|
|
311
|
+
const { overflowX } = getComputedStyle(el);
|
|
312
|
+
if (overflowX !== 'auto' && overflowX !== 'scroll') continue;
|
|
313
|
+
if (deltaX < 0 ? el.scrollLeft > 0 : Math.ceil(el.scrollLeft + el.clientWidth) < el.scrollWidth) return true;
|
|
314
|
+
}
|
|
315
|
+
return false;
|
|
316
|
+
}
|