### Install ForesightJS Development Tools Source: https://github.com/spaansba/foresightjs/blob/main/README.md Instructions for installing the dedicated development tools for ForesightJS using pnpm. These tools aid in visualizing and tuning the library's prediction and prefetching behavior. ```bash pnpm add js.foresight-devtools ``` -------------------------------- ### Install ForesightJS using Package Managers Source: https://github.com/spaansba/foresightjs/blob/main/README.md Instructions for installing the ForesightJS library using popular package managers like pnpm, npm, and yarn. This is the first step to integrate ForesightJS into your project. ```bash pnpm add js.foresight # or npm install js.foresight # or yarn add js.foresight ``` -------------------------------- ### Install and Build ForesightJS Dependencies Source: https://github.com/spaansba/foresightjs/blob/main/CONTRIBUTING.md Commands to install all workspace dependencies and build the project using pnpm. This command should be run from the root of the monorepo. ```bash # Install all workspace dependencies pnpm install # then pnpm build ``` -------------------------------- ### Start ForesightJS Development Server Source: https://github.com/spaansba/foresightjs/blob/main/CONTRIBUTING.md Command to start the development page server from the monorepo root. This allows for immediate reflection of changes in the core library source code without needing to rebuild. ```bash # Start the development page from the monorepo root pnpm dev ``` -------------------------------- ### Install ForesightJS Development Tools (CLI) Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/getting-started/your-first-element.md Provides commands to install the ForesightJS development tools package using package managers like pnpm, npm, or yarn. These tools aid in debugging and tuning the prediction system. The package name is 'js.foresight-devtools'. ```bash pnpm add js.foresight-devtools # or npm install js.foresight-devtools # or yarn add js.foresight-devtools ``` -------------------------------- ### Install ForesightJS Development Tools Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/debugging/devtools.md Install the ForesightJS Development Tools package using your preferred package manager. This package is intended for development environments. ```bash pnpm add -D js.foresight-devtools # or npm install -D js.foresight-devtools # or yarn add -D js.foresight-devtools ``` -------------------------------- ### Basic Usage of ForesightLink in Next.js Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/versioned_docs/version-3.3/react/nextjs.md Demonstrates how to use the custom `ForesightLink` component in a Next.js application. This example shows how to link to the 'Home' page with specific styling and a name for tracking purposes. Remember that Next.js prefetching only works in production. ```tsx import ForesightLink from "./ForesightLink" export default function Navigation() { return ( Home ) } ``` -------------------------------- ### Basic ForesightJS Usage in Vanilla JavaScript Source: https://github.com/spaansba/foresightjs/blob/main/README.md Demonstrates the fundamental usage of ForesightJS in vanilla JavaScript. It shows how to initialize the ForesightManager and register an element for tracking with a prefetching callback. This example is suitable for projects not using a specific framework. ```javascript import { ForesightManager } from "foresightjs" // Initialize the manager if you want custom global settings (do this once at app startup) ForesightManager.initialize({ // Optional props (see configuration) }) // Register an element to be tracked const myButton = document.getElementById("my-button") ForesightManager.instance.register({ element: myButton, callback: () => { // This is where your prefetching logic goes }, hitSlop: 20, // Optional: "hit slop" in pixels. // other optional props (see configuration) }) ``` -------------------------------- ### Example Usage of useForesight Hook in React Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/react/hook.md This example demonstrates how to use the useForesight hook within a React component. It attaches the returned elementRef to a button and configures a callback for prefetching data when the button is hovered over. The example also shows how to specify the element type for the ref. ```tsx import useForesight from "./useForesight" function MyComponent() { const { elementRef, registerResults } = useForesight({ callback: () => { console.log("Prefetching data...") // Your prefetch logic here }, hitSlop: 10, name: "my-button", }) return } ``` -------------------------------- ### Run Development Server - Bash Source: https://github.com/spaansba/foresightjs/blob/main/packages/devpage-vue/README.md Command to start the Vue/Vite development server for ForesightJS. This is typically run from the monorepo root directory. ```bash pnpm dev ``` -------------------------------- ### Install ForesightJS and DevTools for Angular Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/angular.md Installs the necessary ForesightJS packages and development tools for an Angular project using either npm or pnpm package managers. ```bash npm install js.foresight ngx-foresight npm install -D js.foresight-devtools # or pnpm add js.foresight js.foresight-devtools ngx-foresight pnpm add -D js.foresight-devtools ``` -------------------------------- ### Vue Integration with ForesightJS and Devtools Source: https://context7.com/spaansba/foresightjs/llms.txt This example shows how to initialize ForesightJS and ForesightDevtools within a Vue application's main entry point (`main.ts`). It initializes ForesightManager globally and uses dynamic import for ForesightDevtools, enabling it only in development environments. ```javascript // Example: Vue integration // In main.ts import { ForesightManager } from "js.foresight" const app = createApp(App) // Initialize ForesightJS ForesightManager.initialize({ enableMousePrediction: true, enableScrollPrediction: true }) // Development tools if (import.meta.env.DEV) { import("js.foresight-devtools").then(({ ForesightDevtools }) => { ForesightDevtools.initialize({ showDebugger: true, isControlPanelDefaultMinimized: false, logging: { logLocation: "controlPanel", callbackCompleted: true, callbackInvoked: true, elementReactivated: true, } }) }) } app.mount("#app") ``` -------------------------------- ### Initialize ForesightJS and ForesightDevtools Source: https://context7.com/spaansba/foresightjs/llms.txt Demonstrates the initialization of both ForesightManager and ForesightDevtools. ForesightManager handles core analytics tracking, while ForesightDevtools provides visual debugging tools. This example shows setting various prediction and logging options, emphasizing conditional initialization in development. ```javascript import { ForesightManager } from "js.foresight" import { ForesightDevtools } from "js.foresight-devtools" // Initialize ForesightJS first ForesightManager.initialize({ enableMousePrediction: true, trajectoryPredictionTime: 120, enableTabPrediction: true, tabOffset: 2 }) // Initialize development tools with all options ForesightDevtools.initialize({ showDebugger: true, // Show/hide entire devtools overlay isControlPanelDefaultMinimized: false, // Start with panel expanded or minimized showNameTags: true, // Display element names on hover overlay sortElementList: "visibility", // "visibility", "name", or "registration" logging: { logLocation: "controlPanel", // "controlPanel" or "console" // Control which events to log callbackInvoked: true, // Log before callback fires callbackCompleted: true, // Log after callback completes (with duration) elementRegistered: false, // Log when elements register elementUnregistered: false, // Log when elements unregister elementReactivated: true, // Log when elements reactivate after cooldown elementDataUpdated: false, // Log element data changes (bounds/visibility) managerSettingsChanged: true, // Log global settings changes mouseTrajectoryUpdate: false, // Don't log (fires very frequently) scrollTrajectoryUpdate: false, // Don't log (fires very frequently) deviceStrategyChanged: true, // Log when switching mouse/touch/pen }, }) ``` -------------------------------- ### React Integration with ForesightJS and Devtools Source: https://context7.com/spaansba/foresightjs/llms.txt This example illustrates integrating ForesightJS and ForesightDevtools into a React application using the `useEffect` hook. It ensures initialization happens after the component mounts and demonstrates dynamic import for the devtools, activated only in development environments. ```javascript // Example: React integration import { useEffect } from "react" function App() { useEffect(() => { // Initialize ForesightJS ForesightManager.initialize({ trajectoryPredictionTime: 100, tabOffset: 3 }) // Initialize devtools in development only if (import.meta.env.DEV) { const { ForesightDevtools } = await import("js.foresight-devtools") ForesightDevtools.initialize({ showDebugger: true, showNameTags: true, logging: { logLocation: "controlPanel", callbackCompleted: true, callbackInvoked: true, } }) } }, []) return } ``` -------------------------------- ### Basic Usage of ForesightLink in Next.js Navigation Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/react/nextjs.md Demonstrates how to use the custom `ForesightLink` component within a Next.js application's navigation. This example shows basic props like `href`, `className`, and `name` for identifying the link for ForesightJS tracking. ```tsx import ForesightLink from "./ForesightLink" export default function Navigation() { return ( Home ) } ``` -------------------------------- ### ForesightManager.instance Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/debugging/static-properties.md Gets the singleton instance of ForesightManager, initializing it if necessary. This is the primary way to access the manager throughout your application. ```APIDOC ## ForesightManager.instance ### Description Gets the singleton instance of ForesightManager, initializing it if necessary. This is the primary way to access the manager throughout your application. ### Method Static Property Access ### Endpoint N/A ### Parameters None ### Request Example ```javascript const manager = ForesightManager.instance // Register an element manager.register({ element: myButton, callback: () => console.log("Predicted interaction!"), }) // or ForesightManager.instance.register({ element: myButton, callback: () => console.log("Predicted interaction!"), }) ``` ### Response #### Success Response - **instance** (ForesightManager) - The singleton instance of the ForesightManager. #### Response Example ```javascript // manager variable will hold the ForesightManager instance ``` ``` -------------------------------- ### Usage of ForesightLink in React Navigation Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/react/react-router.md Demonstrates how to use the custom `ForesightLink` component within a React navigation structure. This example shows passing `to` props for routing and optional props like `hitSlop` and `name` for ForesightJS configuration. ```tsx export function Navigation() { return ( <> contact about ) } ``` -------------------------------- ### Basic ForesightJS Composable Usage in Vue Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/vue/composable.md This example demonstrates the most basic usage of the `useForesight` composable in a Vue component. It attaches a button and configures ForesightJS to prefetch data when the button is hovered over. This is functionally similar to using the `v-foresight` directive. ```html ``` -------------------------------- ### Set Uniform Default Hit Slop Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/configuration/global-settings.md This example initializes ForesightManager with a uniform `defaultHitSlop` value. This invisible area around elements increases their hover hitbox by the specified pixel amount on all sides. The value is clamped between 0 and 2000 pixels. ```javascript // Uniform hit slop ForesightManager.initialize({ defaultHitSlop: 20, // 20px on all sides }) ``` -------------------------------- ### ForesightJS Analytics Implementation (TypeScript) Source: https://context7.com/spaansba/foresightjs/llms.txt An example implementation of a ForesightAnalytics class that listens for 'callbackCompleted' events to gather statistics on prefetch operations. It tracks total, successful, and failed prefetches, calculates the average duration, and sends summarized data to an analytics service. The class manages its listeners using an AbortController. ```typescript class ForesightAnalytics { private controller = new AbortController() private prefetchStats = { total: 0, successful: 0, failed: 0, avgDuration: 0 } constructor() { this.setupListeners() } private setupListeners() { const signal = this.controller.signal ForesightManager.instance.addEventListener("callbackCompleted", (event) => { this.prefetchStats.total++ if (event.status === "success") { this.prefetchStats.successful++ } else if (event.status === "error") { this.prefetchStats.failed++ } // Update average duration const currentAvg = this.prefetchStats.avgDuration const count = this.prefetchStats.total this.prefetchStats.avgDuration = (currentAvg * (count - 1) + event.elapsed) / count // Send to analytics service this.sendAnalytics({ event: "prefetch_completed", element: event.elementData.name, duration: event.elapsed, status: event.status, trigger: event.hitType.kind, meta: event.elementData.meta }) }, { signal }) } private sendAnalytics(data: any) { // Send to your analytics platform console.log("Analytics:", data) } getStats() { return this.prefetchStats } } ``` -------------------------------- ### Initialize ForesightJS Development Tools (JavaScript) Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/getting-started/your-first-element.md Shows how to initialize the ForesightJS development tools within a JavaScript application. This involves importing the ForesightDevtools class and calling its initialize method. Optional props can be passed for further configuration. Requires the 'js.foresight-devtools' library. ```javascript import { ForesightDevtools } from "js.foresight-devtools" // Initialize development tools ForesightDevtools.initialize({ // optional props }) ``` -------------------------------- ### Enable ForesightJS Development Tools with Configuration Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/debugging/devtools.md Initialize ForesightJS and the development tools, with options to customize their behavior and appearance. This includes settings for visibility, control panel state, element sorting, and logging preferences. ```javascript import { ForesightManager } from "js.foresight" import { ForesightDevtools } from "js.foresight-devtools" // Initialize ForesightJS ForesightManager.initialize({}) // Initialize the development tools (all options are optional) ForesightDevtools.initialize({ showDebugger: true, isControlPanelDefaultMinimized: false, // optional setting which allows you to minimize the control panel on default showNameTags: true, // optional setting which shows the name of the element sortElementList: "visibility", // optional setting for how the elements in the control panel are sorted logging: { logLocation: "controlPanel", // Where to log the Foresight Events callbackCompleted: true, elementReactivated: true, callbackInvoked: true, elementDataUpdated: false, elementRegistered: false, elementUnregistered: false, managerSettingsChanged: true, mouseTrajectoryUpdate: false, // dont log this to the devtools scrollTrajectoryUpdate: false, // dont log this to the devtools deviceStrategyChanged: true, }, }) ``` -------------------------------- ### ForesightManager.instance.registeredElements Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/debugging/static-properties.md Gets a Map of all currently registered elements and their associated data. This is useful for debugging or inspecting the current state of registered elements. ```APIDOC ## ForesightManager.instance.registeredElements ### Description Gets a Map of all currently registered elements and their associated data. This is useful for debugging or inspecting the current state of registered elements. ### Method Static Property Access ### Endpoint N/A ### Parameters None ### Request Example ```javascript const registeredElementsMap = ForesightManager.instance.registeredElements console.log(registeredElementsMap.size) // Number of registered elements ``` ### Response #### Success Response - **registeredElements** (ReadonlyMap) - A read-only Map containing all registered elements as keys and their associated data as values. #### Response Example ```json // Example of the Map structure (not direct JSON output) Map { ForesightElement1 => ForesightElementData1, ForesightElement2 => ForesightElementData2 } ``` ``` -------------------------------- ### Configure Tab Navigation Offset Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/configuration/global-settings.md This example sets the `tabOffset` to control how many tab stops away from an element ForesightJS should trigger its callback when keyboard prediction is enabled. The value is clamped between 0 and 20. ```javascript ForesightManager.initialize({ tabOffset: 1, // Trigger callback when 1 tab stop away }) ``` -------------------------------- ### Clone ForesightJS Repository Source: https://github.com/spaansba/foresightjs/blob/main/CONTRIBUTING.md Instructions to clone the ForesightJS repository to your local machine and navigate into the project directory. This is the first step in setting up your development environment. ```bash git clone https://github.com/your-username/ForesightJS.git cd ForesightJS ``` -------------------------------- ### Retrieve Registration Status and Device Info in JavaScript Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/configuration/element-settings.md Shows how to destructure the return value of the `ForesightManager.instance.register()` method to obtain `isTouchDevice`, `isLimitedConnection`, and `isRegistered` properties. ```javascript const { isTouchDevice, isLimitedConnection, isRegistered } = ForesightManager.instance.register({ element: myElement, callback: () => {}, }) ``` -------------------------------- ### Configure ForesightjsStrategy as Preloading Strategy in Angular Router Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/angular.md Configures the ForesightjsStrategy as the preloading strategy for the Angular router. This ensures that routes are preloaded efficiently based on ForesightJS predictions. Examples are provided for both newer `provideRouter` and older `RouterModule.forRoot` configurations. ```typescript // configure preloading strategy as per routes provideRouter(routes, withPreloading(ForesightjsStrategy)), // for older versions RouterModule.forRoot(routes, { preloadingStrategy: ForesightjsStrategy }) ``` -------------------------------- ### Get ForesightManager State Snapshot (JavaScript) Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/versioned_docs/version-3.3/debugging/static-properties.md Provides a snapshot of the current ForesightManager state, including global settings, registered elements, observer data, and interaction statistics. This method is invaluable for debugging, monitoring application performance, and development. ```javascript const managerData = ForesightManager.instance.getManagerData() // managerData is a Readonly ``` -------------------------------- ### Register Element with ForesightJS (Vanilla JS) Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/getting-started/your-first-element.md Demonstrates the basic usage of ForesightJS to register an HTML element. This involves importing the ForesightManager and calling the register method with an element and a callback function. The callback is executed when user interaction with the element is predicted. Dependencies include the 'js.foresight' library. ```javascript import { ForesightManager } from "js.foresight" // Register an element to be tracked const myLink = document.getElementById("my-link") ForesightManager.instance.register({ element: myLink, callback: () => { // This is where your prefetching logic goes console.log("User is likely to interact with this element!") }, // Optional element settings }) ``` -------------------------------- ### Device Strategy Changed Event Type in TypeScript Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/events.md Defines the structure for the 'deviceStrategyChanged' event. This event is triggered when the user's input strategy changes, for example, switching between mouse/keyboard and pen/touch input. It records the timestamp and the old and new strategies. ```typescript type ManagerSettingsChangedEvent = { type: "deviceStrategyChanged" timestamp: number newStrategy: CurrentDeviceStrategy oldStrategy: CurrentDeviceStrategy } ``` -------------------------------- ### Register Element with Basic Settings in JavaScript Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/configuration/element-settings.md Demonstrates the basic registration of a DOM element with ForesightManager, including essential parameters like `element`, `callback`, and optional settings such as `hitSlop`, `name`, `meta`, and `reactivateAfter`. It also shows how to destructure the return value. ```javascript const myElement = document.getElementById("my-element") const { isTouchDevice, isLimitedConnection, isRegistered } = ForesightManager.instance.register({ element: myElement, // Required: The element to monitor callback: () => { // Required: Function that executes when interaction is predicted console.log("prefetching") }, hitSlop: 50, // slop around the element, making its hitbox bigger name: "My Foresight button!", // name visible in the debug tools meta: { route: "/about", }, // your custom meta data for analytics reactivateAfter: 5 * 60 * 1000, // time for the element to reactivate after the callback has been hit }) ``` -------------------------------- ### Initialize ForesightJS with Minimum Connection Type (JavaScript) Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/configuration/global-settings.md Configures the minimum network connection speed required for ForesightJS to register elements. If the user's connection is slower than the specified threshold, elements will not be registered. This relies on the Network Information API, which may not be universally supported. If the API is unavailable, ForesightJS registers elements regardless of connection speed. ```javascript ForesightManager.initialize({ minimumConnectionType: "3g", }) ``` -------------------------------- ### Initialize ForesightManager with Global Settings (JavaScript) Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/versioned_docs/version-3.3/getting-started/initialize-the-manager.md Initializes the ForesightManager with custom global settings for mouse, keyboard, and scroll prediction, touch device strategy, connection type, and default element hit slop. This is an optional step and the manager can be initialized only once. ```javascript ForesightManager.initialize({ // Mouse prediction settings enableMousePrediction: true, // Enable/disable mouse trajectory prediction trajectoryPredictionTime: 120, // How far ahead to predict (10-200ms) positionHistorySize: 8, // Mouse positions to track (2-30) // Keyboard prediction settings enableTabPrediction: true, // Enable/disable keyboard navigation prediction tabOffset: 2, // Tab stops ahead to trigger (0-20) // Scroll prediction settings enableScrollPrediction: true, // Enable/disable scroll prediction scrollMargin: 150, // Pixel distance for scroll detection (30-300) // Touch device settings touchDeviceStrategy: "viewport", // "none", "viewport", or "onTouchStart" // Connection settings minimumConnectionType: "3g", // "slow-2g", "2g", "3g", "4g" // Default element settings defaultHitSlop: 0, // Default hit slop for all elements (number or {top, right, bottom, left}) }) ``` -------------------------------- ### Adjust Mouse Position History Size Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/configuration/global-settings.md This example configures the `positionHistorySize` setting to store more mouse positions for velocity calculations. Increasing this value can lead to smoother predictions at the cost of increased memory usage. The value is clamped between 2 and 30. ```javascript ForesightManager.initialize({ positionHistorySize: 12, // Keep more position history for smoother predictions }) ``` -------------------------------- ### Initialize ForesightManager with Basic Global Settings Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/configuration/global-settings.md This snippet demonstrates the basic initialization of the ForesightManager with several common global settings. These settings control features like mouse prediction, history size, trajectory prediction time, and more. All settings are optional, and if default options are desired, explicit initialization may not be necessary. ```javascript import { ForesightManager } from "js.foresight" // Initialize the manager once at the top of your app if you want custom global settings // ALL SETTINGS ARE OPTIONAL ForesightManager.initialize({ enableMousePrediction: true, positionHistorySize: 8, trajectoryPredictionTime: 80, defaultHitSlop: 10, enableTabPrediction: true, tabOffset: 3, enableScrollPrediction: true, scrollMargin: 150, touchDeviceStrategy: "viewport", enableManagerLogging: false, minimumConnectionType: "3g", }) ``` -------------------------------- ### ForesightJS Element Registration with Advanced Settings Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/getting-started/your-first-element.md Illustrates advanced element registration in ForesightJS, including optional properties like 'hitSlop' for hitbox size, 'name' for debugging, 'meta' for custom analytics data, and 'reactivateAfter' to control re-triggering. This provides more granular control over element tracking. Requires the 'js.foresight' library. ```javascript import { ForesightManager } from "js.foresight" const myLink = document.getElementById("my-link") ForesightManager.instance.register({ element: myLink, callback: () => { console.log("User is likely to interact with this element!") }, hitSlop: 50, // slop around the element, making its hitbox bigger name: "My Foresight button!", // name visible in the debug tools meta: { route: "/about", }, // your custom meta data for analytics reactivateAfter: 5 * 60 * 1000, // time for the element to reactivate after the callback has been hit }) ``` -------------------------------- ### Get Registered Elements Map (JavaScript) Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/debugging/static-properties.md Retrieves a read-only Map containing all currently registered elements and their associated data within the ForesightManager. This property is valuable for inspecting the current state of registered elements, often used during debugging or for dynamic analysis. ```javascript const registeredElementsMap = ForesightManager.instance.registeredElements ``` -------------------------------- ### ForesightManager.instance.isInitiated Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/debugging/static-properties.md Checks whether the ForesightManager has been initialized. ```APIDOC ## ForesightManager.instance.isInitiated ### Description Checks whether the ForesightManager has been initialized. ### Method Static Property Access ### Endpoint N/A ### Parameters None ### Request Example ```javascript const isInitialized = ForesightManager.instance.isInitiated if (isInitialized) { console.log("ForesightManager is initialized.") } else { console.log("ForesightManager is not initialized.") } ``` ### Response #### Success Response - **isInitiated** (Readonly) - `true` if the ForesightManager has been initialized, `false` otherwise. #### Response Example ```json true ``` ``` -------------------------------- ### Get ForesightManager Data Snapshot (JavaScript) Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/debugging/static-properties.md Provides a read-only snapshot of the current ForesightManager's state. This includes global settings, registered elements, position observer data, and interaction statistics. It's primarily intended for debugging, monitoring, and development purposes. ```javascript const managerData = ForesightManager.instance.getManagerData() ``` -------------------------------- ### Initialize ForesightJS with Manager Logging Enabled (JavaScript) Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/configuration/global-settings.md Enables basic logging for the ForesightManager and its handlers. These logs provide insights into initialization, strategy switching, controller abortion, and cache invalidation, primarily for debugging purposes by ForesightJS maintainers but potentially useful for implementers. ```javascript ForesightManager.initialize({ enableManagerLogging: true, }) ``` -------------------------------- ### Initialize ForesightManager with Global Settings Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/getting-started/initialize-the-manager.md Initializes the ForesightManager with custom global settings to control ForesightJS's behavior. This is an optional step and allows customization of prediction and device settings. If not called, the manager initializes with default settings when the first element is registered. ```javascript ForesightManager.initialize({ // Mouse prediction settings enableMousePrediction: true, // Enable/disable mouse trajectory prediction trajectoryPredictionTime: 120, // How far ahead to predict (10-200ms) positionHistorySize: 8, // Mouse positions to track (2-30) // Keyboard prediction settings enableTabPrediction: true, // Enable/disable keyboard navigation prediction tabOffset: 2, // Tab stops ahead to trigger (0-20) // Scroll prediction settings enableScrollPrediction: true, // Enable/disable scroll prediction scrollMargin: 150, // Pixel distance for scroll detection (30-300) // Touch device settings touchDeviceStrategy: "viewport", // "none", "viewport", or "onTouchStart" // Connection settings minimumConnectionType: "3g", // "slow-2g", "2g", "3g", "4g" // Default element settings defaultHitSlop: 0 // Default hit slop for all elements (number or {top, right, bottom, left}) }) ``` -------------------------------- ### Vue Composable for ForesightJS Integration Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/vue/composable.md The `useForesight` composable provides a Vue-native way to integrate ForesightJS. It gives direct access to `registerResults` and the element's `templateRef`, but requires more setup code than the `v-foresight` directive. It takes options including `templateRefKey`, and optionally `callback`, `hitSlop`, and `name`. ```typescript import { ref, onMounted, useTemplateRef, readonly, type ComponentPublicInstance } from "vue" import { ForesightManager, type ForesightRegisterOptionsWithoutElement, type ForesightRegisterResult, } from "js.foresight" type UseForesightOptions = ForesightRegisterOptionsWithoutElement & { templateRefKey: string } export function useForesight( options: UseForesightOptions ) { const templateRef = useTemplateRef(options.templateRefKey) const registerResults = ref(null) onMounted(() => { if (!templateRef.value) { return } // Extract the underlying HTMLElement if the templateRef is a Vue component const element = templateRef.value instanceof HTMLElement ? templateRef.value : templateRef.value.$el registerResults.value = ForesightManager.instance.register({ element, ...options, }) }) return { templateRef, registerResults: readonly(registerResults), } } ``` -------------------------------- ### Accessing TemplateRef with ForesightJS Composable in Vue Source: https://github.com/spaansba/foresightjs/blob/main/packages/docs/docs/vue/composable.md This example shows how to use the `useForesight` composable to gain direct access to the `templateRef` of a Vue component. This allows for more advanced interactions with the target element or component instance. When targeting a Vue component, specify the component's instance type as the generic parameter. ```html ```