js.foresight 3.2.1 → 3.3.0-beta.1

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/dist/index.d.ts CHANGED
@@ -175,6 +175,8 @@ type CallbackHits = {
175
175
  mouse: MouseCallbackCounts;
176
176
  tab: TabCallbackCounts;
177
177
  scroll: ScrollCallbackCounts;
178
+ touch: number;
179
+ viewport: number;
178
180
  };
179
181
  type CallbackHitType = {
180
182
  kind: "mouse";
@@ -185,6 +187,12 @@ type CallbackHitType = {
185
187
  } | {
186
188
  kind: "scroll";
187
189
  subType: keyof ScrollCallbackCounts;
190
+ } | {
191
+ kind: "touch";
192
+ subType?: string;
193
+ } | {
194
+ kind: "viewport";
195
+ subType?: string;
188
196
  };
189
197
  /**
190
198
  * Snapshot of the current ForesightManager state
@@ -194,7 +202,9 @@ type ForesightManagerData = {
194
202
  globalSettings: Readonly<ForesightManagerSettings>;
195
203
  globalCallbackHits: Readonly<CallbackHits>;
196
204
  eventListeners: ReadonlyMap<keyof ForesightEventMap, ForesightEventListener[]>;
205
+ currentDeviceStrategy: CurrentDeviceStrategy;
197
206
  };
207
+ type TouchDeviceStrategy = "none" | "viewport" | "onTouchStart";
198
208
  type BaseForesightManagerSettings = {
199
209
  /**
200
210
  * Number of mouse positions to keep in history for trajectory calculation.
@@ -261,7 +271,16 @@ type BaseForesightManagerSettings = {
261
271
  * @default 2
262
272
  */
263
273
  tabOffset: number;
274
+ /**
275
+ * The prefetch strategy used for touch devices.
276
+ * - `none`: No prefetching is done on touch devices.
277
+ * - `viewport`: Prefetching is done based on the viewport, meaning elements in the viewport are preloaded.
278
+ * - `onTouchStart`: Prefetching is done when the user touches the element
279
+ * @default onTouchStart
280
+ */
281
+ touchDeviceStrategy: TouchDeviceStrategy;
264
282
  };
283
+ type CurrentDeviceStrategy = "mouse" | "touch" | "pen";
265
284
  /**
266
285
  * Configuration options for the ForesightManager
267
286
  * @link https://foresightjs.com/docs/getting_started/config#available-global-settings
@@ -322,8 +341,14 @@ interface ForesightEventMap {
322
341
  mouseTrajectoryUpdate: MouseTrajectoryUpdateEvent;
323
342
  scrollTrajectoryUpdate: ScrollTrajectoryUpdateEvent;
324
343
  managerSettingsChanged: ManagerSettingsChangedEvent;
344
+ deviceStrategyChanged: DeviceStrategyChangedEvent;
345
+ }
346
+ type ForesightEvent = "elementRegistered" | "elementReactivated" | "elementUnregistered" | "elementDataUpdated" | "callbackInvoked" | "callbackCompleted" | "mouseTrajectoryUpdate" | "scrollTrajectoryUpdate" | "managerSettingsChanged" | "deviceStrategyChanged";
347
+ interface DeviceStrategyChangedEvent extends ForesightBaseEvent {
348
+ type: "deviceStrategyChanged";
349
+ newStrategy: CurrentDeviceStrategy;
350
+ oldStrategy: CurrentDeviceStrategy;
325
351
  }
326
- type ForesightEvent = "elementRegistered" | "elementReactivated" | "elementUnregistered" | "elementDataUpdated" | "callbackInvoked" | "callbackCompleted" | "mouseTrajectoryUpdate" | "scrollTrajectoryUpdate" | "managerSettingsChanged";
327
352
  interface ElementRegisteredEvent extends ForesightBaseEvent {
328
353
  type: "elementRegistered";
329
354
  elementData: ForesightElementData;
@@ -417,17 +442,18 @@ interface ForesightBaseEvent {
417
442
  declare class ForesightManager {
418
443
  private static manager;
419
444
  private elements;
420
- private trajectoryPositions;
445
+ private desktopHandler;
446
+ private touchDeviceHandler;
447
+ private handler;
421
448
  private isSetup;
422
449
  private idCounter;
423
450
  private _globalCallbackHits;
424
451
  private _globalSettings;
452
+ private pendingPointerEvent;
453
+ private rafId;
425
454
  private domObserver;
426
- private positionObserver;
427
455
  private eventListeners;
428
- private mousePredictor;
429
- private tabPredictor;
430
- private scrollPredictor;
456
+ private currentDeviceStrategy;
431
457
  private constructor();
432
458
  private generateId;
433
459
  static initialize(props?: Partial<UpdateForsightManagerSettings>): ForesightManager;
@@ -442,9 +468,14 @@ declare class ForesightManager {
442
468
  get registeredElements(): ReadonlyMap<ForesightElement, ForesightElementData>;
443
469
  register({ element, callback, hitSlop, name, meta, reactivateAfter, }: ForesightRegisterOptions): ForesightRegisterResult;
444
470
  unregister(element: ForesightElement, unregisterReason?: ElementUnregisteredReason): void;
445
- private updateNumericSettings;
446
- private updateBooleanSetting;
447
- alterGlobalSettings(props?: Partial<UpdateForsightManagerSettings>): void;
471
+ private updateHitCounters;
472
+ reactivate(element: ForesightElement): void;
473
+ private makeElementUnactive;
474
+ private callCallback;
475
+ private setDeviceStrategy;
476
+ private handlePointerMove;
477
+ private initializeGlobalListeners;
478
+ private removeGlobalListeners;
448
479
  /**
449
480
  * Detects when registered elements are removed from the DOM and automatically unregisters them to prevent stale references.
450
481
  *
@@ -452,20 +483,16 @@ declare class ForesightManager {
452
483
  *
453
484
  */
