@jsb188/gfx 1.1.2
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 +522 -0
- 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/chain.ts +174 -0
- package/libs/dotGrid.helpers.ts +53 -0
- package/libs/dotGrid.ts +954 -0
- package/libs/effects/dotEffects.ts +136 -0
- package/libs/effects/effectQuad.ts +146 -0
- package/libs/effects/effectRegion.ts +299 -0
- package/libs/effects/imageEffects.ts +599 -0
- package/libs/effects/index.ts +8 -0
- package/libs/effects/ripple.ts +160 -0
- package/libs/glsl.ts +134 -0
- package/libs/passes.ts +374 -0
- package/libs/pointer.ts +151 -0
- package/libs/runtime.ts +329 -0
- package/libs/texture.ts +160 -0
- package/libs/types.ts +94 -0
- package/libs/uniforms.ts +32 -0
- package/main.ts +4 -0
- package/modules/Carousel.helpers.ts +316 -0
- package/modules/Carousel.hooks.ts +520 -0
- package/modules/Carousel.tsx +631 -0
- 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.hooks.ts +12 -0
- package/modules/GfxCanvas.tsx +189 -0
- package/modules/Hero.tsx +90 -0
- 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 +98 -0
- package/package.json +52 -0
- package/scenes/Carousel.ts +277 -0
- package/scenes/DotsBoard.helpers.ts +12 -0
- package/scenes/DotsBoard.ts +245 -0
- package/scenes/Hero.ts +280 -0
- package/tsconfig.json +13 -0
- package/utils/align.ts +18 -0
- package/utils/color.ts +112 -0
- package/utils/dotEffectSpecs.ts +79 -0
- package/utils/dotGridSpecs.ts +469 -0
- package/utils/easing.ts +18 -0
- package/utils/imageEffectSpecs.ts +89 -0
- package/utils/motion.ts +88 -0
- package/utils/random.ts +22 -0
- package/utils/strings.ts +116 -0
package/libs/types.ts
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import type { OGLRenderingContext, Renderer } from 'ogl';
|
|
2
|
+
|
|
3
|
+
export interface SceneSize {
|
|
4
|
+
/** CSS pixel width of the canvas. */
|
|
5
|
+
width: number;
|
|
6
|
+
/** CSS pixel height of the canvas. */
|
|
7
|
+
height: number;
|
|
8
|
+
/** Device pixels per CSS pixel after the runtime's cap; the drawing buffer is width × pixelRatio. */
|
|
9
|
+
pixelRatio: number;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ScenePointer {
|
|
13
|
+
/** Smoothed position in canvas UV space (0..1, y up). Leaves that range while the pointer is outside the canvas. */
|
|
14
|
+
x: number;
|
|
15
|
+
y: number;
|
|
16
|
+
/** Raw position the smoothed value eases toward. */
|
|
17
|
+
targetX: number;
|
|
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;
|
|
22
|
+
/** False until the first pointer event; the position rests at the center before then. */
|
|
23
|
+
active: boolean;
|
|
24
|
+
/** True while the last mouse or pen position is present in the window. */
|
|
25
|
+
present: boolean;
|
|
26
|
+
/** True while the pointer is inside the canvas rect (over children included). */
|
|
27
|
+
hover: boolean;
|
|
28
|
+
/** Eased 0..1 version of `hover`; drive hover effects from this. */
|
|
29
|
+
hoverAmount: number;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface SceneFrame {
|
|
33
|
+
/** Seconds of active animation, excluding time spent hidden or paused. */
|
|
34
|
+
elapsed: number;
|
|
35
|
+
/** Seconds since the previous active frame, capped at 0.1. */
|
|
36
|
+
delta: number;
|
|
37
|
+
reducedMotion: boolean;
|
|
38
|
+
/** Page-wide pointer tracked by the runtime, already eased for this frame. */
|
|
39
|
+
pointer: ScenePointer;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export interface SceneContext {
|
|
43
|
+
renderer: Renderer;
|
|
44
|
+
gl: OGLRenderingContext;
|
|
45
|
+
/** Aborted before cleanup; check this before attaching asynchronously loaded assets. */
|
|
46
|
+
signal: AbortSignal;
|
|
47
|
+
/** Request a frame after changing a scene that renders on demand. */
|
|
48
|
+
invalidate: () => void;
|
|
49
|
+
/** Register cleanup as resources are created, including during factory setup. */
|
|
50
|
+
onDispose: (cleanup: () => void) => void;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface Scene<P = void> {
|
|
54
|
+
/** Defaults to demand. Always mode pauses when hidden, and while reduced motion is enabled unless `pauseForReducedMotion` is false. */
|
|
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;
|
|
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. */
|
|
59
|
+
followsPointer?: boolean;
|
|
60
|
+
/** Per-second easing rate for the pointer; 6 (the default) is roughly 10% per frame at 60fps. */
|
|
61
|
+
pointerSmoothing?: number;
|
|
62
|
+
/** Per-second easing rate for `pointer.hoverAmount`; defaults to 6. */
|
|
63
|
+
hoverSmoothing?: number;
|
|
64
|
+
/** Frame rate for continuous scenes while the pointer is idle; 30 by default, 0 keeps full rate. */
|
|
65
|
+
idleFrameRate?: number;
|
|
66
|
+
/** Seconds without pointer activity before the idle rate applies; defaults to 2. */
|
|
67
|
+
idleAfterSeconds?: number;
|
|
68
|
+
/** Return false while assets are still loading so the wrapper keeps showing its placeholder. */
|
|
69
|
+
isReady?: () => boolean;
|
|
70
|
+
/** Update projections and render targets for the canvas's CSS dimensions. Called before rendering. */
|
|
71
|
+
resize: (size: SceneSize) => void;
|
|
72
|
+
update?: (frame: SceneFrame) => void;
|
|
73
|
+
/** Draw the frame; the runtime has already bound the canvas and does not clear it. */
|
|
74
|
+
render: (frame: SceneFrame) => void;
|
|
75
|
+
/** Apply new params in place. Without it, param changes after mount are ignored. */
|
|
76
|
+
setParams?: (params: P) => void;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export type SceneFactory<P = void> = (context: SceneContext, params: P) => Scene<P>;
|
|
80
|
+
|
|
81
|
+
/** Factories are synchronous; the wrapper loads their modules asynchronously. */
|
|
82
|
+
export type SceneLoader<P = void> = () => Promise<{
|
|
83
|
+
default: SceneFactory<P>;
|
|
84
|
+
}>;
|
|
85
|
+
|
|
86
|
+
export interface GfxRuntime<P = void> {
|
|
87
|
+
invalidate: () => void;
|
|
88
|
+
setVisible: (visible: boolean) => void;
|
|
89
|
+
setParams: (params: P) => void;
|
|
90
|
+
dispose: () => void;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** RGB triple in 0..1, the form every color uniform in this package takes. */
|
|
94
|
+
export type RGB = [number, number, number];
|
package/libs/uniforms.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { RGB } from './types.ts';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Uniform value helpers shared by every pass and scene. OGL keeps a copy of each uniform's last
|
|
5
|
+
* uploaded value and skips the upload when an array compares equal, so vector uniforms are
|
|
6
|
+
* written in place: a frame allocates nothing and unchanged values cost no GL call.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** The `uniforms` shape OGL programs take; each entry's `value` is read at draw time. */
|
|
10
|
+
export type UniformValues = Record<string, { value: unknown }>;
|
|
11
|
+
|
|
12
|
+
/** One uniform slot. Vector uniforms hold a number array that the setters below write into. */
|
|
13
|
+
export type UniformSlot = { value: unknown };
|
|
14
|
+
|
|
15
|
+
/*
|
|
16
|
+
* Write a 2D vector into a uniform's existing array.
|
|
17
|
+
*/
|
|
18
|
+
export function setVec2(uniform: UniformSlot, x: number, y: number) {
|
|
19
|
+
const target = uniform.value as number[];
|
|
20
|
+
target[0] = x;
|
|
21
|
+
target[1] = y;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/*
|
|
25
|
+
* Write a 3D vector (typically an RGB color) into a uniform's existing array.
|
|
26
|
+
*/
|
|
27
|
+
export function setVec3(uniform: UniformSlot, vector: RGB | readonly [number, number, number]) {
|
|
28
|
+
const target = uniform.value as number[];
|
|
29
|
+
target[0] = vector[0];
|
|
30
|
+
target[1] = vector[1];
|
|
31
|
+
target[2] = vector[2];
|
|
32
|
+
}
|
package/main.ts
ADDED
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Start a paused, muted video without letting a rejected autoplay surface as an unhandled error.
|
|
3
|
+
*/
|
|
4
|
+
export function playVideo(video: HTMLVideoElement) {
|
|
5
|
+
if (video.paused && video.readyState >= video.HAVE_FUTURE_DATA) video.play().catch(() => {});
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/*
|
|
9
|
+
* Whether a video is actually rendering frames right now (not merely asked to play).
|
|
10
|
+
*/
|
|
11
|
+
export function isVideoPlaying(video: HTMLVideoElement) {
|
|
12
|
+
return !video.paused && !video.ended && video.readyState >= video.HAVE_CURRENT_DATA;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/*
|
|
16
|
+
* Call `onPlaying` once every given video has started playing, counting a video that failed to
|
|
17
|
+
* load as done so a broken file never blocks, or after `timeoutMs` if some never start (a stalled
|
|
18
|
+
* network). Videos already playing are not waited for. Returns a cleanup that cancels the wait.
|
|
19
|
+
*/
|
|
20
|
+
export function whenVideosPlaying(videos: Iterable<HTMLVideoElement>, timeoutMs: number, onPlaying: () => void) {
|
|
21
|
+
const pending = new Set<HTMLVideoElement>();
|
|
22
|
+
const cleanups: (() => void)[] = [];
|
|
23
|
+
let done = false;
|
|
24
|
+
const finish = () => {
|
|
25
|
+
if (done) return;
|
|
26
|
+
done = true;
|
|
27
|
+
for (const cleanup of cleanups) cleanup();
|
|
28
|
+
onPlaying();
|
|
29
|
+
};
|
|
30
|
+
for (const video of videos) {
|
|
31
|
+
if (isVideoPlaying(video) || video.error) continue;
|
|
32
|
+
pending.add(video);
|
|
33
|
+
const settle = () => {
|
|
34
|
+
pending.delete(video);
|
|
35
|
+
if (!pending.size) finish();
|
|
36
|
+
};
|
|
37
|
+
video.addEventListener('playing', settle);
|
|
38
|
+
video.addEventListener('error', settle);
|
|
39
|
+
cleanups.push(() => {
|
|
40
|
+
video.removeEventListener('playing', settle);
|
|
41
|
+
video.removeEventListener('error', settle);
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
const timer = window.setTimeout(finish, timeoutMs);
|
|
45
|
+
cleanups.push(() => clearTimeout(timer));
|
|
46
|
+
if (!pending.size) finish();
|
|
47
|
+
return () => {
|
|
48
|
+
done = true;
|
|
49
|
+
for (const cleanup of cleanups) cleanup();
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/*
|
|
54
|
+
* Wrap a virtual slide position onto the item list (negative positions included).
|
|
55
|
+
*/
|
|
56
|
+
export function getItemIndex(position: number, count: number) {
|
|
57
|
+
return ((position % count) + count) % count;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/*
|
|
61
|
+
* Left edge of a virtual slide in the endless track, at natural widths: the list repeats every
|
|
62
|
+
* cycle, so the edge is whole cycles plus the widths of the items before it in its cycle.
|
|
63
|
+
*/
|
|
64
|
+
export function getVirtualLeft(position: number, widths: number[], gap: number) {
|
|
65
|
+
const cycleWidth = widths.reduce((sum, width) => sum + width + gap, 0);
|
|
66
|
+
const index = getItemIndex(position, widths.length);
|
|
67
|
+
let left = Math.floor(position / widths.length) * cycleWidth;
|
|
68
|
+
for (let i = 0; i < index; i++) left += widths[i] + gap;
|
|
69
|
+
return left;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/*
|
|
73
|
+
* Virtual slide positions to keep mounted around the focused one: enough on each side to cover
|
|
74
|
+
* half the container at the narrowest slide, plus one entering. Before the container has been
|
|
75
|
+
* measured (width 0) only the immediate neighbours are kept.
|
|
76
|
+
*/
|
|
77
|
+
export function getVirtualPositions(position: number, containerWidth: number, minSlideWidth: number) {
|
|
78
|
+
const sideCount = containerWidth ? Math.ceil(containerWidth / 2 / minSlideWidth) + 1 : 1;
|
|
79
|
+
const positions: number[] = [];
|
|
80
|
+
for (let v = position - sideCount; v <= position + sideCount; v++) positions.push(v);
|
|
81
|
+
return positions;
|
|
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
|
+
}
|