js.foresight 0.0.5

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 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 ADDED
@@ -0,0 +1 @@
1
+ .
@@ -0,0 +1,38 @@
1
+ import type { ForesightManager } from "./ForesightManager";
2
+ import type { LinkElement, Point, Rect } from "../types/types";
3
+ type LinkManagerData = {
4
+ callback: () => void;
5
+ expandedRect: Rect | null;
6
+ isHovering: boolean;
7
+ isTrajectoryHit: boolean;
8
+ trajectoryHitTime: number;
9
+ };
10
+ export declare class IntentDebugger {
11
+ private foresightManagerInstance;
12
+ private shadowHost;
13
+ private shadowRoot;
14
+ private debugContainer;
15
+ private debugLinkOverlays;
16
+ private debugPredictedMouseIndicator;
17
+ private debugTrajectoryLine;
18
+ private debugControlsContainer;
19
+ private debugStyleElement;
20
+ constructor(foresightManager: ForesightManager);
21
+ initialize(links: Map<LinkElement, LinkManagerData>, currentSettings: {
22
+ positionHistorySize: number;
23
+ trajectoryPredictionTime: number;
24
+ enableMouseTrajectory: boolean;
25
+ }, currentPoint: Point, predictedPoint: Point): void;
26
+ cleanup(): void;
27
+ createOrUpdateLinkOverlay(element: LinkElement, linkData: LinkManagerData): void;
28
+ removeLinkOverlay(element: LinkElement): void;
29
+ updateAllLinkVisuals(links: Map<LinkElement, LinkManagerData>): void;
30
+ updateTrajectoryVisuals(currentPoint: Point, predictedPoint: Point, enableMouseTrajectory: boolean): void;
31
+ private createDebugControls;
32
+ updateControlsState(settings: {
33
+ positionHistorySize: number;
34
+ trajectoryPredictionTime: number;
35
+ enableMouseTrajectory: boolean;
36
+ }): void;
37
+ }
38
+ export {};
@@ -0,0 +1,243 @@
1
+ "use strict";
2
+ "use client";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.IntentDebugger = void 0;
5
+ class IntentDebugger {
6
+ foresightManagerInstance;
7
+ shadowHost = null;
8
+ shadowRoot = null;
9
+ debugContainer = null;
10
+ debugLinkOverlays = new Map();
11
+ debugPredictedMouseIndicator = null;
12
+ debugTrajectoryLine = null;
13
+ debugControlsContainer = null;
14
+ debugStyleElement = null;
15
+ constructor(foresightManager) {
16
+ this.foresightManagerInstance = foresightManager;
17
+ }
18
+ initialize(links, currentSettings, currentPoint, predictedPoint) {
19
+ if (typeof window === "undefined")
20
+ return;
21
+ this.cleanup();
22
+ this.shadowHost = document.createElement("div");
23
+ this.shadowHost.id = "intent-debugger-shadow-host";
24
+ // Host itself should not capture pointer events unless specifically designed to.
25
+ this.shadowHost.style.pointerEvents = "none";
26
+ document.body.appendChild(this.shadowHost);
27
+ this.shadowRoot = this.shadowHost.attachShadow({ mode: "open" });
28
+ this.debugStyleElement = document.createElement("style");
29
+ this.debugStyleElement.textContent = `
30
+ #intent-debug-container {
31
+ position: fixed; top: 0; left: 0; width: 100%; height: 100%;
32
+ pointer-events: none; z-index: 9999;
33
+ }
34
+ .intent-link-overlay {
35
+ position: absolute; border: 2px solid blue;
36
+ background-color: rgba(0, 0, 255, 0.1); box-sizing: border-box;
37
+ transition: opacity 0.2s ease, border-color 0.2s ease, background-color 0.2s ease, box-shadow 0.2s ease;
38
+ }
39
+ .intent-link-overlay.active {
40
+ border-color: red; background-color: rgba(255, 0, 0, 0.1);
41
+ }
42
+ .intent-link-overlay.trajectory-hit {
43
+ border-color: lime; background-color: rgba(0, 255, 0, 0.3);
44
+ box-shadow: 0 0 10px rgba(0, 255, 0, 0.8);
45
+ }
46
+ .intent-expanded-overlay {
47
+ position: absolute; border: 1px dashed rgba(0, 0, 255, 0.5);
48
+ background-color: rgba(0, 0, 255, 0.05); box-sizing: border-box;
49
+ }
50
+ .intent-mouse-predicted {
51
+ position: absolute; width: 20px; height: 20px; border-radius: 50%;
52
+ border: 2px solid orange; background-color: rgba(255, 165, 0, 0.3);
53
+ transform: translate(-50%, -50%); z-index: 10000;
54
+ }
55
+ .intent-trajectory-line {
56
+ position: absolute; height: 2px; background-color: rgba(255, 100, 0, 0.5);
57
+ transform-origin: left center; z-index: 9999;
58
+ }
59
+ #intent-debug-controls {
60
+ position: fixed; bottom: 10px; right: 10px;
61
+ background-color: rgba(0, 0, 0, 0.7); color: white; padding: 10px;
62
+ border-radius: 5px; font-family: monospace; font-size: 12px;
63
+ z-index: 10001; pointer-events: auto; /* Make controls interactive */
64
+ }
65
+ #intent-debug-controls h3 { margin: 0 0 5px 0; font-size: 14px; }
66
+ #intent-debug-controls label { display: block; margin: 5px 0; }
67
+ #intent-debug-controls input { margin-right: 5px; vertical-align: middle; }
68
+ #intent-debug-controls button {
69
+ margin: 5px 5px 0 0; padding: 3px 8px; background: #444;
70
+ border: 1px solid #666; color: white; border-radius: 3px; cursor: pointer;
71
+ }
72
+ #intent-debug-controls button:hover { background: #555; }
73
+ `;
74
+ this.shadowRoot.appendChild(this.debugStyleElement);
75
+ this.debugContainer = document.createElement("div");
76
+ this.debugContainer.id = "intent-debug-container";
77
+ this.shadowRoot.appendChild(this.debugContainer);
78
+ this.debugPredictedMouseIndicator = document.createElement("div");
79
+ this.debugPredictedMouseIndicator.className = "intent-mouse-predicted";
80
+ this.debugContainer.appendChild(this.debugPredictedMouseIndicator);
81
+ this.debugTrajectoryLine = document.createElement("div");
82
+ this.debugTrajectoryLine.className = "intent-trajectory-line";
83
+ this.debugContainer.appendChild(this.debugTrajectoryLine);
84
+ this.createDebugControls(currentSettings); // Appends to shadowRoot
85
+ links.forEach((data, element) => {
86
+ this.createOrUpdateLinkOverlay(element, data);
87
+ });
88
+ this.updateTrajectoryVisuals(currentPoint, predictedPoint, currentSettings.enableMouseTrajectory);
89
+ }
90
+ cleanup() {
91
+ this.shadowHost?.remove();
92
+ this.shadowHost = null;
93
+ this.shadowRoot = null;
94
+ }
95
+ createOrUpdateLinkOverlay(element, linkData) {
96
+ if (!this.debugContainer)
97
+ return;
98
+ let overlays = this.debugLinkOverlays.get(element);
99
+ if (!overlays) {
100
+ const linkOverlay = document.createElement("div");
101
+ linkOverlay.className = "intent-link-overlay";
102
+ this.debugContainer.appendChild(linkOverlay);
103
+ const expandedOverlay = document.createElement("div");
104
+ expandedOverlay.className = "intent-expanded-overlay";
105
+ this.debugContainer.appendChild(expandedOverlay);
106
+ overlays = { linkOverlay, expandedOverlay };
107
+ this.debugLinkOverlays.set(element, overlays);
108
+ }
109
+ const { linkOverlay, expandedOverlay } = overlays;
110
+ const rect = element.getBoundingClientRect();
111
+ // Corrected: Since debugContainer is position:fixed top:0 left:0,
112
+ // getBoundingClientRect() coords are already relative to it.
113
+ linkOverlay.style.left = `${rect.left}px`;
114
+ linkOverlay.style.top = `${rect.top}px`;
115
+ linkOverlay.style.width = `${rect.width}px`;
116
+ linkOverlay.style.height = `${rect.height}px`;
117
+ linkOverlay.classList.toggle("trajectory-hit", linkData.isTrajectoryHit);
118
+ linkOverlay.classList.toggle("active", linkData.isHovering);
119
+ if (linkData.expandedRect) {
120
+ // Corrected: Assuming expandedRect coords are viewport-relative.
121
+ expandedOverlay.style.left = `${linkData.expandedRect.left}px`;
122
+ expandedOverlay.style.top = `${linkData.expandedRect.top}px`;
123
+ expandedOverlay.style.width = `${linkData.expandedRect.right - linkData.expandedRect.left}px`;
124
+ expandedOverlay.style.height = `${linkData.expandedRect.bottom - linkData.expandedRect.top}px`;
125
+ expandedOverlay.style.display = "block";
126
+ }
127
+ else {
128
+ expandedOverlay.style.display = "none";
129
+ }
130
+ }
131
+ removeLinkOverlay(element) {
132
+ const overlays = this.debugLinkOverlays.get(element);
133
+ if (overlays) {
134
+ overlays.linkOverlay.remove();
135
+ overlays.expandedOverlay.remove();
136
+ this.debugLinkOverlays.delete(element);
137
+ }
138
+ }
139
+ updateAllLinkVisuals(links) {
140
+ if (!this.shadowRoot || !this.debugContainer)
141
+ return;
142
+ const currentElements = new Set(links.keys());
143
+ this.debugLinkOverlays.forEach((_, element) => {
144
+ if (!currentElements.has(element)) {
145
+ this.removeLinkOverlay(element);
146
+ }
147
+ });
148
+ links.forEach((data, element) => {
149
+ this.createOrUpdateLinkOverlay(element, data);
150
+ });
151
+ }
152
+ updateTrajectoryVisuals(currentPoint, predictedPoint, enableMouseTrajectory) {
153
+ if (!this.shadowRoot || !this.debugContainer)
154
+ return;
155
+ if (this.debugPredictedMouseIndicator) {
156
+ this.debugPredictedMouseIndicator.style.left = `${predictedPoint?.x || 0}px`;
157
+ this.debugPredictedMouseIndicator.style.top = `${predictedPoint?.y || 0}px`;
158
+ this.debugPredictedMouseIndicator.style.display =
159
+ enableMouseTrajectory && predictedPoint ? "block" : "none";
160
+ }
161
+ if (this.debugTrajectoryLine) {
162
+ if (enableMouseTrajectory && currentPoint && predictedPoint) {
163
+ const dx = predictedPoint.x - currentPoint.x;
164
+ const dy = predictedPoint.y - currentPoint.y;
165
+ const length = Math.sqrt(dx * dx + dy * dy);
166
+ const angle = (Math.atan2(dy, dx) * 180) / Math.PI;
167
+ this.debugTrajectoryLine.style.left = `${currentPoint.x}px`;
168
+ this.debugTrajectoryLine.style.top = `${currentPoint.y}px`;
169
+ this.debugTrajectoryLine.style.width = `${length}px`;
170
+ this.debugTrajectoryLine.style.transform = `translateY(-50%) rotate(${angle}deg)`;
171
+ this.debugTrajectoryLine.style.display = "block";
172
+ }
173
+ else {
174
+ this.debugTrajectoryLine.style.display = "none";
175
+ }
176
+ }
177
+ }
178
+ createDebugControls(initialSettings) {
179
+ if (!this.shadowRoot)
180
+ return;
181
+ this.debugControlsContainer = document.createElement("div");
182
+ this.debugControlsContainer.id = "intent-debug-controls";
183
+ this.shadowRoot.appendChild(this.debugControlsContainer);
184
+ this.debugControlsContainer.innerHTML = `
185
+ <h3>Trajectory Debug</h3>
186
+ <label>
187
+ <input type="checkbox" id="intent-trajectory-enabled" ${initialSettings.enableMouseTrajectory ? "checked" : ""}>
188
+ Enable Trajectory
189
+ </label>
190
+ <label>
191
+ History Size: <span id="intent-history-value">${initialSettings.positionHistorySize}</span>
192
+ <input type="range" id="intent-history-size" min="2" max="20" value="${initialSettings.positionHistorySize}">
193
+ </label>
194
+ <label>
195
+ Prediction Time: <span id="intent-prediction-value">${initialSettings.trajectoryPredictionTime}</span>ms
196
+ <input type="range" id="intent-prediction-time" min="10" max="500" value="${initialSettings.trajectoryPredictionTime}">
197
+ </label>
198
+
199
+ `;
200
+ const enabledCheckbox = this.debugControlsContainer.querySelector("#intent-trajectory-enabled");
201
+ enabledCheckbox.addEventListener("change", () => {
202
+ this.foresightManagerInstance.setTrajectorySettings({
203
+ enabled: enabledCheckbox.checked,
204
+ });
205
+ });
206
+ const historySlider = this.debugControlsContainer.querySelector("#intent-history-size");
207
+ const historyValueSpan = this.debugControlsContainer.querySelector("#intent-history-value");
208
+ historySlider.addEventListener("input", () => {
209
+ const value = parseInt(historySlider.value);
210
+ historyValueSpan.textContent = value.toString();
211
+ this.foresightManagerInstance.setTrajectorySettings({ historySize: value });
212
+ });
213
+ const predictionSlider = this.debugControlsContainer.querySelector("#intent-prediction-time");
214
+ const predictionValueSpan = this.debugControlsContainer.querySelector("#intent-prediction-value");
215
+ predictionSlider.addEventListener("input", () => {
216
+ const value = parseInt(predictionSlider.value);
217
+ predictionValueSpan.textContent = value.toString();
218
+ this.foresightManagerInstance.setTrajectorySettings({
219
+ predictionTime: value,
220
+ });
221
+ });
222
+ }
223
+ updateControlsState(settings) {
224
+ if (!this.debugControlsContainer)
225
+ return;
226
+ const enabledCheckbox = this.debugControlsContainer.querySelector("#intent-trajectory-enabled");
227
+ if (enabledCheckbox)
228
+ enabledCheckbox.checked = settings.enableMouseTrajectory;
229
+ const historySlider = this.debugControlsContainer.querySelector("#intent-history-size");
230
+ const historyValueSpan = this.debugControlsContainer.querySelector("#intent-history-value");
231
+ if (historySlider && historyValueSpan) {
232
+ historySlider.value = settings.positionHistorySize.toString();
233
+ historyValueSpan.textContent = settings.positionHistorySize.toString();
234
+ }
235
+ const predictionSlider = this.debugControlsContainer.querySelector("#intent-prediction-time");
236
+ const predictionValueSpan = this.debugControlsContainer.querySelector("#intent-prediction-value");
237
+ if (predictionSlider && predictionValueSpan) {
238
+ predictionSlider.value = settings.trajectoryPredictionTime.toString();
239
+ predictionValueSpan.textContent = settings.trajectoryPredictionTime.toString();
240
+ }
241
+ }
242
+ }
243
+ exports.IntentDebugger = IntentDebugger;
@@ -0,0 +1,39 @@
1
+ import type { IntentCallback, IntentManagerProps, LinkElement } from "../types/types";
2
+ export declare class ForesightManager {
3
+ private static instance;
4
+ private links;
5
+ private isSetup;
6
+ private debugMode;
7
+ private debugger;
8
+ private positionHistorySize;
9
+ private trajectoryPredictionTime;
10
+ private positions;
11
+ private enableMouseTrajectory;
12
+ private currentPoint;
13
+ private predictedPoint;
14
+ private lastResizeScrollCallTimestamp;
15
+ private resizeScrollThrottleTimeoutId;
16
+ private readonly resizeScrollThrottleDelay;
17
+ private constructor();
18
+ static initialize(props?: Partial<IntentManagerProps>): ForesightManager;
19
+ static getInstance(): ForesightManager;
20
+ private checkTrajectoryHitExpiration;
21
+ register(element: LinkElement, callback: IntentCallback): () => void;
22
+ private unregister;
23
+ setTrajectorySettings(settings: {
24
+ historySize?: number;
25
+ predictionTime?: number;
26
+ enabled?: boolean;
27
+ }): void;
28
+ private turnOnDebugMode;
29
+ private getExpandedRect;
30
+ private updateExpandedRect;
31
+ private updateAllRects;
32
+ private predictMousePosition;
33
+ private pointIntersectsRect;
34
+ private isMouseInExpandedArea;
35
+ private handleMouseMove;
36
+ private handleResizeOrScroll;
37
+ private setupGlobalListeners;
38
+ private removeGlobalListeners;
39
+ }
@@ -0,0 +1,314 @@
1
+ "use strict";
2
+ "use client";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.ForesightManager = void 0;
5
+ const ForesightDebugger_1 = require("./ForesightDebugger");
6
+ class ForesightManager {
7
+ static instance;
8
+ links = new Map();
9
+ isSetup = false;
10
+ debugMode = false;
11
+ debugger = null;
12
+ positionHistorySize = 6;
13
+ trajectoryPredictionTime = 50;
14
+ positions = [];
15
+ enableMouseTrajectory = true;
16
+ currentPoint = { x: 0, y: 0 };
17
+ predictedPoint = { x: 0, y: 0 };
18
+ lastResizeScrollCallTimestamp = 0;
19
+ resizeScrollThrottleTimeoutId = null;
20
+ resizeScrollThrottleDelay = 50;
21
+ constructor() {
22
+ setInterval(this.checkTrajectoryHitExpiration.bind(this), 100);
23
+ }
24
+ static initialize(props) {
25
+ if (!ForesightManager.instance) {
26
+ ForesightManager.instance = new ForesightManager();
27
+ }
28
+ if (props) {
29
+ ForesightManager.instance.setTrajectorySettings({
30
+ historySize: props.positionHistorySize,
31
+ predictionTime: props.trajectoryPredictionTime,
32
+ enabled: props.enableMouseTrajectory,
33
+ });
34
+ }
35
+ if (props?.debug) {
36
+ this.instance.turnOnDebugMode();
37
+ }
38
+ else {
39
+ if (this.instance.debugger) {
40
+ this.instance.debugMode = false;
41
+ this.instance.debugger.cleanup();
42
+ this.instance.debugger = null;
43
+ }
44
+ }
45
+ return ForesightManager.instance;
46
+ }
47
+ static getInstance() {
48
+ if (!ForesightManager.instance) {
49
+ return this.initialize();
50
+ }
51
+ return ForesightManager.instance;
52
+ }
53
+ checkTrajectoryHitExpiration() {
54
+ const now = performance.now();
55
+ let needsVisualUpdate = false;
56
+ const updatedLinkElements = [];
57
+ this.links.forEach((linkData, element) => {
58
+ if (linkData.isTrajectoryHit && now - linkData.trajectoryHitTime > 300) {
59
+ this.links.set(element, {
60
+ ...linkData,
61
+ isTrajectoryHit: false,
62
+ });
63
+ needsVisualUpdate = true;
64
+ updatedLinkElements.push(element);
65
+ }
66
+ });
67
+ if (needsVisualUpdate && this.debugMode && this.debugger) {
68
+ updatedLinkElements.forEach((element) => {
69
+ const data = this.links.get(element);
70
+ if (data && this.debugger) {
71
+ console.log("asda");
72
+ this.debugger.createOrUpdateLinkOverlay(element, data);
73
+ }
74
+ });
75
+ }
76
+ }
77
+ register(element, callback) {
78
+ const newLinkData = {
79
+ callback,
80
+ expandedRect: null,
81
+ isHovering: false,
82
+ isTrajectoryHit: false,
83
+ trajectoryHitTime: 0,
84
+ };
85
+ this.links.set(element, newLinkData);
86
+ this.updateExpandedRect(element); // This will also update debug visuals if active
87
+ this.setupGlobalListeners();
88
+ if (this.debugMode && this.debugger) {
89
+ const data = this.links.get(element);
90
+ if (data)
91
+ this.debugger.createOrUpdateLinkOverlay(element, data);
92
+ }
93
+ return () => this.unregister(element);
94
+ }
95
+ unregister(element) {
96
+ this.links.delete(element);
97
+ if (this.debugMode && this.debugger) {
98
+ this.debugger.removeLinkOverlay(element);
99
+ }
100
+ if (this.links.size === 0 && this.isSetup) {
101
+ this.removeGlobalListeners();
102
+ }
103
+ }
104
+ setTrajectorySettings(settings) {
105
+ let changed = false;
106
+ if (settings.historySize !== undefined && this.positionHistorySize !== settings.historySize) {
107
+ this.positionHistorySize = settings.historySize;
108
+ while (this.positions.length > this.positionHistorySize) {
109
+ this.positions.shift();
110
+ }
111
+ changed = true;
112
+ }
113
+ if (settings.predictionTime !== undefined &&
114
+ this.trajectoryPredictionTime !== settings.predictionTime) {
115
+ this.trajectoryPredictionTime = settings.predictionTime;
116
+ changed = true;
117
+ }
118
+ if (settings.enabled !== undefined && this.enableMouseTrajectory !== settings.enabled) {
119
+ this.enableMouseTrajectory = settings.enabled;
120
+ changed = true;
121
+ }
122
+ if (changed && this.debugMode && this.debugger) {
123
+ this.debugger.updateControlsState({
124
+ positionHistorySize: this.positionHistorySize,
125
+ trajectoryPredictionTime: this.trajectoryPredictionTime,
126
+ enableMouseTrajectory: this.enableMouseTrajectory,
127
+ });
128
+ this.debugger.updateTrajectoryVisuals(this.currentPoint, this.predictedPoint, this.enableMouseTrajectory);
129
+ }
130
+ }
131
+ turnOnDebugMode() {
132
+ this.debugMode = true;
133
+ if (!this.debugger) {
134
+ this.debugger = new ForesightDebugger_1.IntentDebugger(this);
135
+ this.debugger.initialize(this.links, {
136
+ positionHistorySize: this.positionHistorySize,
137
+ trajectoryPredictionTime: this.trajectoryPredictionTime,
138
+ enableMouseTrajectory: this.enableMouseTrajectory,
139
+ }, this.currentPoint, this.predictedPoint);
140
+ }
141
+ }
142
+ getExpandedRect(baseRect, hitSlop) {
143
+ return {
144
+ left: baseRect.left - hitSlop.left,
145
+ right: baseRect.right + hitSlop.right,
146
+ top: baseRect.top - hitSlop.top,
147
+ bottom: baseRect.bottom + hitSlop.bottom,
148
+ };
149
+ }
150
+ updateExpandedRect(element) {
151
+ const linkData = this.links.get(element);
152
+ if (!linkData)
153
+ return;
154
+ const expandedRect = this.getExpandedRect(element.getBoundingClientRect(), {
155
+ top: 100,
156
+ left: 100,
157
+ right: 100,
158
+ bottom: 100,
159
+ });
160
+ if (expandedRect != linkData.expandedRect) {
161
+ console.log("updating rect");
162
+ this.links.set(element, {
163
+ ...linkData,
164
+ expandedRect,
165
+ });
166
+ }
167
+ if (this.debugMode && this.debugger) {
168
+ const updatedData = this.links.get(element);
169
+ if (updatedData)
170
+ this.debugger.createOrUpdateLinkOverlay(element, updatedData);
171
+ }
172
+ }
173
+ updateAllRects() {
174
+ this.links.forEach((_, element) => {
175
+ this.updateExpandedRect(element);
176
+ });
177
+ }
178
+ predictMousePosition = (point) => {
179
+ const now = performance.now();
180
+ const currentPosition = { point, time: now };
181
+ const { x, y } = point;
182
+ this.positions.push(currentPosition);
183
+ if (this.positions.length > this.positionHistorySize) {
184
+ this.positions.shift();
185
+ }
186
+ if (this.positions.length < 2) {
187
+ return { x, y };
188
+ }
189
+ const first = this.positions[0];
190
+ const last = this.positions[this.positions.length - 1];
191
+ const dt = (last.time - first.time) / 1000;
192
+ if (dt === 0) {
193
+ return { x, y };
194
+ }
195
+ const dx = last.point.x - first.point.x;
196
+ const dy = last.point.y - first.point.y;
197
+ const vx = dx / dt;
198
+ const vy = dy / dt;
199
+ const trajectoryPredictionTimeInSeconds = this.trajectoryPredictionTime / 1000;
200
+ const predictedX = x + vx * trajectoryPredictionTimeInSeconds;
201
+ const predictedY = y + vy * trajectoryPredictionTimeInSeconds;
202
+ return { x: predictedX, y: predictedY };
203
+ };
204
+ pointIntersectsRect = (x, y, rect) => {
205
+ return x >= rect.left && x <= rect.right && y >= rect.top && y <= rect.bottom;
206
+ };
207
+ isMouseInExpandedArea = (area, clientPoint, isAlreadyHovering) => {
208
+ const isInExpandedArea = clientPoint.x >= area.left &&
209
+ clientPoint.x <= area.right &&
210
+ clientPoint.y >= area.top &&
211
+ clientPoint.y <= area.bottom;
212
+ if (isInExpandedArea && !isAlreadyHovering) {
213
+ return { isHoveringInArea: true, shouldRunCallback: true };
214
+ }
215
+ return { isHoveringInArea: isInExpandedArea, shouldRunCallback: false };
216
+ };
217
+ handleMouseMove = (e) => {
218
+ this.currentPoint = { x: e.clientX, y: e.clientY };
219
+ this.predictedPoint = this.enableMouseTrajectory
220
+ ? this.predictMousePosition(this.currentPoint)
221
+ : this.currentPoint;
222
+ const linksToUpdateInDebugger = [];
223
+ this.links.forEach((linkData, element) => {
224
+ if (!linkData.expandedRect)
225
+ return;
226
+ const { isHoveringInArea, shouldRunCallback } = this.isMouseInExpandedArea(linkData.expandedRect, this.currentPoint, linkData.isHovering);
227
+ let linkStateChanged = false;
228
+ if (this.enableMouseTrajectory && !isHoveringInArea) {
229
+ if (this.pointIntersectsRect(this.predictedPoint.x, this.predictedPoint.y, linkData.expandedRect)) {
230
+ if (!linkData.isTrajectoryHit) {
231
+ linkData.callback();
232
+ console.log("trajectory");
233
+ this.links.set(element, {
234
+ ...linkData,
235
+ isTrajectoryHit: true,
236
+ trajectoryHitTime: performance.now(),
237
+ isHovering: isHoveringInArea,
238
+ });
239
+ linkStateChanged = true;
240
+ }
241
+ }
242
+ }
243
+ if (linkData.isHovering !== isHoveringInArea) {
244
+ this.links.set(element, {
245
+ ...linkData,
246
+ isHovering: isHoveringInArea,
247
+ isTrajectoryHit: this.links.get(element).isTrajectoryHit,
248
+ trajectoryHitTime: this.links.get(element).trajectoryHitTime,
249
+ });
250
+ linkStateChanged = true;
251
+ }
252
+ if (linkStateChanged) {
253
+ linksToUpdateInDebugger.push(element);
254
+ }
255
+ if (shouldRunCallback) {
256
+ if (!linkData.isTrajectoryHit ||
257
+ (linkData.isTrajectoryHit && !this.enableMouseTrajectory)) {
258
+ linkData.callback();
259
+ console.log("hover");
260
+ }
261
+ }
262
+ });
263
+ if (this.debugMode && this.debugger) {
264
+ linksToUpdateInDebugger.forEach((element) => {
265
+ const data = this.links.get(element);
266
+ if (data)
267
+ this.debugger.createOrUpdateLinkOverlay(element, data);
268
+ });
269
+ this.debugger.updateTrajectoryVisuals(this.currentPoint, this.predictedPoint, this.enableMouseTrajectory);
270
+ }
271
+ };
272
+ // Throttled handler for resize and scroll events
273
+ handleResizeOrScroll = () => {
274
+ if (this.resizeScrollThrottleTimeoutId) {
275
+ clearTimeout(this.resizeScrollThrottleTimeoutId);
276
+ }
277
+ const now = performance.now();
278
+ const timeSinceLastCall = now - this.lastResizeScrollCallTimestamp;
279
+ if (timeSinceLastCall >= this.resizeScrollThrottleDelay) {
280
+ this.updateAllRects();
281
+ this.lastResizeScrollCallTimestamp = now;
282
+ this.resizeScrollThrottleTimeoutId = null;
283
+ }
284
+ else {
285
+ this.resizeScrollThrottleTimeoutId = setTimeout(() => {
286
+ this.updateAllRects();
287
+ this.lastResizeScrollCallTimestamp = performance.now();
288
+ this.resizeScrollThrottleTimeoutId = null;
289
+ }, this.resizeScrollThrottleDelay - timeSinceLastCall);
290
+ }
291
+ };
292
+ setupGlobalListeners() {
293
+ if (this.isSetup)
294
+ return;
295
+ document.addEventListener("mousemove", this.handleMouseMove);
296
+ // Use the throttled handler for resize and scroll
297
+ window.addEventListener("resize", this.handleResizeOrScroll);
298
+ window.addEventListener("scroll", this.handleResizeOrScroll);
299
+ this.isSetup = true;
300
+ }
301
+ removeGlobalListeners() {
302
+ document.removeEventListener("mousemove", this.handleMouseMove);
303
+ // Remove the throttled handler for resize and scroll
304
+ window.removeEventListener("resize", this.handleResizeOrScroll);
305
+ window.removeEventListener("scroll", this.handleResizeOrScroll);
306
+ // Clear any pending timeout for the throttled handler
307
+ if (this.resizeScrollThrottleTimeoutId) {
308
+ clearTimeout(this.resizeScrollThrottleTimeoutId);
309
+ this.resizeScrollThrottleTimeoutId = null;
310
+ }
311
+ this.isSetup = false;
312
+ }
313
+ }
314
+ exports.ForesightManager = ForesightManager;
@@ -0,0 +1,2 @@
1
+ export { ForesightManager } from "./ForesightManager/ForesightManager";
2
+ export * from "./types/types";
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.ForesightManager = void 0;
18
+ // Export the ForesightManager (currently called IntentManager)
19
+ var ForesightManager_1 = require("./ForesightManager/ForesightManager");
20
+ Object.defineProperty(exports, "ForesightManager", { enumerable: true, get: function () { return ForesightManager_1.ForesightManager; } });
21
+ // Export any types you need
22
+ __exportStar(require("./types/types"), exports);
@@ -0,0 +1,29 @@
1
+ export type Rect = {
2
+ top: number;
3
+ left: number;
4
+ right: number;
5
+ bottom: number;
6
+ };
7
+ export type IntentCallback = () => void;
8
+ export type LinkElement = HTMLAnchorElement;
9
+ export type MousePosition = {
10
+ point: Point;
11
+ time: number;
12
+ };
13
+ export type Point = {
14
+ x: number;
15
+ y: number;
16
+ };
17
+ export type LinkData = {
18
+ callback: IntentCallback;
19
+ expandedRect: Rect | null;
20
+ isHovering: boolean;
21
+ isTrajectoryHit: boolean;
22
+ trajectoryHitTime: number;
23
+ };
24
+ export type IntentManagerProps = {
25
+ positionHistorySize: number;
26
+ trajectoryPredictionTime: number;
27
+ enableMouseTrajectory: boolean;
28
+ debug: boolean;
29
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "js.foresight",
3
+ "version": "0.0.5",
4
+ "description": "",
5
+ "main": "dist/index.js",
6
+ "types": "dist/index.d.ts",
7
+ "scripts": {
8
+ "clean": "rm -rf dist",
9
+ "build": "pnpm clean && tsc",
10
+ "prepublishOnly": "pnpm build",
11
+ "test": "cd ./test_project && pnpm dev"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist",
21
+ "README.md",
22
+ "LICENSE"
23
+ ],
24
+ "keywords": [],
25
+ "author": "Bart Spaans",
26
+ "license": "MIT",
27
+ "devDependencies": {
28
+ "@types/node": "^22.15.17",
29
+ "typescript": "^5.8.3"
30
+ }
31
+ }