454
485
  private handleDomMutations;
455
- private updateHitCounters;
456
- reactivate(element: ForesightElement): void;
457
- private makeElementUnactive;
458
- private callCallback;
459
- private handlePositionChange;
460
- private handlePositionChangeDataUpdates;
461
- private initializeGlobalListeners;
462
- private removeGlobalListeners;
463
486
  private forceUpdateAllElementBounds;
464
487
  /**
465
488
  * ONLY use this function when you want to change the rect bounds via code, if the rects are changing because of updates in the DOM do not use this function.
466
489
  * We need an observer for that
467
490
  */
468
491
  private forceUpdateElementBounds;
492
+ private initializeManagerSettings;
493
+ private updateNumericSettings;
494
+ private updateBooleanSetting;
495
+ alterGlobalSettings(props?: Partial<UpdateForsightManagerSettings>): void;
469
496
  }
470
497
 
471
- export { type CallbackCompletedEvent, type CallbackHitType, type CallbackHits, type CallbackInvokedEvent, type ElementCallbackInfo, type ElementDataUpdatedEvent, type ElementReactivatedEvent, type ElementRegisteredEvent, type ElementUnregisteredEvent, type ForesightElement, type ForesightElementData, type ForesightEvent, ForesightManager, type ForesightManagerSettings, type Rect as ForesightRect, type ForesightRegisterOptions, type ForesightRegisterOptionsWithoutElement, type ForesightRegisterResult, type HitSlop, type ManagerSettingsChangedEvent, type MouseTrajectoryUpdateEvent, type ScrollTrajectoryUpdateEvent, type UpdateForsightManagerSettings, type UpdatedManagerSetting };
498
+ export { type CallbackCompletedEvent, type CallbackHitType, type CallbackHits, type CallbackInvokedEvent, type DeviceStrategyChangedEvent, type ElementCallbackInfo, type ElementDataUpdatedEvent, type ElementReactivatedEvent, type ElementRegisteredEvent, type ElementUnregisteredEvent, type ForesightElement, type ForesightElementData, type ForesightEvent, ForesightManager, type ForesightManagerSettings, type Rect as ForesightRect, type ForesightRegisterOptions, type ForesightRegisterOptionsWithoutElement, type ForesightRegisterResult, type HitSlop, type ManagerSettingsChangedEvent, type MouseTrajectoryUpdateEvent, type ScrollTrajectoryUpdateEvent, type TouchDeviceStrategy, type UpdateForsightManagerSettings, type UpdatedManagerSetting };
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{PositionObserver as st}from"position-observer";var v=class{constructor(t){this.head=0;this.count=0;if(t<=0)throw new Error("CircularBuffer capacity must be greater than 0");this.capacity=t,this.buffer=new Array(t)}add(t){this.buffer[this.head]=t,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 t=(this.head-1+this.capacity)%this.capacity;return this.buffer[t]}}}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 t=this.getFirst(),e=this.getLast();return[t,e]}resize(t){if(t<=0)throw new Error("CircularBuffer capacity must be greater than 0");if(t===this.capacity)return;let e=this.getAllItems();if(this.capacity=t,this.buffer=new Array(t),this.head=0,this.count=0,e.length>t){let i=e.slice(-t);for(let o of i)this.add(o)}else for(let i of e)this.add(i)}getAllItems(){if(this.count===0)return[];let t=new Array(this.count);if(this.count<this.capacity)for(let e=0;e<this.count;e++)t[e]=this.buffer[e];else{let e=this.head;for(let i=0;i<this.capacity;i++){let o=(e+i)%this.capacity;t[i]=this.buffer[o]}}return t}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}};function u(n,t,e,i){return n<t?console.warn(`ForesightJS: "${i}" value ${n} is below minimum bound ${t}, clamping to ${t}`):n>e&&console.warn(`ForesightJS: "${i}" value ${n} is above maximum bound ${e}, clamping to ${e}`),Math.min(Math.max(n,t),e)}function D(n){let t=window.innerWidth||document.documentElement.clientWidth,e=window.innerHeight||document.documentElement.clientHeight;return n.top<e&&n.bottom>0&&n.left<t&&n.right>0}function k(n){if(typeof n=="number"){let t=u(n,0,2e3,"hitslop");return{top:t,left:t,right:t,bottom:t}}return{top:u(n.top,0,2e3,"hitslop - top"),left:u(n.left,0,2e3,"hitslop - left"),right:u(n.right,0,2e3,"hitslop - right"),bottom:u(n.bottom,0,2e3,"hitslop - bottom")}}function S(n,t){return{left:n.left-t.left,right:n.right+t.right,top:n.top-t.top,bottom:n.bottom+t.bottom}}function x(n,t){return!n||!t?n===t:n.left===t.left&&n.right===t.right&&n.top===t.top&&n.bottom===t.bottom}function T(n,t){return n.x>=t.left&&n.x<=t.right&&n.y>=t.top&&n.y<=t.bottom}function j(){let n=z(),t=K();return{isTouchDevice:n,isLimitedConnection:t,shouldRegister:!n&&!t}}function z(){return window.matchMedia("(pointer: coarse)").matches&&navigator.maxTouchPoints>0}function K(){let n=navigator.connection;return n?/2g/.test(n.effectiveType)||n.saveData:!1}function O(n,t){return n!==void 0&&t!==n}function I(n,t,e){let i=0,o=1,r=t.x-n.x,c=t.y-n.y,s=(a,l)=>{if(a===0){if(l<0)return!1}else{let d=l/a;if(a<0){if(d>o)return!1;d>i&&(i=d)}else{if(d<i)return!1;d<o&&(o=d)}}return!0};return!s(-r,n.x-e.left)||!s(r,e.right-n.x)||!s(-c,n.y-e.top)||!s(c,e.bottom-n.y)?!1:i<=o}function w(n,t,e){let i=performance.now(),o={point:n,time:i},{x:r,y:c}=n;if(t.add(o),t.length<2)return{x:r,y:c};let[s,a]=t.getFirstLast();if(!s||!a)return{x:r,y:c};let l=(a.time-s.time)*.001;if(l===0)return{x:r,y:c};let d=a.point.x-s.point.x,p=a.point.y-s.point.y,g=d/l,b=p/l,R=e*.001,_=r+g*R,A=c+b*R;return{x:_,y:A}}var h=class{constructor(t){this.elements=t.dependencies.elements,this.callCallback=t.dependencies.callCallback,this.emit=t.dependencies.emit,this.abortController=new AbortController}abort(){this.abortController.abort()}handleError(t,e){console.error(`${this.constructor.name} error in ${e}:`,t)}};var C=class extends h{constructor(e){super(e);this.pendingMouseEvent=null;this.rafId=null;this.handleMouseMove=e=>{this.pendingMouseEvent=e,!this.rafId&&(this.rafId=requestAnimationFrame(()=>{this.pendingMouseEvent&&this.processMouseMovement(this.pendingMouseEvent),this.rafId=null}))};this.enableMousePrediction=e.settings.enableMousePrediction,this.trajectoryPredictionTime=e.settings.trajectoryPredictionTime,this.positionHistorySize=e.settings.positionHistorySize,this.trajectoryPositions=e.trajectoryPositions,this.initializeListeners()}initializeListeners(){let{signal:e}=this.abortController;document.addEventListener("mousemove",this.handleMouseMove,{signal:e})}updatePointerState(e){let i={x:e.clientX,y:e.clientY};this.trajectoryPositions.currentPoint=i,this.enableMousePrediction?this.trajectoryPositions.predictedPoint=w(i,this.trajectoryPositions.positions,this.trajectoryPredictionTime):this.trajectoryPositions.predictedPoint=i}cleanup(){this.abort(),this.rafId&&(cancelAnimationFrame(this.rafId),this.rafId=null),this.pendingMouseEvent=null}processMouseMovement(e){try{this.updatePointerState(e);for(let i of this.elements.values()){if(!i.isIntersectingWithViewport||!i.callbackInfo.isCallbackActive||i.callbackInfo.isRunningCallback)continue;let o=i.elementBounds.expandedRect;if(this.enableMousePrediction)I(this.trajectoryPositions.currentPoint,this.trajectoryPositions.predictedPoint,o)&&this.callCallback(i,{kind:"mouse",subType:"trajectory"});else if(T(this.trajectoryPositions.currentPoint,o)){this.callCallback(i,{kind:"mouse",subType:"hover"});return}}this.emit({type:"mouseTrajectoryUpdate",predictionEnabled:this.enableMousePrediction,trajectoryPositions:this.trajectoryPositions})}catch(i){this.handleError(i,"processMouseMovement")}}};function H(n,t){let i=t.top-n.top,o=t.left-n.left;return i<-1?"down":i>1?"up":o<-1?"right":o>1?"left":"none"}function N(n,t,e){let{x:i,y:o}=n,r={x:i,y:o};switch(t){case"down":r.y+=e;break;case"up":r.y-=e;break;case"left":r.x-=e;break;case"right":r.x+=e;break;case"none":break;default:}return r}var y=class extends h{constructor(e){super(e);this.predictedScrollPoint=null;this.scrollDirection=null;this.scrollMargin=e.settings.scrollMargin,this.trajectoryPositions=e.trajectoryPositions}initializeListeners(){}cleanup(){this.abort(),this.resetScrollProps()}resetScrollProps(){this.scrollDirection=null,this.predictedScrollPoint=null}handleScrollPrefetch(e,i){if(!(!e.isIntersectingWithViewport||e.callbackInfo.isRunningCallback||!e.callbackInfo.isCallbackActive))try{if(this.scrollDirection=this.scrollDirection??H(e.elementBounds.originalRect,i),this.scrollDirection==="none")return;this.predictedScrollPoint=this.predictedScrollPoint??N(this.trajectoryPositions.currentPoint,this.scrollDirection,this.scrollMargin),I(this.trajectoryPositions.currentPoint,this.predictedScrollPoint,e.elementBounds.expandedRect)&&this.callCallback(e,{kind:"scroll",subType:this.scrollDirection}),this.emit({type:"scrollTrajectoryUpdate",currentPoint:this.trajectoryPositions.currentPoint,predictedPoint:this.predictedScrollPoint,scrollDirection:this.scrollDirection})}catch(o){this.handleError(o,"handleScrollPrefetch")}}handleError(e,i){super.handleError(e,i),this.emit({type:"scrollTrajectoryUpdate",currentPoint:this.trajectoryPositions.currentPoint,predictedPoint:this.trajectoryPositions.currentPoint,scrollDirection:"none"})}};import{tabbable as V}from"tabbable";function U(n,t,e,i){if(t!==null&&t>-1){let o=n?t-1:t+1;if(o>=0&&o<e.length&&e[o]===i)return o}return e.findIndex(o=>o===i)}var E=class extends h{constructor(e){super(e);this.lastKeyDown=null;this.tabbableElementsCache=[];this.lastFocusedIndex=null;this.handleKeyDown=e=>{e.key==="Tab"&&(this.lastKeyDown=e)};this.handleFocusIn=e=>{try{if(!this.lastKeyDown)return;let i=e.target;if(!(i instanceof HTMLElement))return;(!this.tabbableElementsCache.length||this.lastFocusedIndex===-1)&&(this.tabbableElementsCache=V(document.documentElement));let o=this.lastKeyDown.shiftKey,r=U(o,this.lastFocusedIndex,this.tabbableElementsCache,i);this.lastFocusedIndex=r,this.lastKeyDown=null;let c=[];for(let s=0;s<=this.tabOffset;s++){let a=o?r-s:r+s,l=this.tabbableElementsCache[a];l&&l instanceof Element&&this.elements.has(l)&&c.push(l)}for(let s of c){let a=this.elements.get(s);a&&!a.callbackInfo.isRunningCallback&&a.callbackInfo.isCallbackActive&&this.callCallback(a,{kind:"tab",subType:o?"reverse":"forwards"})}}catch(i){this.handleError(i,"handleFocusIn")}};this.tabOffset=e.settings.tabOffset,this.initializeListeners()}initializeListeners(){let{signal:e}=this.abortController;document.addEventListener("keydown",this.handleKeyDown,{signal:e}),document.addEventListener("focusin",this.handleFocusIn,{signal:e})}invalidateCache(){this.tabbableElementsCache=[],this.lastFocusedIndex=null}cleanup(){this.abort(),this.tabbableElementsCache=[],this.lastFocusedIndex=null,this.lastKeyDown=null}};var L=class n{constructor(){this.elements=new Map;this.trajectoryPositions={positions:new v(8),currentPoint:{x:0,y:0},predictedPoint:{x:0,y:0}};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},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};this.domObserver=null;this.positionObserver=null;this.eventListeners=new Map;this.mousePredictor=null;this.tabPredictor=null;this.scrollPredictor=null;this.handleDomMutations=t=>{t.length&&this.tabPredictor?.invalidateCache();for(let e of t)if(e.type==="childList"&&e.removedNodes.length>0)for(let i of this.elements.keys())i.isConnected||this.unregister(i,"disconnected")};this.handlePositionChange=t=>{let e=this._globalSettings.enableScrollPrediction;for(let i of t){let o=this.elements.get(i.target);o&&(e?this.scrollPredictor?.handleScrollPrefetch(o,i.boundingClientRect):T(this.trajectoryPositions.currentPoint,o.elementBounds.expandedRect)&&this.callCallback(o,{kind:"mouse",subType:"hover"}),this.handlePositionChangeDataUpdates(o,i))}this._globalSettings.enableScrollPrediction&&this.scrollPredictor?.resetScrollProps()};this.handlePositionChangeDataUpdates=(t,e)=>{let i=[],o=e.isIntersecting;t.isIntersectingWithViewport!==o&&(i.push("visibility"),t.isIntersectingWithViewport=o),o&&(i.push("bounds"),t.elementBounds={hitSlop:t.elementBounds.hitSlop,originalRect:e.boundingClientRect,expandedRect:S(e.boundingClientRect,t.elementBounds.hitSlop)}),i.length&&this.emit({type:"elementDataUpdated",elementData:t,updatedProps:i})}}generateId(){return`foresight-${++this.idCounter}`}static initialize(t){return this.isInitiated||(n.manager=new n),t!==void 0&&n.manager.alterGlobalSettings(t),n.manager}addEventListener(t,e,i){if(i?.signal?.aborted)return()=>{};let o=this.eventListeners.get(t)??[];o.push(e),this.eventListeners.set(t,o),i?.signal?.addEventListener("abort",()=>this.removeEventListener(t,e))}removeEventListener(t,e){let i=this.eventListeners.get(t);if(!i)return;let o=i.indexOf(e);o>-1&&i.splice(o,1)}emit(t){let e=this.eventListeners.get(t.type)?.slice();if(e)for(let i=0;i<e.length;i++)try{e[i](t)}catch(o){console.error(`Error in ForesightManager event listener ${i} for ${t.type}:`,o)}}get getManagerData(){return{registeredElements:this.elements,globalSettings:this._globalSettings,globalCallbackHits:this._globalCallbackHits,eventListeners:this.eventListeners}}static get isInitiated(){return!!n.manager}static get instance(){return this.initialize()}get registeredElements(){return this.elements}register({element:t,callback:e,hitSlop:i,name:o,meta:r,reactivateAfter:c}){let{shouldRegister:s,isTouchDevice:a,isLimitedConnection:l}=j();if(!s)return{isLimitedConnection:l,isTouchDevice:a,isRegistered:!1,unregister:()=>{}};let d=this.elements.get(t);if(d)return d.registerCount++,{isLimitedConnection:l,isTouchDevice:a,isRegistered:!1,unregister:()=>{}};this.isSetup||this.initializeGlobalListeners();let p=t.getBoundingClientRect(),g=i?k(i):this._globalSettings.defaultHitSlop,b={id:this.generateId(),element:t,callback:e,elementBounds:{originalRect:p,expandedRect:S(p,g),hitSlop:g},trajectoryHitData:{isTrajectoryHit:!1,trajectoryHitTime:0,trajectoryHitExpirationTimeoutId:void 0},name:o||t.id||"unnamed",isIntersectingWithViewport:D(p),registerCount:1,meta:r??{},callbackInfo:{callbackFiredCount:0,lastCallbackInvokedAt:void 0,lastCallbackCompletedAt:void 0,lastCallbackRuntime:void 0,lastCallbackStatus:void 0,lastCallbackErrorMessage:void 0,reactivateAfter:c??1/0,isCallbackActive:!0,isRunningCallback:!1,reactivateTimeoutId:void 0}};return this.elements.set(t,b),this.positionObserver?.observe(t),this.emit({type:"elementRegistered",timestamp:Date.now(),elementData:b}),{isTouchDevice:a,isLimitedConnection:l,isRegistered:!0,unregister:()=>{}}}unregister(t,e){let i=this.elements.get(t);if(!i)return;i?.trajectoryHitData.trajectoryHitExpirationTimeoutId&&clearTimeout(i.trajectoryHitData.trajectoryHitExpirationTimeoutId),i?.callbackInfo.reactivateTimeoutId&&clearTimeout(i.callbackInfo.reactivateTimeoutId),this.positionObserver?.unobserve(t),this.elements.delete(t);let o=this.elements.size===0&&this.isSetup;o&&this.removeGlobalListeners(),i&&this.emit({type:"elementUnregistered",elementData:i,timestamp:Date.now(),unregisterReason:e??"by user",wasLastElement:o})}updateNumericSettings(t,e,i,o){return O(t,this._globalSettings[e])?(this._globalSettings[e]=u(t,i,o,e),!0):!1}updateBooleanSetting(t,e){return O(t,this._globalSettings[e])?(this._globalSettings[e]=t,!0):!1}alterGlobalSettings(t){let e=[],i=this._globalSettings.trajectoryPredictionTime;this.updateNumericSettings(t?.trajectoryPredictionTime,"trajectoryPredictionTime",10,200)&&e.push({setting:"trajectoryPredictionTime",oldValue:i,newValue:this._globalSettings.trajectoryPredictionTime});let r=this._globalSettings.positionHistorySize;this.updateNumericSettings(t?.positionHistorySize,"positionHistorySize",2,30)&&(e.push({setting:"positionHistorySize",oldValue:r,newValue:this._globalSettings.positionHistorySize}),this.trajectoryPositions.positions.resize(this._globalSettings.positionHistorySize));let s=this._globalSettings.scrollMargin;if(this.updateNumericSettings(t?.scrollMargin,"scrollMargin",30,300)){let f=this._globalSettings.scrollMargin;this.scrollPredictor&&(this.scrollPredictor.scrollMargin=f),e.push({setting:"scrollMargin",oldValue:s,newValue:f})}let l=this._globalSettings.tabOffset;this.updateNumericSettings(t?.tabOffset,"tabOffset",0,20)&&(this.tabPredictor&&(this.tabPredictor.tabOffset=this._globalSettings.tabOffset),e.push({setting:"tabOffset",oldValue:l,newValue:this._globalSettings.tabOffset}));let p=this._globalSettings.enableMousePrediction;this.updateBooleanSetting(t?.enableMousePrediction,"enableMousePrediction")&&e.push({setting:"enableMousePrediction",oldValue:p,newValue:this._globalSettings.enableMousePrediction});let b=this._globalSettings.enableScrollPrediction;this.updateBooleanSetting(t?.enableScrollPrediction,"enableScrollPrediction")&&(this._globalSettings.enableScrollPrediction?this.scrollPredictor=new y({dependencies:{callCallback:this.callCallback.bind(this),emit:this.emit.bind(this),elements:this.elements},settings:{scrollMargin:this._globalSettings.scrollMargin},trajectoryPositions:this.trajectoryPositions}):(this.scrollPredictor?.cleanup(),this.scrollPredictor=null),e.push({setting:"enableScrollPrediction",oldValue:b,newValue:this._globalSettings.enableScrollPrediction}));let _=this._globalSettings.enableTabPrediction;if(this.updateBooleanSetting(t?.enableTabPrediction,"enableTabPrediction")&&(e.push({setting:"enableTabPrediction",oldValue:_,newValue:this._globalSettings.enableTabPrediction}),this._globalSettings.enableTabPrediction?this.tabPredictor=new E({dependencies:{callCallback:this.callCallback.bind(this),emit:this.emit.bind(this),elements:this.elements},settings:{tabOffset:this._globalSettings.tabOffset}}):(this.tabPredictor?.cleanup(),this.tabPredictor=null)),t?.defaultHitSlop!==void 0){let f=this._globalSettings.defaultHitSlop,F=k(t.defaultHitSlop);x(f,F)||(this._globalSettings.defaultHitSlop=F,e.push({setting:"defaultHitSlop",oldValue:f,newValue:F}),this.forceUpdateAllElementBounds())}e.length>0&&this.emit({type:"managerSettingsChanged",timestamp:Date.now(),managerData:this.getManagerData,updatedSettings:e})}updateHitCounters(t){switch(t.kind){case"mouse":this._globalCallbackHits.mouse[t.subType]++;break;case"tab":this._globalCallbackHits.tab[t.subType]++;break;case"scroll":this._globalCallbackHits.scroll[t.subType]++;break;default:}this._globalCallbackHits.total++}reactivate(t){let e=this.elements.get(t);e&&(e.callbackInfo.reactivateTimeoutId&&(clearTimeout(e.callbackInfo.reactivateTimeoutId),e.callbackInfo.reactivateTimeoutId=void 0),e.callbackInfo.isRunningCallback||(e.callbackInfo.isCallbackActive=!0,this.positionObserver?.observe(e.element),this.emit({type:"elementReactivated",elementData:e,timestamp:Date.now()})))}makeElementUnactive(t){t.callbackInfo.callbackFiredCount++,t.callbackInfo.lastCallbackInvokedAt=Date.now(),t.callbackInfo.isRunningCallback=!0,t.callbackInfo.reactivateTimeoutId&&(clearTimeout(t.callbackInfo.reactivateTimeoutId),t.callbackInfo.reactivateTimeoutId=void 0),t?.trajectoryHitData.trajectoryHitExpirationTimeoutId&&clearTimeout(t.trajectoryHitData.trajectoryHitExpirationTimeoutId)}callCallback(t,e){if(t.callbackInfo.isRunningCallback||!t.callbackInfo.isCallbackActive)return;this.makeElementUnactive(t),(async()=>{this.updateHitCounters(e),this.emit({type:"callbackInvoked",timestamp:Date.now(),elementData:t,hitType:e});let o=performance.now(),r,c=null;try{await t.callback(),r="success"}catch(s){c=s instanceof Error?s.message:String(s),r="error",console.error(`Error in callback for element ${t.name} (${t.element.tagName}):`,s)}t.callbackInfo.lastCallbackCompletedAt=Date.now(),this.emit({type:"callbackCompleted",timestamp:Date.now(),elementData:t,hitType:e,elapsed:t.callbackInfo.lastCallbackRuntime=performance.now()-o,status:t.callbackInfo.lastCallbackStatus=r,errorMessage:t.callbackInfo.lastCallbackErrorMessage=c}),t.callbackInfo.isRunningCallback=!1,t.callbackInfo.isCallbackActive=!1,this.positionObserver?.unobserve(t.element),t.callbackInfo.reactivateAfter!==1/0&&t.callbackInfo.reactivateAfter>0&&(t.callbackInfo.reactivateTimeoutId=setTimeout(()=>{this.reactivate(t.element)},t.callbackInfo.reactivateAfter))})()}initializeGlobalListeners(){if(this.isSetup||typeof window>"u"||typeof document>"u")return;let t=this._globalSettings,e={callCallback:this.callCallback.bind(this),emit:this.emit.bind(this),elements:this.elements};t.enableTabPrediction&&(this.tabPredictor=new E({dependencies:e,settings:{tabOffset:t.tabOffset}})),t.enableScrollPrediction&&(this.scrollPredictor=new y({dependencies:e,settings:{scrollMargin:t.scrollMargin},trajectoryPositions:this.trajectoryPositions})),this.mousePredictor=new C({dependencies:e,settings:{enableMousePrediction:t.enableMousePrediction,trajectoryPredictionTime:t.trajectoryPredictionTime,positionHistorySize:t.positionHistorySize},trajectoryPositions:this.trajectoryPositions}),this.domObserver=new MutationObserver(this.handleDomMutations),this.domObserver.observe(document.documentElement,{childList:!0,subtree:!0,attributes:!1}),this.positionObserver=new st(this.handlePositionChange),this.isSetup=!0}removeGlobalListeners(){this.isSetup=!1,this.domObserver?.disconnect(),this.domObserver=null,this.positionObserver?.disconnect(),this.positionObserver=null,this.mousePredictor?.cleanup(),this.tabPredictor?.cleanup(),this.scrollPredictor?.cleanup()}forceUpdateAllElementBounds(){for(let[,t]of this.elements)t.isIntersectingWithViewport&&this.forceUpdateElementBounds(t)}forceUpdateElementBounds(t){let e=t.element.getBoundingClientRect(),i=S(e,t.elementBounds.hitSlop);if(!x(i,t.elementBounds.expandedRect)){let o={...t,elementBounds:{...t.elementBounds,originalRect:e,expandedRect:i}};this.elements.set(t.element,o),this.emit({type:"elementDataUpdated",elementData:o,updatedProps:["bounds"]})}}};export{L as ForesightManager};
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};
package/package.json CHANGED
@@ -1,69 +1,70 @@
1
- {
2
- "name": "js.foresight",
3
- "version": "3.2.1",
4
- "description": "Predicts mouse trajectory to trigger actions as users approach elements, enabling anticipatory UI updates or pre-loading. Made with vanilla javascript and usable in every 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
- "mouse-trajectory",
30
- "element-hitslop",
31
- "foresight",
32
- "interaction-prediction",
33
- "cursor-prediction",
34
- "vanilla-javascript",
35
- "prefetching",
36
- "keyboard-tracking",
37
- "keyboard-prefetching",
38
- "tab-prefetching"
39
- ],
40
- "author": "Bart Spaans",
41
- "license": "MIT",
42
- "devDependencies": {
43
- "@testing-library/dom": "^10.4.0",
44
- "@testing-library/jest-dom": "^6.6.3",
45
- "@types/node": "^22.15.30",
46
- "@vitest/coverage-v8": "3.2.4",
47
- "@vitest/ui": "^3.2.4",
48
- "happy-dom": "^18.0.1",
49
- "jsdom": "^26.1.0",
50
- "tslib": "^2.8.1",
51
- "tsup": "^8.5.0",
52
- "typescript": "^5.8.3",
53
- "vitest": "^3.2.4"
54
- },
55
- "dependencies": {
56
- "position-observer": "^1.0.0",
57
- "tabbable": "^6.2.0"
58
- },
59
- "scripts": {
60
- "build": "tsup --sourcemap",
61
- "build:prod": "tsup",
62
- "dev": "tsup --sourcemap --watch",
63
- "test": "vitest",
64
- "test:watch": "vitest --watch",
65
- "test:ui": "vitest --ui",
66
- "test:coverage": "vitest --coverage",
67
- "test:run": "vitest run"
68
- }
69
- }
1
+ {
2
+ "name": "js.foresight",
3
+ "version": "3.3.0-beta.1",
4
+ "description": "Predicts mouse trajectory to trigger actions as users approach elements, enabling anticipatory UI updates or pre-loading. Made with vanilla javascript and usable in every framework.",
5
+ "type": "module",
6
+ "scripts": {
7
+ "build": "tsup --sourcemap",
8
+ "build:prod": "tsup",
9
+ "dev": "tsup --sourcemap --watch",
10
+ "test": "vitest",
11
+ "test:watch": "vitest --watch",
12
+ "test:ui": "vitest --ui",
13
+ "test:coverage": "vitest --coverage",
14
+ "test:run": "vitest run",
15
+ "prepublishOnly": "pnpm test:run && pnpm build:prod"
16
+ },
17
+ "main": "./dist/index.js",
18
+ "module": "./dist/index.js",
19
+ "types": "./dist/index.d.ts",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "default": "./dist/index.js"
24
+ }
25
+ },
26
+ "homepage": "https://foresightjs.com/",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/spaansba/ForesightJS"
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "keywords": [
37
+ "javascript-prefetch",
38
+ "smart-prefetch",
39
+ "fast-prefetch",
40
+ "mouse-trajectory",
41
+ "element-hitslop",
42
+ "foresight",
43
+ "interaction-prediction",
44
+ "cursor-prediction",
45
+ "vanilla-javascript",
46
+ "prefetching",
47
+ "keyboard-tracking",
48
+ "keyboard-prefetching",
49
+ "tab-prefetching"
50
+ ],
51
+ "author": "Bart Spaans",
52
+ "license": "MIT",
53
+ "devDependencies": {
54
+ "@testing-library/dom": "^10.4.0",
55
+ "@testing-library/jest-dom": "^6.6.3",
56
+ "@types/node": "^22.15.30",
57
+ "@vitest/coverage-v8": "3.2.4",
58
+ "@vitest/ui": "^3.2.4",
59
+ "happy-dom": "^18.0.1",
60
+ "jsdom": "^26.1.0",
61
+ "tslib": "^2.8.1",
62
+ "tsup": "^8.5.0",
63
+ "typescript": "^5.8.3",
64
+ "vitest": "^3.2.4"
65
+ },
66
+ "dependencies": {
67
+ "position-observer": "^1.0.0",
68
+ "tabbable": "^6.2.0"
69
+ }
70
+ }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
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.