js.foresight 3.3.0-beta.1 → 3.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +15 -39
- package/dist/index.d.ts +10 -19
- package/dist/index.js +1 -1
- package/package.json +73 -70
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Bart Spaans
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -11,12 +11,13 @@
|
|
|
11
11
|
[](http://www.typescriptlang.org/)
|
|
12
12
|
[](https://opensource.org/licenses/MIT)
|
|
13
13
|
[](https://foresightjs.com#playground)
|
|
14
|
-
|
|
14
|
+
|
|
15
|
+
ForesightJS is a lightweight JavaScript library that predicts user intent to prefetch content before it's needed. **It works completely out of the box without configuration**, supporting both desktop and mobile devices with different prediction strategies.
|
|
15
16
|
|
|
16
17
|
### [Playground](https://foresightjs.com/)
|
|
17
18
|
|
|
18
19
|

|
|
19
|
-
_In the GIF above, the [ForesightJS DevTools](https://foresightjs.com/docs/
|
|
20
|
+
_In the GIF above, the [ForesightJS DevTools](https://foresightjs.com/docs/debugging/devtools) are enabled. Normally, users won't see anything that ForesightJS does except the increased perceived speed from early prefetching._
|
|
20
21
|
|
|
21
22
|
## Download
|
|
22
23
|
|
|
@@ -28,27 +29,9 @@ npm install js.foresight
|
|
|
28
29
|
yarn add js.foresight
|
|
29
30
|
```
|
|
30
31
|
|
|
31
|
-
## Which problems does ForesightJS solve?
|
|
32
|
-
|
|
33
|
-
### Problem 1: On-Hover Prefetching Still Has Latency
|
|
34
|
-
|
|
35
|
-
Traditional hover-based prefetching only triggers after the user's cursor reaches an element. This approach wastes the critical 100-200ms window between when a user begins moving toward a target and when the hover event actually fires.
|
|
36
|
-
|
|
37
|
-
### Problem 2: Viewport-Based Prefetching is Wasteful
|
|
38
|
-
|
|
39
|
-
Many modern frameworks (like Next.js) automatically prefetch resources for all links that enter the viewport. While well-intentioned, this creates significant overhead since users typically interact with only a small fraction of visible elements. Simply scrolling up and down the Next.js homepage can trigger **_1.59MB_** of unnecessary prefetch requests.
|
|
40
|
-
|
|
41
|
-
### Problem 3: Hover-Based Prefetching Excludes Keyboard Users
|
|
42
|
-
|
|
43
|
-
Many routers rely on hover-based prefetching, but this approach completely excludes keyboard users since keyboard navigation never triggers hover events. This means keyboard users miss out on the performance benefits that mouse users get from hover-based prefetching.
|
|
44
|
-
|
|
45
|
-
### The ForesightJS Solution
|
|
46
|
-
|
|
47
|
-
ForesightJS bridges the gap between wasteful viewport prefetching and basic hover prefetching. The `ForesightManager` predicts user interactions by analyzing mouse trajectory patterns, scroll direction and keyboard navigation sequences. This allows you to prefetch resources at the optimal time to improve performance, but targeted enough to avoid waste.
|
|
48
|
-
|
|
49
32
|
## Basic Usage Example
|
|
50
33
|
|
|
51
|
-
This basic example is in vanilla JS, ofcourse most people will use ForesightJS with a framework. You can read about framework integrations in the [docs](https://foresightjs.com/docs/integrations).
|
|
34
|
+
This basic example is in vanilla JS, ofcourse most people will use ForesightJS with a framework. You can read about framework integrations in the [docs](https://foresightjs.com/docs/integrations/react/useForesight).
|
|
52
35
|
|
|
53
36
|
```javascript
|
|
54
37
|
import { ForesightManager } from "foresightjs"
|
|
@@ -73,38 +56,29 @@ const { isTouchDevice } = ForesightManager.instance.register({
|
|
|
73
56
|
|
|
74
57
|
## Integrations
|
|
75
58
|
|
|
76
|
-
Since ForesightJS is framework agnostic, it can be integrated with any JavaScript framework. While I haven't yet built
|
|
59
|
+
Since ForesightJS is framework agnostic, it can be integrated with any JavaScript framework. While I haven't yet built integrations for every framework, ready-to-use implementations for [Next.js](https://foresightjs.com/docs/integrations/react/nextjs) and [React Router](https://foresightjs.com/docs/integrations/react/react-router) are already available. Sharing integrations for other frameworks/packages is highly appreciated!
|
|
77
60
|
|
|
78
61
|
## Configuration
|
|
79
62
|
|
|
80
|
-
ForesightJS
|
|
63
|
+
ForesightJS works out of the box with no setup required, but it can be configured both [globally](https://foresightjs.com/docs/configuration/global-settings) and per [element](https://foresightjs.com/docs/configuration/element-settings) if needed.
|
|
81
64
|
|
|
82
65
|
## Development Tools
|
|
83
66
|
|
|
84
|
-
ForesightJS has dedicated [Development Tools](https://github.com/spaansba/ForesightJS-
|
|
67
|
+
ForesightJS has dedicated [Development Tools](https://github.com/spaansba/ForesightJS/tree/main/packages/js.foresight-devtools) created with [Foresight Events](https://foresightjs.com/docs/events) that help you understand and tune how foresight is working in your application. This standalone development package provides real-time visualization of mouse trajectory predictions, element bounds, and callback execution.
|
|
85
68
|
|
|
86
69
|
```bash
|
|
87
|
-
|
|
70
|
+
pnpm add js.foresight-devtools
|
|
88
71
|
```
|
|
89
72
|
|
|
90
|
-
See the [development tools documentation](https://foresightjs.com/docs/
|
|
91
|
-
|
|
92
|
-
## What About Touch Devices and Slow Connections?
|
|
73
|
+
See the [development tools documentation](https://foresightjs.com/docs/debugging/devtools) for more details.
|
|
93
74
|
|
|
94
|
-
|
|
75
|
+
## Prediction Strategies
|
|
95
76
|
|
|
96
|
-
|
|
77
|
+
ForesightJS uses different prediction strategies depending on the device type:
|
|
97
78
|
|
|
98
|
-
|
|
99
|
-
- `isLimitedConnection` - true when user is on a 2G connection or has data-saver enabled
|
|
100
|
-
- `isRegistered` - true if element was actually registered
|
|
79
|
+
**Desktop/Keyboard Users**: Mouse trajectory prediction, keyboard navigation tracking, and scroll-based prefetching. [Read more](https://foresightjs.com/docs/getting-started/what-is-foresightjs#keyboardmouse-users)
|
|
101
80
|
|
|
102
|
-
|
|
103
|
-
An example of this can be found in the [Next.js](https://foresightjs.com/docs/integrations/react/nextjs) or [React Router](https://foresightjs.com/docs/integrations/react/react-router) ForesightLink components.
|
|
104
|
-
|
|
105
|
-
## How Does ForesightJS Work?
|
|
106
|
-
|
|
107
|
-
For a detailed technical explanation of its prediction algorithms and internal architecture, see the **[Behind the Scenes documentation](https://foresightjs.com/docs/Behind_the_Scenes)**.
|
|
81
|
+
**Mobile Devices**: Viewport enter detection and touch start events (configurable via [`touchDeviceStrategy`]). [Read more](https://foresightjs.com/docs/getting-started/what-is-foresightjs#touch-devices-v330)
|
|
108
82
|
|
|
109
83
|
## Providing Context to AI Tools
|
|
110
84
|
|
|
@@ -114,6 +88,8 @@ ForesightJS is a newer library, so most AI assistants and LLMs may not have much
|
|
|
114
88
|
- Use [llms-full.txt](https://foresightjs.com/llms-full.txt) for a full markdown version of the docs, ideal for AI tools that support context injection or uploads.
|
|
115
89
|
- All documentation pages are also available in markdown. You can view them by adding .md to the end of any URL, for example: https://foresightjs.com/docs/getting_started.md.
|
|
116
90
|
|
|
91
|
+
[Read more](https://foresightjs.com/docs/ai-context)
|
|
92
|
+
|
|
117
93
|
# Contributing
|
|
118
94
|
|
|
119
95
|
Please see the [contributing guidelines](/CONTRIBUTING.md)
|
package/dist/index.d.ts
CHANGED
|
@@ -64,19 +64,10 @@ type ElementBounds = {
|
|
|
64
64
|
/** The hit slop values applied to this element. */
|
|
65
65
|
hitSlop: Exclude<HitSlop, number>;
|
|
66
66
|
};
|
|
67
|
-
/**
|
|
68
|
-
* Represents trajectory hit related data for a foresight element.
|
|
69
|
-
*/
|
|
70
|
-
type TrajectoryHitData = {
|
|
71
|
-
/** True if the predicted mouse trajectory has intersected the element's expanded bounds. */
|
|
72
|
-
isTrajectoryHit: boolean;
|
|
73
|
-
/** The timestamp when the last trajectory hit occurred. */
|
|
74
|
-
trajectoryHitTime: number;
|
|
75
|
-
/** Timeout ID for expiring the trajectory hit state. */
|
|
76
|
-
trajectoryHitExpirationTimeoutId?: ReturnType<typeof setTimeout>;
|
|
77
|
-
};
|
|
78
67
|
type ForesightRegisterResult = {
|
|
79
|
-
/** Whether the current device is a touch device. This is important as ForesightJS only works based on cursor movement. If the user is using a touch device you should handle prefetching differently
|
|
68
|
+
/** Whether the current device is a touch device. This is important as ForesightJS only works based on cursor movement. If the user is using a touch device you should handle prefetching differently
|
|
69
|
+
* @deprecated As of version 3.3, ForesightJS handles touch devices internally with dedicated touch strategies
|
|
70
|
+
*/
|
|
80
71
|
isTouchDevice: boolean;
|
|
81
72
|
/** Whether the user has connection limitations (slow network (2g) or data saver enabled) that should prevent prefetching */
|
|
82
73
|
isLimitedConnection: boolean;
|
|
@@ -95,10 +86,6 @@ type ForesightElementData = Required<Pick<ForesightRegisterOptions, "callback" |
|
|
|
95
86
|
id: string;
|
|
96
87
|
/** The boundary information for the element. */
|
|
97
88
|
elementBounds: ElementBounds;
|
|
98
|
-
/**
|
|
99
|
-
* Represents trajectory hit related data for a foresight element. Only used for the manager
|
|
100
|
-
*/
|
|
101
|
-
trajectoryHitData: TrajectoryHitData;
|
|
102
89
|
/**
|
|
103
90
|
* Is the element intersecting with the viewport, usefull to track which element we should observe or not
|
|
104
91
|
* Can be @undefined in the split second the element is registering
|
|
@@ -203,6 +190,7 @@ type ForesightManagerData = {
|
|
|
203
190
|
globalCallbackHits: Readonly<CallbackHits>;
|
|
204
191
|
eventListeners: ReadonlyMap<keyof ForesightEventMap, ForesightEventListener[]>;
|
|
205
192
|
currentDeviceStrategy: CurrentDeviceStrategy;
|
|
193
|
+
activeElementCount: number;
|
|
206
194
|
};
|
|
207
195
|
type TouchDeviceStrategy = "none" | "viewport" | "onTouchStart";
|
|
208
196
|
type BaseForesightManagerSettings = {
|
|
@@ -361,7 +349,7 @@ interface ElementUnregisteredEvent extends ForesightBaseEvent {
|
|
|
361
349
|
type: "elementUnregistered";
|
|
362
350
|
elementData: ForesightElementData;
|
|
363
351
|
unregisterReason: ElementUnregisteredReason;
|
|
364
|
-
|
|
352
|
+
wasLastRegisteredElement: boolean;
|
|
365
353
|
}
|
|
366
354
|
/**
|
|
367
355
|
* The reason an element was unregistered from ForesightManager's tracking.
|
|
@@ -371,7 +359,7 @@ interface ElementUnregisteredEvent extends ForesightBaseEvent {
|
|
|
371
359
|
* - `devtools`: When clicking the trash icon in the devtools element tab
|
|
372
360
|
* - any other string
|
|
373
361
|
*/
|
|
374
|
-
type ElementUnregisteredReason = "
|
|
362
|
+
type ElementUnregisteredReason = "disconnected" | "apiCall" | "devtools" | (string & {});
|
|
375
363
|
interface ElementDataUpdatedEvent extends Omit<ForesightBaseEvent, "timestamp"> {
|
|
376
364
|
type: "elementDataUpdated";
|
|
377
365
|
elementData: ForesightElementData;
|
|
@@ -388,6 +376,7 @@ interface CallbackCompletedEventBase extends ForesightBaseEvent {
|
|
|
388
376
|
elementData: ForesightElementData;
|
|
389
377
|
hitType: CallbackHitType;
|
|
390
378
|
elapsed: number;
|
|
379
|
+
wasLastActiveElement: boolean;
|
|
391
380
|
}
|
|
392
381
|
type CallbackCompletedEvent = CallbackCompletedEventBase & {
|
|
393
382
|
status: callbackStatus;
|
|
@@ -442,11 +431,12 @@ interface ForesightBaseEvent {
|
|
|
442
431
|
declare class ForesightManager {
|
|
443
432
|
private static manager;
|
|
444
433
|
private elements;
|
|
434
|
+
private idCounter;
|
|
435
|
+
private activeElementCount;
|
|
445
436
|
private desktopHandler;
|
|
446
437
|
private touchDeviceHandler;
|
|
447
438
|
private handler;
|
|
448
439
|
private isSetup;
|
|
449
|
-
private idCounter;
|
|
450
440
|
private _globalCallbackHits;
|
|
451
441
|
private _globalSettings;
|
|
452
442
|
private pendingPointerEvent;
|
|
@@ -470,6 +460,7 @@ declare class ForesightManager {
|
|
|
470
460
|
unregister(element: ForesightElement, unregisterReason?: ElementUnregisteredReason): void;
|
|
471
461
|
private updateHitCounters;
|
|
472
462
|
reactivate(element: ForesightElement): void;
|
|
463
|
+
private clearReactivateTimeout;
|
|
473
464
|
private makeElementUnactive;
|
|
474
465
|
private callCallback;
|
|
475
466
|
private setDeviceStrategy;
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
function h(o,e,t,i){return o<e?console.warn(`ForesightJS: "${i}" value ${o} is below minimum bound ${e}, clamping to ${e}`):o>t&&console.warn(`ForesightJS: "${i}" value ${o} is above maximum bound ${t}, clamping to ${t}`),Math.min(Math.max(o,e),t)}function z(o){let e=window.innerWidth||document.documentElement.clientWidth,t=window.innerHeight||document.documentElement.clientHeight;return o.top<t&&o.bottom>0&&o.left<e&&o.right>0}function P(o){if(typeof o=="number"){let e=h(o,0,2e3,"hitslop");return{top:e,left:e,right:e,bottom:e}}return{top:h(o.top,0,2e3,"hitslop - top"),left:h(o.left,0,2e3,"hitslop - left"),right:h(o.right,0,2e3,"hitslop - right"),bottom:h(o.bottom,0,2e3,"hitslop - bottom")}}function S(o,e){return{left:o.left-e.left,right:o.right+e.right,top:o.top-e.top,bottom:o.bottom+e.bottom}}function H(o,e){return!o||!e?o===e:o.left===e.left&&o.right===e.right&&o.top===e.top&&o.bottom===e.bottom}function T(o,e){return o.x>=e.left&&o.x<=e.right&&o.y>=e.top&&o.y<=e.bottom}function K(){let o=N(),e=te();return{isTouchDevice:o,isLimitedConnection:e,shouldRegister:!o&&!e}}function N(){return window.matchMedia("(pointer: coarse)").matches&&navigator.maxTouchPoints>0}function te(){let o=navigator.connection;return o?/2g/.test(o.effectiveType)||o.saveData:!1}function A(o,e){return o!==void 0&&e!==o}var d=class{constructor(e){this._isConnected=!1;this.elements=e.elements,this.callCallback=e.callCallback,this.emit=e.emit,this.settings=e.settings}get isConnected(){return this._isConnected}disconnect(){this.isConnected&&(process.env.NODE_ENV==="development"&&console.log(`\u{1F50C} ${this.moduleName} disconnecting...`),this.abortController?.abort(`${this.moduleName} module disconnected`),this.onDisconnect(),this._isConnected=!1)}connect(){process.env.NODE_ENV==="development"&&console.log(`\u{1F50C} ${this.moduleName} connecting...`),this.onConnect(),this._isConnected=!0}createAbortController(){this.abortController&&!this.abortController.signal.aborted||(this.abortController=new AbortController,process.env.NODE_ENV==="development"&&console.log(`\u{1F39B}\uFE0F ${this.moduleName} created new AbortController`))}handleError(e,t){console.error(`${this.moduleName} error in ${t}:`,e)}};function I(o,e,t){let i=0,n=1,r=e.x-o.x,l=e.y-o.y,s=(a,c)=>{if(a===0){if(c<0)return!1}else{let u=c/a;if(a<0){if(u>n)return!1;u>i&&(i=u)}else{if(u<i)return!1;u<n&&(n=u)}}return!0};return!s(-r,o.x-t.left)||!s(r,t.right-o.x)||!s(-l,o.y-t.top)||!s(l,t.bottom-o.y)?!1:i<=n}function $(o,e,t){let i=performance.now(),n={point:o,time:i},{x:r,y:l}=o;if(e.add(n),e.length<2)return{x:r,y:l};let[s,a]=e.getFirstLast();if(!s||!a)return{x:r,y:l};let c=(a.time-s.time)*.001;if(c===0)return{x:r,y:l};let u=a.point.x-s.point.x,p=a.point.y-s.point.y,v=u/c,x=p/c,O=t*.001,w=r+v*O,V=l+x*O;return{x:w,y:V}}var C=class extends d{constructor(t){super(t.dependencies);this.moduleName="MousePredictor";this.trajectoryPositions=t.trajectoryPositions}onDisconnect(){}onConnect(){}updatePointerState(t){let i={x:t.clientX,y:t.clientY};this.trajectoryPositions.currentPoint=i,this.settings.enableMousePrediction?this.trajectoryPositions.predictedPoint=$(i,this.trajectoryPositions.positions,this.settings.trajectoryPredictionTime):this.trajectoryPositions.predictedPoint=i}processMouseMovement(t){try{this.updatePointerState(t);for(let i of this.elements.values()){if(!i.isIntersectingWithViewport||!i.callbackInfo.isCallbackActive||i.callbackInfo.isRunningCallback)continue;let n=i.elementBounds.expandedRect;if(this.settings.enableMousePrediction)I(this.trajectoryPositions.currentPoint,this.trajectoryPositions.predictedPoint,n)&&this.callCallback(i,{kind:"mouse",subType:"trajectory"});else if(T(this.trajectoryPositions.currentPoint,n)){this.callCallback(i,{kind:"mouse",subType:"hover"});return}}this.emit({type:"mouseTrajectoryUpdate",predictionEnabled:this.settings.enableMousePrediction,trajectoryPositions:this.trajectoryPositions})}catch(i){this.handleError(i,"processMouseMovement")}}};function Y(o,e){let i=e.top-o.top,n=e.left-o.left;return i<-1?"down":i>1?"up":n<-1?"right":n>1?"left":"none"}function X(o,e,t){let{x:i,y:n}=o,r={x:i,y:n};switch(e){case"down":r.y+=t;break;case"up":r.y-=t;break;case"left":r.x-=t;break;case"right":r.x+=t;break;case"none":break;default:}return r}var M=class extends d{constructor(t){super(t.dependencies);this.moduleName="ScrollPredictor";this.predictedScrollPoint=null;this.scrollDirection=null;this.trajectoryPositions=t.trajectoryPositions}onConnect(){}onDisconnect(){this.resetScrollProps()}resetScrollProps(){this.scrollDirection=null,this.predictedScrollPoint=null}handleScrollPrefetch(t,i){if(!(!t.isIntersectingWithViewport||t.callbackInfo.isRunningCallback||!t.callbackInfo.isCallbackActive))try{if(this.scrollDirection=this.scrollDirection??Y(t.elementBounds.originalRect,i),this.scrollDirection==="none")return;this.predictedScrollPoint=this.predictedScrollPoint??X(this.trajectoryPositions.currentPoint,this.scrollDirection,this.settings.scrollMargin),I(this.trajectoryPositions.currentPoint,this.predictedScrollPoint,t.elementBounds.expandedRect)&&this.callCallback(t,{kind:"scroll",subType:this.scrollDirection}),this.emit({type:"scrollTrajectoryUpdate",currentPoint:this.trajectoryPositions.currentPoint,predictedPoint:this.predictedScrollPoint,scrollDirection:this.scrollDirection})}catch(n){this.handleError(n,"handleScrollPrefetch")}}handleError(t,i){super.handleError(t,i),this.emit({type:"scrollTrajectoryUpdate",currentPoint:this.trajectoryPositions.currentPoint,predictedPoint:this.trajectoryPositions.currentPoint,scrollDirection:"none"})}};import{tabbable as ie}from"tabbable";function W(o,e,t,i){if(e!==null&&e>-1){let n=o?e-1:e+1;if(n>=0&&n<t.length&&t[n]===i)return n}return t.findIndex(n=>n===i)}var F=class extends d{constructor(t){super(t);this.moduleName="TabPredictor";this.lastKeyDown=null;this.tabbableElementsCache=[];this.lastFocusedIndex=null;this.handleKeyDown=t=>{t.key==="Tab"&&(this.lastKeyDown=t)};this.handleFocusIn=t=>{try{if(!this.lastKeyDown)return;let i=t.target;if(!(i instanceof HTMLElement))return;(!this.tabbableElementsCache.length||this.lastFocusedIndex===-1)&&(this.tabbableElementsCache=ie(document.documentElement));let n=this.lastKeyDown.shiftKey,r=W(n,this.lastFocusedIndex,this.tabbableElementsCache,i);this.lastFocusedIndex=r,this.lastKeyDown=null;let l=[];for(let s=0;s<=this.settings.tabOffset;s++){let a=n?r-s:r+s,c=this.tabbableElementsCache[a];c&&c instanceof Element&&this.elements.has(c)&&l.push(c)}for(let s of l){let a=this.elements.get(s);a&&!a.callbackInfo.isRunningCallback&&a.callbackInfo.isCallbackActive&&this.callCallback(a,{kind:"tab",subType:n?"reverse":"forwards"})}}catch(i){this.handleError(i,"handleFocusIn")}}}invalidateCache(){this.tabbableElementsCache=[],this.lastFocusedIndex=null}onConnect(){this.createAbortController(),document.addEventListener("keydown",this.handleKeyDown,{signal:this.abortController?.signal,passive:!0}),document.addEventListener("focusin",this.handleFocusIn,{signal:this.abortController?.signal,passive:!0})}onDisconnect(){this.tabbableElementsCache=[],this.lastFocusedIndex=null,this.lastKeyDown=null}};import{PositionObserver as oe}from"position-observer";var D=class{constructor(e){this.head=0;this.count=0;if(e<=0)throw new Error("CircularBuffer capacity must be greater than 0");this.capacity=e,this.buffer=new Array(e)}add(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.capacity,this.count<this.capacity&&this.count++}getFirst(){if(this.count!==0)return this.count<this.capacity?this.buffer[0]:this.buffer[this.head]}getLast(){if(this.count!==0){if(this.count<this.capacity)return this.buffer[this.count-1];{let e=(this.head-1+this.capacity)%this.capacity;return this.buffer[e]}}}getFirstLast(){if(this.count===0)return[void 0,void 0];if(this.count===1){let i=this.count<this.capacity?this.buffer[0]:this.buffer[this.head];return[i,i]}let e=this.getFirst(),t=this.getLast();return[e,t]}resize(e){if(e<=0)throw new Error("CircularBuffer capacity must be greater than 0");if(e===this.capacity)return;let t=this.getAllItems();if(this.capacity=e,this.buffer=new Array(e),this.head=0,this.count=0,t.length>e){let i=t.slice(-e);for(let n of i)this.add(n)}else for(let i of t)this.add(i)}getAllItems(){if(this.count===0)return[];let e=new Array(this.count);if(this.count<this.capacity)for(let t=0;t<this.count;t++)e[t]=this.buffer[t];else{let t=this.head;for(let i=0;i<this.capacity;i++){let n=(t+i)%this.capacity;e[i]=this.buffer[n]}}return e}clear(){this.head=0,this.count=0}get length(){return this.count}get size(){return this.capacity}get isFull(){return this.count===this.capacity}get isEmpty(){return this.count===0}};var m=class extends d{constructor(t){super(t);this.moduleName="DesktopHandler";this.positionObserver=null;this.trajectoryPositions={positions:new D(8),currentPoint:{x:0,y:0},predictedPoint:{x:0,y:0}};this.handlePositionChange=t=>{let i=this.settings.enableScrollPrediction;for(let n of t){let r=this.elements.get(n.target);r&&(i?this.scrollPredictor?.handleScrollPrefetch(r,n.boundingClientRect):T(this.trajectoryPositions.currentPoint,r.elementBounds.expandedRect)&&this.callCallback(r,{kind:"mouse",subType:"hover"}),this.handlePositionChangeDataUpdates(r,n))}i&&this.scrollPredictor?.resetScrollProps()};this.handlePositionChangeDataUpdates=(t,i)=>{let n=[],r=i.isIntersecting;t.isIntersectingWithViewport!==r&&(n.push("visibility"),t.isIntersectingWithViewport=r),r&&(n.push("bounds"),t.elementBounds={hitSlop:t.elementBounds.hitSlop,originalRect:i.boundingClientRect,expandedRect:S(i.boundingClientRect,t.elementBounds.hitSlop)}),n.length&&this.emit({type:"elementDataUpdated",elementData:t,updatedProps:n})};this.tabPredictor=new F(t),this.scrollPredictor=new M({dependencies:t,trajectoryPositions:this.trajectoryPositions}),this.mousePredictor=new C({dependencies:t,trajectoryPositions:this.trajectoryPositions})}invalidateTabCache(){this.tabPredictor?.invalidateCache()}processMouseMovement(t){this.mousePredictor.processMouseMovement(t)}onConnect(){this.settings.enableTabPrediction&&this.connectTabPredictor(),this.settings.enableScrollPrediction&&this.connectScrollPredictor(),this.connectMousePredictor(),this.positionObserver=new oe(this.handlePositionChange);for(let t of this.elements.keys())this.positionObserver.observe(t)}onDisconnect(){this.disconnectMousePredictor(),this.disconnectTabPredictor(),this.disconnectScrollPredictor(),this.positionObserver?.disconnect(),this.positionObserver=null}observeElement(t){this.positionObserver?.observe(t)}unobserveElement(t){this.positionObserver?.unobserve(t)}connectTabPredictor(){this.tabPredictor.connect()}connectScrollPredictor(){this.scrollPredictor.connect()}connectMousePredictor(){this.mousePredictor.connect()}disconnectTabPredictor(){this.tabPredictor.disconnect()}disconnectScrollPredictor(){this.scrollPredictor.disconnect()}disconnectMousePredictor(){this.mousePredictor.disconnect()}};var _=class extends d{constructor(t){super(t);this.moduleName="ViewportPredictor";this.intersectionObserver=null}onConnect(){this.intersectionObserver=new IntersectionObserver(this.handleViewportEnter.bind(this))}onDisconnect(){this.intersectionObserver?.disconnect(),this.intersectionObserver=null}observeElement(t){this.intersectionObserver?.observe(t)}unobserveElement(t){this.intersectionObserver?.unobserve(t)}handleViewportEnter(t){t.forEach(i=>{if(i.isIntersecting){let n=this.elements.get(i.target);n&&(this.callCallback(n,{kind:"viewport"}),this.unobserveElement(i.target))}})}};var k=class extends d{constructor(t){super(t);this.moduleName="TouchStartPredictor";this.handleTouchStart=t=>{let i=t.target,n=this.elements.get(i);n&&(this.callCallback(n,{kind:"touch"}),this.unobserveElement(i))}}onConnect(){this.createAbortController()}onDisconnect(){}observeElement(t){t instanceof HTMLElement&&t.addEventListener("touchstart",this.handleTouchStart,{signal:this.abortController?.signal})}unobserveElement(t){t instanceof HTMLElement&&t.removeEventListener("touchstart",this.handleTouchStart)}};var f=class extends d{constructor(t){super(t);this.moduleName="TouchDeviceHandler";this.viewportPredictor=new _(t),this.touchStartPredictor=new k(t),this.predictor=this.viewportPredictor}setTouchPredictor(){this.predictor.disconnect(),this.settings.touchDeviceStrategy==="viewport"?this.predictor=this.viewportPredictor:this.settings.touchDeviceStrategy==="onTouchStart"&&(this.predictor=this.touchStartPredictor),this.predictor.connect();for(let t of this.elements.keys())this.predictor.observeElement(t)}onDisconnect(){this.predictor.disconnect()}onConnect(){this.setTouchPredictor()}observeElement(t){this.predictor.observeElement(t)}unobserveElement(t){this.predictor.unobserveElement(t)}};var B=class o{constructor(e){this.elements=new Map;this.isSetup=!1;this.idCounter=0;this._globalCallbackHits={mouse:{hover:0,trajectory:0},tab:{forwards:0,reverse:0},scroll:{down:0,left:0,right:0,up:0},touch:0,viewport:0,total:0};this._globalSettings={debug:!1,enableMousePrediction:!0,enableScrollPrediction:!0,positionHistorySize:8,trajectoryPredictionTime:120,scrollMargin:150,defaultHitSlop:{top:0,left:0,right:0,bottom:0},enableTabPrediction:!0,tabOffset:2,touchDeviceStrategy:"viewport"};this.pendingPointerEvent=null;this.rafId=null;this.domObserver=null;this.eventListeners=new Map;this.currentDeviceStrategy=N()?"touch":"mouse";this.handlePointerMove=e=>{e.pointerType!=this.currentDeviceStrategy&&(this.emit({type:"deviceStrategyChanged",timestamp:Date.now(),newStrategy:e.pointerType,oldStrategy:this.currentDeviceStrategy}),this.setDeviceStrategy(this.currentDeviceStrategy=e.pointerType)),this.pendingPointerEvent=e,!this.rafId&&(this.rafId=requestAnimationFrame(()=>{if(this.handler instanceof f){this.rafId=null;return}this.pendingPointerEvent&&this.handler.processMouseMovement(this.pendingPointerEvent),this.rafId=null}))};this.handleDomMutations=e=>{e.length&&this.desktopHandler?.invalidateTabCache();for(let t of e)if(t.type==="childList"&&t.removedNodes.length>0)for(let i of this.elements.keys())i.isConnected||this.unregister(i,"disconnected")};e!==void 0&&this.initializeManagerSettings(e);let t={elements:this.elements,callCallback:this.callCallback.bind(this),emit:this.emit.bind(this),settings:this._globalSettings};this.desktopHandler=new m(t),this.touchDeviceHandler=new f(t),this.handler=this.currentDeviceStrategy==="mouse"?this.desktopHandler:this.touchDeviceHandler,this.initializeGlobalListeners()}generateId(){return`foresight-${++this.idCounter}`}static initialize(e){return this.isInitiated||(o.manager=new o(e)),o.manager}addEventListener(e,t,i){if(i?.signal?.aborted)return()=>{};let n=this.eventListeners.get(e)??[];n.push(t),this.eventListeners.set(e,n),i?.signal?.addEventListener("abort",()=>this.removeEventListener(e,t))}removeEventListener(e,t){let i=this.eventListeners.get(e);if(!i)return;let n=i.indexOf(t);n>-1&&i.splice(n,1)}emit(e){let t=this.eventListeners.get(e.type)?.slice();if(t)for(let i=0;i<t.length;i++)try{t[i](e)}catch(n){console.error(`Error in ForesightManager event listener ${i} for ${e.type}:`,n)}}get getManagerData(){return{registeredElements:this.elements,globalSettings:this._globalSettings,globalCallbackHits:this._globalCallbackHits,eventListeners:this.eventListeners,currentDeviceStrategy:this.currentDeviceStrategy}}static get isInitiated(){return!!o.manager}static get instance(){return this.initialize()}get registeredElements(){return this.elements}register({element:e,callback:t,hitSlop:i,name:n,meta:r,reactivateAfter:l}){let{isTouchDevice:s,isLimitedConnection:a}=K(),c=this.elements.get(e);if(c)return c.registerCount++,{isLimitedConnection:a,isTouchDevice:s,isRegistered:!1,unregister:()=>{}};let u=e.getBoundingClientRect(),p=i?P(i):this._globalSettings.defaultHitSlop,v={id:this.generateId(),element:e,callback:t,elementBounds:{originalRect:u,expandedRect:S(u,p),hitSlop:p},trajectoryHitData:{isTrajectoryHit:!1,trajectoryHitTime:0,trajectoryHitExpirationTimeoutId:void 0},name:n||e.id||"unnamed",isIntersectingWithViewport:z(u),registerCount:1,meta:r??{},callbackInfo:{callbackFiredCount:0,lastCallbackInvokedAt:void 0,lastCallbackCompletedAt:void 0,lastCallbackRuntime:void 0,lastCallbackStatus:void 0,lastCallbackErrorMessage:void 0,reactivateAfter:l??1/0,isCallbackActive:!0,isRunningCallback:!1,reactivateTimeoutId:void 0}};return this.elements.set(e,v),this.handler.observeElement(e),this.emit({type:"elementRegistered",timestamp:Date.now(),elementData:v}),{isTouchDevice:s,isLimitedConnection:a,isRegistered:!0,unregister:()=>{}}}unregister(e,t){let i=this.elements.get(e);if(!i)return;i?.trajectoryHitData.trajectoryHitExpirationTimeoutId&&clearTimeout(i.trajectoryHitData.trajectoryHitExpirationTimeoutId),i?.callbackInfo.reactivateTimeoutId&&clearTimeout(i.callbackInfo.reactivateTimeoutId),this.handler.unobserveElement(e),this.elements.delete(e);let n=this.elements.size===0&&this.isSetup;i&&this.emit({type:"elementUnregistered",elementData:i,timestamp:Date.now(),unregisterReason:t??"by user",wasLastElement:n})}updateHitCounters(e){switch(e.kind){case"mouse":this._globalCallbackHits.mouse[e.subType]++;break;case"tab":this._globalCallbackHits.tab[e.subType]++;break;case"scroll":this._globalCallbackHits.scroll[e.subType]++;break;case"touch":this._globalCallbackHits.touch++;break;case"viewport":this._globalCallbackHits.viewport++;break;default:}this._globalCallbackHits.total++}reactivate(e){let t=this.elements.get(e);t&&(t.callbackInfo.reactivateTimeoutId&&(clearTimeout(t.callbackInfo.reactivateTimeoutId),t.callbackInfo.reactivateTimeoutId=void 0),t.callbackInfo.isRunningCallback||(t.callbackInfo.isCallbackActive=!0,this.handler.observeElement(e),this.emit({type:"elementReactivated",elementData:t,timestamp:Date.now()})))}makeElementUnactive(e){e.callbackInfo.callbackFiredCount++,e.callbackInfo.lastCallbackInvokedAt=Date.now(),e.callbackInfo.isRunningCallback=!0,e.callbackInfo.reactivateTimeoutId&&(clearTimeout(e.callbackInfo.reactivateTimeoutId),e.callbackInfo.reactivateTimeoutId=void 0),e?.trajectoryHitData.trajectoryHitExpirationTimeoutId&&clearTimeout(e.trajectoryHitData.trajectoryHitExpirationTimeoutId)}callCallback(e,t){if(e.callbackInfo.isRunningCallback||!e.callbackInfo.isCallbackActive)return;this.makeElementUnactive(e),(async()=>{this.updateHitCounters(t),this.emit({type:"callbackInvoked",timestamp:Date.now(),elementData:e,hitType:t});let n=performance.now(),r,l=null;try{await e.callback(),r="success"}catch(s){l=s instanceof Error?s.message:String(s),r="error",console.error(`Error in callback for element ${e.name} (${e.element.tagName}):`,s)}e.callbackInfo.lastCallbackCompletedAt=Date.now(),this.emit({type:"callbackCompleted",timestamp:Date.now(),elementData:e,hitType:t,elapsed:e.callbackInfo.lastCallbackRuntime=performance.now()-n,status:e.callbackInfo.lastCallbackStatus=r,errorMessage:e.callbackInfo.lastCallbackErrorMessage=l}),e.callbackInfo.isRunningCallback=!1,e.callbackInfo.isCallbackActive=!1,this.handler.unobserveElement(e.element),e.callbackInfo.reactivateAfter!==1/0&&e.callbackInfo.reactivateAfter>0&&(e.callbackInfo.reactivateTimeoutId=setTimeout(()=>{this.reactivate(e.element)},e.callbackInfo.reactivateAfter))})()}setDeviceStrategy(e){this.handler.disconnect(),this.handler=e==="mouse"?this.desktopHandler:this.touchDeviceHandler,this.handler.connect()}initializeGlobalListeners(){this.isSetup||(this.setDeviceStrategy(this.currentDeviceStrategy),document.addEventListener("pointermove",this.handlePointerMove),this.domObserver=new MutationObserver(this.handleDomMutations),this.domObserver.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1}),this.isSetup=!0)}removeGlobalListeners(){this.isSetup=!1,this.domObserver?.disconnect(),this.domObserver=null,this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.pendingPointerEvent=null}forceUpdateAllElementBounds(){for(let[,e]of this.elements)e.isIntersectingWithViewport&&this.forceUpdateElementBounds(e)}forceUpdateElementBounds(e){let t=e.element.getBoundingClientRect(),i=S(t,e.elementBounds.hitSlop);if(!H(i,e.elementBounds.expandedRect)){let n={...e,elementBounds:{...e.elementBounds,originalRect:t,expandedRect:i}};this.elements.set(e.element,n),this.emit({type:"elementDataUpdated",elementData:n,updatedProps:["bounds"]})}}initializeManagerSettings(e){this.updateNumericSettings(e.trajectoryPredictionTime,"trajectoryPredictionTime",10,200),this.updateNumericSettings(e.positionHistorySize,"positionHistorySize",2,30),this.updateNumericSettings(e.scrollMargin,"scrollMargin",30,300),this.updateNumericSettings(e.tabOffset,"tabOffset",0,20),this.updateBooleanSetting(e.enableMousePrediction,"enableMousePrediction"),this.updateBooleanSetting(e.enableScrollPrediction,"enableScrollPrediction"),this.updateBooleanSetting(e.enableTabPrediction,"enableTabPrediction"),e.defaultHitSlop!==void 0&&(this._globalSettings.defaultHitSlop=P(e.defaultHitSlop)),e.touchDeviceStrategy!==void 0&&(this._globalSettings.touchDeviceStrategy=e.touchDeviceStrategy),e.debug!==void 0&&(this._globalSettings.debug=e.debug),console.log(this._globalSettings)}updateNumericSettings(e,t,i,n){return A(e,this._globalSettings[t])?(this._globalSettings[t]=h(e,i,n,t),!0):!1}updateBooleanSetting(e,t){return A(e,this._globalSettings[t])?(this._globalSettings[t]=e,!0):!1}alterGlobalSettings(e){let t=[],i=this._globalSettings.trajectoryPredictionTime;this.updateNumericSettings(e?.trajectoryPredictionTime,"trajectoryPredictionTime",10,200)&&t.push({setting:"trajectoryPredictionTime",oldValue:i,newValue:this._globalSettings.trajectoryPredictionTime});let r=this._globalSettings.positionHistorySize;this.updateNumericSettings(e?.positionHistorySize,"positionHistorySize",2,30)&&(t.push({setting:"positionHistorySize",oldValue:r,newValue:this._globalSettings.positionHistorySize}),this.desktopHandler.trajectoryPositions.positions.resize(this._globalSettings.positionHistorySize));let s=this._globalSettings.scrollMargin;if(this.updateNumericSettings(e?.scrollMargin,"scrollMargin",30,300)){let g=this._globalSettings.scrollMargin;t.push({setting:"scrollMargin",oldValue:s,newValue:g})}let c=this._globalSettings.tabOffset;this.updateNumericSettings(e?.tabOffset,"tabOffset",0,20)&&(this._globalSettings.tabOffset=h(e.tabOffset,0,20,"tabOffset"),t.push({setting:"tabOffset",oldValue:c,newValue:this._globalSettings.tabOffset}));let p=this._globalSettings.enableMousePrediction;this.updateBooleanSetting(e?.enableMousePrediction,"enableMousePrediction")&&t.push({setting:"enableMousePrediction",oldValue:p,newValue:this._globalSettings.enableMousePrediction});let x=this._globalSettings.enableScrollPrediction;this.updateBooleanSetting(e?.enableScrollPrediction,"enableScrollPrediction")&&(this.handler instanceof m&&(this._globalSettings.enableScrollPrediction?this.handler.connectScrollPredictor():this.handler.disconnectScrollPredictor()),t.push({setting:"enableScrollPrediction",oldValue:x,newValue:this._globalSettings.enableScrollPrediction}));let w=this._globalSettings.enableTabPrediction;if(this.updateBooleanSetting(e?.enableTabPrediction,"enableTabPrediction")&&(this.handler instanceof m&&(this._globalSettings.enableTabPrediction?this.handler.connectTabPredictor():this.handler.disconnectTabPredictor()),t.push({setting:"enableTabPrediction",oldValue:w,newValue:this._globalSettings.enableTabPrediction})),e?.defaultHitSlop!==void 0){let g=this._globalSettings.defaultHitSlop,b=P(e.defaultHitSlop);H(g,b)||(this._globalSettings.defaultHitSlop=b,t.push({setting:"defaultHitSlop",oldValue:g,newValue:b}),this.forceUpdateAllElementBounds())}if(e?.touchDeviceStrategy!==void 0){let g=this._globalSettings.touchDeviceStrategy,b=e.touchDeviceStrategy;this._globalSettings.touchDeviceStrategy=b,t.push({setting:"touchDeviceStrategy",oldValue:g,newValue:b}),this.handler instanceof f&&this.handler.setTouchPredictor()}t.length>0&&this.emit({type:"managerSettingsChanged",timestamp:Date.now(),managerData:this.getManagerData,updatedSettings:t})}};export{B as ForesightManager};
|
|
1
|
+
function p(n,e,t,i){return n<e?console.warn(`ForesightJS: "${i}" value ${n} is below minimum bound ${e}, clamping to ${e}`):n>t&&console.warn(`ForesightJS: "${i}" value ${n} is above maximum bound ${t}, clamping to ${t}`),Math.min(Math.max(n,e),t)}function z(n){if(typeof window>"u"||typeof document>"u")return!1;let e=window.innerWidth||document.documentElement.clientWidth,t=window.innerHeight||document.documentElement.clientHeight;return n.top<t&&n.bottom>0&&n.left<e&&n.right>0}function T(n){if(typeof n=="number"){let e=p(n,0,2e3,"hitslop");return{top:e,left:e,right:e,bottom:e}}return{top:p(n.top,0,2e3,"hitslop - top"),left:p(n.left,0,2e3,"hitslop - left"),right:p(n.right,0,2e3,"hitslop - right"),bottom:p(n.bottom,0,2e3,"hitslop - bottom")}}function P(n,e){return{left:n.left-e.left,right:n.right+e.right,top:n.top-e.top,bottom:n.bottom+e.bottom}}function w(n,e){return!n||!e?n===e:n.left===e.left&&n.right===e.right&&n.top===e.top&&n.bottom===e.bottom}function C(n,e){return n.x>=e.left&&n.x<=e.right&&n.y>=e.top&&n.y<=e.bottom}function K(){let n=A(),e=te();return{isTouchDevice:n,isLimitedConnection:e,shouldRegister:!e}}function A(){return typeof window>"u"||typeof navigator>"u"?!1:window.matchMedia("(pointer: coarse)").matches&&navigator.maxTouchPoints>0}function te(){let n=navigator.connection;return n?/2g/.test(n.effectiveType)||n.saveData:!1}function N(n,e){return n!==void 0&&e!==n}var u=class{constructor(e){this._isConnected=!1;this.elements=e.elements,this.callCallback=e.callCallback,this.emit=e.emit,this.settings=e.settings}get isConnected(){return this._isConnected}disconnect(){this.isConnected&&(this.devLog(`Disconnecting ${this.moduleName}...`),this.abortController?.abort(`${this.moduleName} module disconnected`),this.onDisconnect(),this._isConnected=!1)}connect(){this.devLog(`Connecting ${this.moduleName}...`),this.onConnect(),this._isConnected=!0}devLog(e){process.env.NODE_ENV==="development"&&console.log(`\u{1F6E0}\uFE0F ${this.moduleName}: ${e}`)}createAbortController(){this.abortController&&!this.abortController.signal.aborted||(this.abortController=new AbortController,this.devLog(`Created new AbortController for ${this.moduleName}`))}};function I(n,e,t){let i=0,o=1,r=e.x-n.x,l=e.y-n.y,a=(s,d)=>{if(s===0){if(d<0)return!1}else{let c=d/s;if(s<0){if(c>o)return!1;c>i&&(i=c)}else{if(c<i)return!1;c<o&&(o=c)}}return!0};return!a(-r,n.x-t.left)||!a(r,t.right-n.x)||!a(-l,n.y-t.top)||!a(l,t.bottom-n.y)?!1:i<=o}function Y(n,e,t){let i=performance.now(),o={point:n,time:i},{x:r,y:l}=n;if(e.add(o),e.length<2)return{x:r,y:l};let[a,s]=e.getFirstLast();if(!a||!s)return{x:r,y:l};let d=(s.time-a.time)*.001;if(d===0)return{x:r,y:l};let c=s.point.x-a.point.x,h=s.point.y-a.point.y,y=c/d,g=h/d,x=t*.001,L=r+y*x,V=l+g*x;return{x:L,y:V}}var F=class extends u{constructor(t){super(t.dependencies);this.moduleName="MousePredictor";this.trajectoryPositions=t.trajectoryPositions}updatePointerState(t){let i={x:t.clientX,y:t.clientY};this.trajectoryPositions.currentPoint=i,this.settings.enableMousePrediction?this.trajectoryPositions.predictedPoint=Y(i,this.trajectoryPositions.positions,this.settings.trajectoryPredictionTime):this.trajectoryPositions.predictedPoint=i}processMouseMovement(t){this.updatePointerState(t);let i=this.settings.enableMousePrediction,o=this.trajectoryPositions.currentPoint;for(let r of this.elements.values()){if(!r.isIntersectingWithViewport||!r.callbackInfo.isCallbackActive||r.callbackInfo.isRunningCallback)continue;let l=r.elementBounds.expandedRect;if(i)I(o,this.trajectoryPositions.predictedPoint,l)&&this.callCallback(r,{kind:"mouse",subType:"trajectory"});else if(C(o,l)){this.callCallback(r,{kind:"mouse",subType:"hover"});return}}this.emit({type:"mouseTrajectoryUpdate",predictionEnabled:i,trajectoryPositions:this.trajectoryPositions})}onDisconnect(){}onConnect(){}};function $(n,e){let i=e.top-n.top,o=e.left-n.left;return i<-1?"down":i>1?"up":o<-1?"right":o>1?"left":"none"}function G(n,e,t){let{x:i,y:o}=n,r={x:i,y:o};switch(e){case"down":r.y+=t;break;case"up":r.y-=t;break;case"left":r.x-=t;break;case"right":r.x+=t;break;case"none":break;default:}return r}var M=class extends u{constructor(t){super(t.dependencies);this.moduleName="ScrollPredictor";this.predictedScrollPoint=null;this.scrollDirection=null;this.onDisconnect=()=>this.resetScrollProps();this.trajectoryPositions=t.trajectoryPositions}resetScrollProps(){this.scrollDirection=null,this.predictedScrollPoint=null}handleScrollPrefetch(t,i){!t.isIntersectingWithViewport||t.callbackInfo.isRunningCallback||!t.callbackInfo.isCallbackActive||(this.scrollDirection=this.scrollDirection??$(t.elementBounds.originalRect,i),this.scrollDirection!=="none"&&(this.predictedScrollPoint=this.predictedScrollPoint??G(this.trajectoryPositions.currentPoint,this.scrollDirection,this.settings.scrollMargin),I(this.trajectoryPositions.currentPoint,this.predictedScrollPoint,t.elementBounds.expandedRect)&&this.callCallback(t,{kind:"scroll",subType:this.scrollDirection}),this.emit({type:"scrollTrajectoryUpdate",currentPoint:this.trajectoryPositions.currentPoint,predictedPoint:this.predictedScrollPoint,scrollDirection:this.scrollDirection})))}onConnect(){}};import{tabbable as ie}from"tabbable";function X(n,e,t,i){if(e!==null&&e>-1){let o=n?e-1:e+1;if(o>=0&&o<t.length&&t[o]===i)return o}return t.findIndex(o=>o===i)}var D=class extends u{constructor(t){super(t);this.moduleName="TabPredictor";this.lastKeyDown=null;this.tabbableElementsCache=[];this.lastFocusedIndex=null;this.handleKeyDown=t=>{t.key==="Tab"&&(this.lastKeyDown=t)};this.handleFocusIn=t=>{if(!this.lastKeyDown)return;let i=t.target;if(!(i instanceof HTMLElement))return;(!this.tabbableElementsCache.length||this.lastFocusedIndex===-1)&&(this.tabbableElementsCache=ie(document.documentElement));let o=this.lastKeyDown.shiftKey,r=X(o,this.lastFocusedIndex,this.tabbableElementsCache,i);this.lastFocusedIndex=r,this.lastKeyDown=null;let l=[],a=this.settings.tabOffset,s=this.elements;for(let d=0;d<=a;d++){let c=o?r-d:r+d,h=this.tabbableElementsCache[c];h&&h instanceof Element&&s.has(h)&&l.push(h)}for(let d of l){let c=s.get(d);c&&!c.callbackInfo.isRunningCallback&&c.callbackInfo.isCallbackActive&&this.callCallback(c,{kind:"tab",subType:o?"reverse":"forwards"})}}}invalidateCache(){this.tabbableElementsCache=[],this.lastFocusedIndex=null}onConnect(){typeof document>"u"||(this.createAbortController(),document.addEventListener("keydown",this.handleKeyDown,{signal:this.abortController?.signal,passive:!0}),document.addEventListener("focusin",this.handleFocusIn,{signal:this.abortController?.signal,passive:!0}))}onDisconnect(){this.tabbableElementsCache=[],this.lastFocusedIndex=null,this.lastKeyDown=null}};import{PositionObserver as ne}from"position-observer";var R=class{constructor(e){this.head=0;this.count=0;if(e<=0)throw new Error("CircularBuffer capacity must be greater than 0");this.capacity=e,this.buffer=new Array(e)}add(e){this.buffer[this.head]=e,this.head=(this.head+1)%this.capacity,this.count<this.capacity&&this.count++}getFirst(){if(this.count!==0)return this.count<this.capacity?this.buffer[0]:this.buffer[this.head]}getLast(){if(this.count!==0){if(this.count<this.capacity)return this.buffer[this.count-1];{let e=(this.head-1+this.capacity)%this.capacity;return this.buffer[e]}}}getFirstLast(){if(this.count===0)return[void 0,void 0];if(this.count===1){let i=this.count<this.capacity?this.buffer[0]:this.buffer[this.head];return[i,i]}let e=this.getFirst(),t=this.getLast();return[e,t]}resize(e){if(e<=0)throw new Error("CircularBuffer capacity must be greater than 0");if(e===this.capacity)return;let t=this.getAllItems();if(this.capacity=e,this.buffer=new Array(e),this.head=0,this.count=0,t.length>e){let i=t.slice(-e);for(let o of i)this.add(o)}else for(let i of t)this.add(i)}getAllItems(){if(this.count===0)return[];let e=new Array(this.count);if(this.count<this.capacity)for(let t=0;t<this.count;t++)e[t]=this.buffer[t];else{let t=this.head;for(let i=0;i<this.capacity;i++){let o=(t+i)%this.capacity;e[i]=this.buffer[o]}}return e}clear(){this.head=0,this.count=0}get length(){return this.count}get size(){return this.capacity}get isFull(){return this.count===this.capacity}get isEmpty(){return this.count===0}};var f=class extends u{constructor(t){super(t);this.moduleName="DesktopHandler";this.positionObserver=null;this.trajectoryPositions={positions:new R(8),currentPoint:{x:0,y:0},predictedPoint:{x:0,y:0}};this.handlePositionChange=t=>{let i=this.settings.enableScrollPrediction;for(let o of t){let r=this.elements.get(o.target);r&&(i?this.scrollPredictor?.handleScrollPrefetch(r,o.boundingClientRect):this.checkForMouseHover(r),this.handlePositionChangeDataUpdates(r,o))}i&&this.scrollPredictor?.resetScrollProps()};this.checkForMouseHover=t=>{C(this.trajectoryPositions.currentPoint,t.elementBounds.expandedRect)&&this.callCallback(t,{kind:"mouse",subType:"hover"})};this.handlePositionChangeDataUpdates=(t,i)=>{let o=[],r=i.isIntersecting;t.isIntersectingWithViewport!==r&&(o.push("visibility"),t.isIntersectingWithViewport=r),r&&(o.push("bounds"),t.elementBounds={hitSlop:t.elementBounds.hitSlop,originalRect:i.boundingClientRect,expandedRect:P(i.boundingClientRect,t.elementBounds.hitSlop)}),o.length&&this.emit({type:"elementDataUpdated",elementData:t,updatedProps:o})};this.processMouseMovement=t=>this.mousePredictor.processMouseMovement(t);this.invalidateTabCache=()=>this.tabPredictor?.invalidateCache();this.observeElement=t=>this.positionObserver?.observe(t);this.unobserveElement=t=>this.positionObserver?.unobserve(t);this.connectTabPredictor=()=>this.tabPredictor.connect();this.connectScrollPredictor=()=>this.scrollPredictor.connect();this.connectMousePredictor=()=>this.mousePredictor.connect();this.disconnectTabPredictor=()=>this.tabPredictor.disconnect();this.disconnectScrollPredictor=()=>this.scrollPredictor.disconnect();this.disconnectMousePredictor=()=>this.mousePredictor.disconnect();this.tabPredictor=new D(t),this.scrollPredictor=new M({dependencies:t,trajectoryPositions:this.trajectoryPositions}),this.mousePredictor=new F({dependencies:t,trajectoryPositions:this.trajectoryPositions})}onConnect(){this.settings.enableTabPrediction&&this.connectTabPredictor(),this.settings.enableScrollPrediction&&this.connectScrollPredictor(),this.connectMousePredictor(),this.positionObserver=new ne(this.handlePositionChange);for(let t of this.elements.keys())this.positionObserver.observe(t)}onDisconnect(){this.disconnectMousePredictor(),this.disconnectTabPredictor(),this.disconnectScrollPredictor(),this.positionObserver?.disconnect(),this.positionObserver=null}};var _=class extends u{constructor(t){super(t);this.moduleName="ViewportPredictor";this.intersectionObserver=null;this.onConnect=()=>this.intersectionObserver=new IntersectionObserver(this.handleViewportEnter);this.observeElement=t=>this.intersectionObserver?.observe(t);this.unobserveElement=t=>this.intersectionObserver?.unobserve(t);this.handleViewportEnter=t=>{for(let i of t){if(!i.isIntersecting)continue;let o=this.elements.get(i.target);o&&(this.callCallback(o,{kind:"viewport"}),this.unobserveElement(i.target))}}}onDisconnect(){this.intersectionObserver?.disconnect(),this.intersectionObserver=null}};var k=class extends u{constructor(t){super(t);this.moduleName="TouchStartPredictor";this.onConnect=()=>this.createAbortController();this.onDisconnect=()=>{};this.handleTouchStart=t=>{let i=t.target,o=this.elements.get(i);o&&(this.callCallback(o,{kind:"touch"}),this.unobserveElement(i))}}observeElement(t){t instanceof HTMLElement&&t.addEventListener("touchstart",this.handleTouchStart,{signal:this.abortController?.signal})}unobserveElement(t){t instanceof HTMLElement&&t.removeEventListener("touchstart",this.handleTouchStart)}};var v=class extends u{constructor(t){super(t);this.moduleName="TouchDeviceHandler";this.predictor=null;this.onDisconnect=()=>this.predictor?.disconnect();this.onConnect=()=>this.setTouchPredictor();this.observeElement=t=>this.predictor?.observeElement(t);this.unobserveElement=t=>this.predictor?.unobserveElement(t);this.viewportPredictor=new _(t),this.touchStartPredictor=new k(t),this.predictor=this.viewportPredictor}setTouchPredictor(){switch(this.predictor?.disconnect(),this.settings.touchDeviceStrategy){case"viewport":this.predictor=this.viewportPredictor;break;case"onTouchStart":this.predictor=this.touchStartPredictor;break;case"none":this.predictor=null;return;default:this.settings.touchDeviceStrategy}this.predictor?.connect();for(let t of this.elements.keys())this.predictor?.observeElement(t)}};var B=class n{constructor(e){this.elements=new Map;this.idCounter=0;this.activeElementCount=0;this.isSetup=!1;this._globalCallbackHits={mouse:{hover:0,trajectory:0},tab:{forwards:0,reverse:0},scroll:{down:0,left:0,right:0,up:0},touch:0,viewport:0,total:0};this._globalSettings={debug:!1,enableMousePrediction:!0,enableScrollPrediction:!0,positionHistorySize:8,trajectoryPredictionTime:120,scrollMargin:150,defaultHitSlop:{top:0,left:0,right:0,bottom:0},enableTabPrediction:!0,tabOffset:2,touchDeviceStrategy:"onTouchStart"};this.pendingPointerEvent=null;this.rafId=null;this.domObserver=null;this.eventListeners=new Map;this.currentDeviceStrategy=A()?"touch":"mouse";this.handlePointerMove=e=>{this.pendingPointerEvent=e,e.pointerType!=this.currentDeviceStrategy&&(this.emit({type:"deviceStrategyChanged",timestamp:Date.now(),newStrategy:e.pointerType,oldStrategy:this.currentDeviceStrategy}),this.setDeviceStrategy(this.currentDeviceStrategy=e.pointerType)),!this.rafId&&(this.rafId=requestAnimationFrame(()=>{if(this.handler instanceof v){this.rafId=null;return}this.pendingPointerEvent&&this.handler.processMouseMovement(this.pendingPointerEvent),this.rafId=null}))};this.handleDomMutations=e=>{if(!e.length)return;this.desktopHandler?.invalidateTabCache();let t=!1;for(let i=0;i<e.length;i++){let o=e[i];if(o.type==="childList"&&o.removedNodes.length>0){t=!0;break}}if(t)for(let i of this.elements.keys())i.isConnected||this.unregister(i,"disconnected")};e!==void 0&&this.initializeManagerSettings(e);let t={elements:this.elements,callCallback:this.callCallback.bind(this),emit:this.emit.bind(this),settings:this._globalSettings};this.desktopHandler=new f(t),this.touchDeviceHandler=new v(t),this.handler=this.currentDeviceStrategy==="mouse"?this.desktopHandler:this.touchDeviceHandler,this.initializeGlobalListeners()}generateId(){return`foresight-${++this.idCounter}`}static initialize(e){return this.isInitiated||(n.manager=new n(e)),n.manager}addEventListener(e,t,i){if(i?.signal?.aborted)return()=>{};let o=this.eventListeners.get(e)??[];o.push(t),this.eventListeners.set(e,o),i?.signal?.addEventListener("abort",()=>this.removeEventListener(e,t))}removeEventListener(e,t){let i=this.eventListeners.get(e);if(!i)return;let o=i.indexOf(t);o>-1&&i.splice(o,1)}emit(e){let t=this.eventListeners.get(e.type)?.slice();if(t)for(let i=0;i<t.length;i++)try{t[i](e)}catch(o){console.error(`Error in ForesightManager event listener ${i} for ${e.type}:`,o)}}get getManagerData(){return{registeredElements:this.elements,globalSettings:this._globalSettings,globalCallbackHits:this._globalCallbackHits,eventListeners:this.eventListeners,currentDeviceStrategy:this.currentDeviceStrategy,activeElementCount:this.activeElementCount}}static get isInitiated(){return!!n.manager}static get instance(){return this.initialize()}get registeredElements(){return this.elements}register({element:e,callback:t,hitSlop:i,name:o,meta:r,reactivateAfter:l}){let{isTouchDevice:a,isLimitedConnection:s,shouldRegister:d}=K();if(!d)return{isLimitedConnection:s,isTouchDevice:a,isRegistered:!1,unregister:()=>{}};let c=this.elements.get(e);if(c)return c.registerCount++,{isLimitedConnection:s,isTouchDevice:a,isRegistered:!1,unregister:()=>{}};this.isSetup||this.initializeGlobalListeners();let h=e.getBoundingClientRect(),y=i?T(i):this._globalSettings.defaultHitSlop,g={id:this.generateId(),element:e,callback:t,elementBounds:{originalRect:h,expandedRect:P(h,y),hitSlop:y},name:o||e.id||"unnamed",isIntersectingWithViewport:z(h),registerCount:1,meta:r??{},callbackInfo:{callbackFiredCount:0,lastCallbackInvokedAt:void 0,lastCallbackCompletedAt:void 0,lastCallbackRuntime:void 0,lastCallbackStatus:void 0,lastCallbackErrorMessage:void 0,reactivateAfter:l??1/0,isCallbackActive:!0,isRunningCallback:!1,reactivateTimeoutId:void 0}};return this.elements.set(e,g),this.activeElementCount++,this.handler.observeElement(e),this.emit({type:"elementRegistered",timestamp:Date.now(),elementData:g}),{isTouchDevice:a,isLimitedConnection:s,isRegistered:!0,unregister:()=>{this.unregister(e)}}}unregister(e,t){let i=this.elements.get(e);if(!i)return;this.clearReactivateTimeout(i),this.handler.unobserveElement(e),this.elements.delete(e),i.callbackInfo.isCallbackActive&&this.activeElementCount--;let o=this.elements.size===0&&this.isSetup;o&&this.removeGlobalListeners(),i&&this.emit({type:"elementUnregistered",elementData:i,timestamp:Date.now(),unregisterReason:t??"by user",wasLastRegisteredElement:o})}updateHitCounters(e){switch(e.kind){case"mouse":this._globalCallbackHits.mouse[e.subType]++;break;case"tab":this._globalCallbackHits.tab[e.subType]++;break;case"scroll":this._globalCallbackHits.scroll[e.subType]++;break;case"touch":this._globalCallbackHits.touch++;break;case"viewport":this._globalCallbackHits.viewport++;break;default:}this._globalCallbackHits.total++}reactivate(e){let t=this.elements.get(e);t&&(this.isSetup||this.initializeGlobalListeners(),this.clearReactivateTimeout(t),t.callbackInfo.isRunningCallback||(t.callbackInfo.isCallbackActive=!0,this.activeElementCount++,this.handler.observeElement(e),this.emit({type:"elementReactivated",elementData:t,timestamp:Date.now()})))}clearReactivateTimeout(e){clearTimeout(e.callbackInfo.reactivateTimeoutId),e.callbackInfo.reactivateTimeoutId=void 0}makeElementUnactive(e){e.callbackInfo.callbackFiredCount++,e.callbackInfo.lastCallbackInvokedAt=Date.now(),e.callbackInfo.isRunningCallback=!0,this.clearReactivateTimeout(e)}callCallback(e,t){if(e.callbackInfo.isRunningCallback||!e.callbackInfo.isCallbackActive)return;this.makeElementUnactive(e),(async()=>{this.updateHitCounters(t),this.emit({type:"callbackInvoked",timestamp:Date.now(),elementData:e,hitType:t});let o=performance.now(),r,l=null;try{await e.callback(),r="success"}catch(s){l=s instanceof Error?s.message:String(s),r="error",console.error(`Error in callback for element ${e.name}:`,s)}e.callbackInfo.lastCallbackCompletedAt=Date.now(),e.callbackInfo.isRunningCallback=!1,e.callbackInfo.isCallbackActive=!1,this.activeElementCount--,this.handler.unobserveElement(e.element),e.callbackInfo.reactivateAfter!==1/0&&(e.callbackInfo.reactivateTimeoutId=setTimeout(()=>{this.reactivate(e.element)},e.callbackInfo.reactivateAfter));let a=this.activeElementCount===0;a&&this.removeGlobalListeners(),this.emit({type:"callbackCompleted",timestamp:Date.now(),elementData:e,hitType:t,elapsed:e.callbackInfo.lastCallbackRuntime=performance.now()-o,status:e.callbackInfo.lastCallbackStatus=r,errorMessage:e.callbackInfo.lastCallbackErrorMessage=l,wasLastActiveElement:a})})()}setDeviceStrategy(e){this.handler.disconnect(),this.handler=e==="mouse"?this.desktopHandler:this.touchDeviceHandler,this.handler.connect()}initializeGlobalListeners(){this.isSetup||typeof document>"u"||(this.setDeviceStrategy(this.currentDeviceStrategy),document.addEventListener("pointermove",this.handlePointerMove),this.domObserver=new MutationObserver(this.handleDomMutations),this.domObserver.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1}),this.isSetup=!0)}removeGlobalListeners(){typeof document>"u"||(this.isSetup=!1,this.domObserver?.disconnect(),this.domObserver=null,document.removeEventListener("pointermove",this.handlePointerMove),this.handler.disconnect(),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.pendingPointerEvent=null)}forceUpdateAllElementBounds(){for(let[,e]of this.elements)e.isIntersectingWithViewport&&this.forceUpdateElementBounds(e)}forceUpdateElementBounds(e){let t=e.element.getBoundingClientRect(),i=P(t,e.elementBounds.hitSlop);if(!w(i,e.elementBounds.expandedRect)){let o={...e,elementBounds:{...e.elementBounds,originalRect:t,expandedRect:i}};this.elements.set(e.element,o),this.emit({type:"elementDataUpdated",elementData:o,updatedProps:["bounds"]})}}initializeManagerSettings(e){this.updateNumericSettings(e.trajectoryPredictionTime,"trajectoryPredictionTime",10,200),this.updateNumericSettings(e.positionHistorySize,"positionHistorySize",2,30),this.updateNumericSettings(e.scrollMargin,"scrollMargin",30,300),this.updateNumericSettings(e.tabOffset,"tabOffset",0,20),this.updateBooleanSetting(e.enableMousePrediction,"enableMousePrediction"),this.updateBooleanSetting(e.enableScrollPrediction,"enableScrollPrediction"),this.updateBooleanSetting(e.enableTabPrediction,"enableTabPrediction"),e.defaultHitSlop!==void 0&&(this._globalSettings.defaultHitSlop=T(e.defaultHitSlop)),e.touchDeviceStrategy!==void 0&&(this._globalSettings.touchDeviceStrategy=e.touchDeviceStrategy),e.debug!==void 0&&(this._globalSettings.debug=e.debug)}updateNumericSettings(e,t,i,o){return N(e,this._globalSettings[t])?(this._globalSettings[t]=p(e,i,o,t),!0):!1}updateBooleanSetting(e,t){return N(e,this._globalSettings[t])?(this._globalSettings[t]=e,!0):!1}alterGlobalSettings(e){let t=[],i=this._globalSettings.trajectoryPredictionTime;this.updateNumericSettings(e?.trajectoryPredictionTime,"trajectoryPredictionTime",10,200)&&t.push({setting:"trajectoryPredictionTime",oldValue:i,newValue:this._globalSettings.trajectoryPredictionTime});let r=this._globalSettings.positionHistorySize;this.updateNumericSettings(e?.positionHistorySize,"positionHistorySize",2,30)&&(t.push({setting:"positionHistorySize",oldValue:r,newValue:this._globalSettings.positionHistorySize}),this.desktopHandler.trajectoryPositions.positions.resize(this._globalSettings.positionHistorySize));let a=this._globalSettings.scrollMargin;if(this.updateNumericSettings(e?.scrollMargin,"scrollMargin",30,300)){let m=this._globalSettings.scrollMargin;t.push({setting:"scrollMargin",oldValue:a,newValue:m})}let d=this._globalSettings.tabOffset;this.updateNumericSettings(e?.tabOffset,"tabOffset",0,20)&&(this._globalSettings.tabOffset=p(e.tabOffset,0,20,"tabOffset"),t.push({setting:"tabOffset",oldValue:d,newValue:this._globalSettings.tabOffset}));let h=this._globalSettings.enableMousePrediction;this.updateBooleanSetting(e?.enableMousePrediction,"enableMousePrediction")&&t.push({setting:"enableMousePrediction",oldValue:h,newValue:this._globalSettings.enableMousePrediction});let g=this._globalSettings.enableScrollPrediction;this.updateBooleanSetting(e?.enableScrollPrediction,"enableScrollPrediction")&&(this.handler instanceof f&&(this._globalSettings.enableScrollPrediction?this.handler.connectScrollPredictor():this.handler.disconnectScrollPredictor()),t.push({setting:"enableScrollPrediction",oldValue:g,newValue:this._globalSettings.enableScrollPrediction}));let L=this._globalSettings.enableTabPrediction;if(this.updateBooleanSetting(e?.enableTabPrediction,"enableTabPrediction")&&(this.handler instanceof f&&(this._globalSettings.enableTabPrediction?this.handler.connectTabPredictor():this.handler.disconnectTabPredictor()),t.push({setting:"enableTabPrediction",oldValue:L,newValue:this._globalSettings.enableTabPrediction})),e?.defaultHitSlop!==void 0){let m=this._globalSettings.defaultHitSlop,b=T(e.defaultHitSlop);w(m,b)||(this._globalSettings.defaultHitSlop=b,t.push({setting:"defaultHitSlop",oldValue:m,newValue:b}),this.forceUpdateAllElementBounds())}if(e?.touchDeviceStrategy!==void 0){let m=this._globalSettings.touchDeviceStrategy,b=e.touchDeviceStrategy;this._globalSettings.touchDeviceStrategy=b,t.push({setting:"touchDeviceStrategy",oldValue:m,newValue:b}),this.handler instanceof v&&this.handler.setTouchPredictor()}t.length>0&&this.emit({type:"managerSettingsChanged",timestamp:Date.now(),managerData:this.getManagerData,updatedSettings:t})}};export{B as ForesightManager};
|
package/package.json
CHANGED
|
@@ -1,70 +1,73 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "js.foresight",
|
|
3
|
-
"version": "3.3.0
|
|
4
|
-
"description": "Predicts
|
|
5
|
-
"type": "module",
|
|
6
|
-
"
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
"
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
"
|
|
21
|
-
"
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
"
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
"
|
|
38
|
-
"
|
|
39
|
-
"
|
|
40
|
-
"
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
"
|
|
48
|
-
"
|
|
49
|
-
"
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
"
|
|
55
|
-
"
|
|
56
|
-
"
|
|
57
|
-
"
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
"
|
|
61
|
-
"
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
"
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
|
|
70
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "js.foresight",
|
|
3
|
+
"version": "3.3.0",
|
|
4
|
+
"description": "Predicts where users will click based on mouse movement, keyboard navigation, and scroll behavior. Includes touch device support. Triggers callbacks before interactions happen to enable prefetching and faster UI responses. Works with any framework.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"module": "./dist/index.js",
|
|
8
|
+
"types": "./dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
}
|
|
14
|
+
},
|
|
15
|
+
"homepage": "https://foresightjs.com/",
|
|
16
|
+
"repository": {
|
|
17
|
+
"type": "git",
|
|
18
|
+
"url": "git+https://github.com/spaansba/ForesightJS"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"README.md",
|
|
23
|
+
"LICENSE"
|
|
24
|
+
],
|
|
25
|
+
"keywords": [
|
|
26
|
+
"javascript-prefetch",
|
|
27
|
+
"smart-prefetch",
|
|
28
|
+
"fast-prefetch",
|
|
29
|
+
"interaction-prediction",
|
|
30
|
+
"mobile-prefetch",
|
|
31
|
+
"mouse-trajectory",
|
|
32
|
+
"element-hitslop",
|
|
33
|
+
"foresight",
|
|
34
|
+
"interaction-prediction",
|
|
35
|
+
"cursor-prediction",
|
|
36
|
+
"vanilla-javascript",
|
|
37
|
+
"prefetching",
|
|
38
|
+
"keyboard-tracking",
|
|
39
|
+
"keyboard-prefetching",
|
|
40
|
+
"tab-prefetching"
|
|
41
|
+
],
|
|
42
|
+
"author": "Bart Spaans",
|
|
43
|
+
"license": "MIT",
|
|
44
|
+
"llms": "https://foresightjs.com/llms.txt",
|
|
45
|
+
"llmsFull": "https://foresightjs.com/llms-full.txt",
|
|
46
|
+
"devDependencies": {
|
|
47
|
+
"@testing-library/dom": "^10.4.1",
|
|
48
|
+
"@testing-library/jest-dom": "^6.6.4",
|
|
49
|
+
"@types/node": "^24.1.0",
|
|
50
|
+
"@vitest/coverage-v8": "3.2.4",
|
|
51
|
+
"@vitest/ui": "^3.2.4",
|
|
52
|
+
"happy-dom": "^18.0.1",
|
|
53
|
+
"jsdom": "^26.1.0",
|
|
54
|
+
"tslib": "^2.8.1",
|
|
55
|
+
"tsup": "^8.5.0",
|
|
56
|
+
"typescript": "^5.9.2",
|
|
57
|
+
"vitest": "^3.2.4"
|
|
58
|
+
},
|
|
59
|
+
"dependencies": {
|
|
60
|
+
"position-observer": "^1.0.1",
|
|
61
|
+
"tabbable": "^6.2.0"
|
|
62
|
+
},
|
|
63
|
+
"scripts": {
|
|
64
|
+
"build": "tsup --sourcemap",
|
|
65
|
+
"build:prod": "tsup",
|
|
66
|
+
"dev": "tsup --sourcemap --watch",
|
|
67
|
+
"test": "vitest",
|
|
68
|
+
"test:watch": "vitest --watch",
|
|
69
|
+
"test:ui": "vitest --ui",
|
|
70
|
+
"test:coverage": "vitest --coverage",
|
|
71
|
+
"test:run": "vitest run"
|
|
72
|
+
}
|
|
73
|
+
}
|