@foresightjs/vue 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE 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,38 @@
1
+ # @foresightjs/vue
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@foresightjs/vue.svg)](https://www.npmjs.com/package/@foresightjs/vue)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
+ [![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
6
+
7
+ Official Vue 3 bindings for [ForesightJS](https://foresightjs.com/), a lightweight library that predicts user intent (mouse trajectory, keyboard navigation, scroll, touch) to trigger callbacks like prefetching _before_ the user interacts.
8
+
9
+ - **Docs:** [foresightjs.com/docs/vue/installation](https://foresightjs.com/docs/vue/installation)
10
+ - **Core library:** [`js.foresight`](https://www.npmjs.com/package/js.foresight)
11
+ - **Playground:** [foresightjs.com](https://foresightjs.com/#playground)
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ pnpm add @foresightjs/vue js.foresight
17
+ # or
18
+ npm install @foresightjs/vue js.foresight
19
+ ```
20
+
21
+ Requires Vue 3.5+
22
+
23
+ ## What's included
24
+
25
+ - `v-foresight` -> directive to register an element with a callback or full options object
26
+ - `useForesight` -> register a single element and get reactive refs for its state
27
+ - `useForesights` -> register a dynamic list of elements from a single composable
28
+ - `useForesightEvent` -> subscribe to a ForesightManager event for the lifetime of the calling scope
29
+
30
+ For usage and examples, see the [Vue documentation](https://foresightjs.com/docs/vue/installation).
31
+
32
+ ## Contributing
33
+
34
+ Please see the [contributing guidelines](https://github.com/spaansba/ForesightJS/blob/main/CONTRIBUTING.md).
35
+
36
+ ## License
37
+
38
+ [MIT](./LICENSE)
@@ -0,0 +1,86 @@
1
+ import { CallbackCompletedEvent, CallbackHitType, CallbackHits, CallbackInvokedEvent, DeviceStrategyChangedEvent, ElementRegisteredEvent, ElementUnregisteredEvent, ForesightCallback, ForesightElementState, ForesightElementState as ForesightElementState$1, ForesightEvent, ForesightEvent as ForesightEvent$1, ForesightEventMap, ForesightEventMap as ForesightEventMap$1, ForesightManager, ForesightManagerSettings, ForesightRegisterOptionsWithoutElement, ForesightRegisterOptionsWithoutElement as ForesightRegisterOptionsWithoutElement$1, HitSlop, ManagerSettingsChangedEvent, MinimumConnectionType, MouseTrajectoryUpdateEvent, ScrollTrajectoryUpdateEvent, TouchDeviceStrategy, UpdateForsightManagerSettings } from "js.foresight";
2
+ import { ComponentPublicInstance, MaybeRef, MaybeRefOrGetter, ObjectDirective, ToRefs } from "vue";
3
+
4
+ //#region src/types/index.d.ts
5
+ type MaybeElement = Element | ComponentPublicInstance | null | undefined;
6
+ type UseForesightOptions = ForesightRegisterOptionsWithoutElement$1;
7
+ type UseForesightReturn = ToRefs<Readonly<ForesightElementState$1>> & {
8
+ /** Template ref function - bind to an element with `:ref="elementRef"`. */elementRef: (el: MaybeElement) => void;
9
+ };
10
+ //#endregion
11
+ //#region src/composables/useForesight.d.ts
12
+ /**
13
+ * Registers a single element with ForesightManager.
14
+ *
15
+ * @param options - Registration options as a plain object, ref, or getter.
16
+ *
17
+ * Returns reactive refs for all element state (`isPredicted`, `hitCount`, etc.)
18
+ * plus an `elementRef` function to bind the target element.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * const { isPredicted, elementRef } = useForesight({
23
+ * callback: () => prefetch('/about'),
24
+ * name: 'about-link',
25
+ * })
26
+ * ```
27
+ * ```vue
28
+ * <a :ref="elementRef" href="/about">About</a>
29
+ * ```
30
+ */
31
+ declare const useForesight: (options: MaybeRefOrGetter<UseForesightOptions>) => UseForesightReturn;
32
+ //#endregion
33
+ //#region src/composables/useForesights.d.ts
34
+ type UseForesightSlot = Readonly<ForesightElementState$1> & {
35
+ /** Template ref function - bind to an element with `:ref="slot.elementRef"`. */elementRef: (el: MaybeElement) => void;
36
+ };
37
+ /**
38
+ * Registers multiple elements with ForesightManager from a single composable.
39
+ *
40
+ * @param options - Array of registration options (plain array, ref, or getter).
41
+ * The array length determines the number of slots.
42
+ *
43
+ * Returns a reactive array of `UseForesightSlot` objects. Each slot contains:
44
+ * - `elementRef` - a template ref function to bind an element (`:ref="slot.elementRef"`)
45
+ * - All `ForesightElementState` properties (`isPredicted`, `hitCount`, etc.)
46
+ *
47
+ * @example
48
+ * ```ts
49
+ * const items = ref([{ name: 'a' }, { name: 'b' }])
50
+ *
51
+ * const slots = useForesights(() =>
52
+ * items.value.map(item => ({
53
+ * callback: () => prefetch(item.name),
54
+ * name: item.name,
55
+ * }))
56
+ * )
57
+ * ```
58
+ * ```vue
59
+ * <button v-for="(item, i) in items" :ref="slots[i].elementRef">
60
+ * {{ slots[i].isPredicted ? 'predicted!' : item.name }}
61
+ * </button>
62
+ * ```
63
+ */
64
+ declare const useForesights: (options: MaybeRefOrGetter<UseForesightOptions[]>) => UseForesightSlot[];
65
+ //#endregion
66
+ //#region src/composables/useForesightEvent.d.ts
67
+ type ListenerArg<K extends ForesightEvent$1> = MaybeRef<(event: ForesightEventMap$1[K]) => void>;
68
+ /**
69
+ * Subscribes to a ForesightManager event for the lifetime of the calling scope.
70
+ *
71
+ * The listener is always invoked with its latest reference - no stale closures
72
+ * when passed as a `ref()`. Changing `eventType` automatically tears down the
73
+ * previous subscription and creates a new one; changing only the `listener`
74
+ * does not re-subscribe.
75
+ */
76
+ declare const useForesightEvent: <K extends ForesightEvent$1>(eventType: MaybeRefOrGetter<K>, listener: ListenerArg<K>) => void;
77
+ //#endregion
78
+ //#region src/directives/vForesight.d.ts
79
+ /** Shorthand: pass just the callback instead of a full options object. */
80
+ type CallbackShorthand = () => void;
81
+ type ForesightDirectiveValue = UseForesightOptions | CallbackShorthand;
82
+ type ForesightDirectiveElement = HTMLElement | SVGElement;
83
+ declare const vForesight: ObjectDirective<ForesightDirectiveElement, ForesightDirectiveValue>;
84
+ //#endregion
85
+ export { type CallbackCompletedEvent, type CallbackHitType, type CallbackHits, type CallbackInvokedEvent, type DeviceStrategyChangedEvent, type ElementRegisteredEvent, type ElementUnregisteredEvent, type ForesightCallback, type ForesightElementState, type ForesightEvent, type ForesightEventMap, ForesightManager, type ForesightManagerSettings, type ForesightRegisterOptionsWithoutElement, type HitSlop, type ManagerSettingsChangedEvent, type MinimumConnectionType, type MouseTrajectoryUpdateEvent, type ScrollTrajectoryUpdateEvent, type TouchDeviceStrategy, type UpdateForsightManagerSettings, type UseForesightOptions, type UseForesightReturn, type UseForesightSlot, useForesight, useForesightEvent, useForesights, vForesight };
86
+ //# sourceMappingURL=index.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../src/types/index.ts","../src/composables/useForesight.ts","../src/composables/useForesights.ts","../src/composables/useForesightEvent.ts","../src/directives/vForesight.ts"],"mappings":";;;;KAGY,YAAA,GAAe,OAAA,GAAU,uBAAA;AAAA,KAQzB,mBAAA,GAAsB,wCAAA;AAAA,KAEtB,kBAAA,GAAqB,MAAA,CAAO,QAAA,CAAS,uBAAA;EAVtB,2EAYzB,UAAA,GAAa,EAAA,EAAI,YAAA;AAAA;;;;;AAZnB;;;;;AAQA;;;;;AAEA;;;;;;;cCwBa,YAAA,GACX,OAAA,EAAS,gBAAA,CAAiB,mBAAA,MACzB,kBAAA;;;KCpBS,gBAAA,GAAmB,QAAA,CAAS,uBAAA;EFhB5B,gFEkBV,UAAA,GAAa,EAAA,EAAI,YAAA;AAAA;;;AFVnB;;;;;AAEA;;;;;;;;;;;;;;;;;;;;cE6Ca,aAAA,GACX,OAAA,EAAS,gBAAA,CAAiB,mBAAA,QACzB,gBAAA;;;KCzDE,WAAA,WAAsB,gBAAA,IAAkB,QAAA,EAAU,KAAA,EAAO,mBAAA,CAAkB,CAAA;;AHAhF;;;;;AAQA;;cGEa,iBAAA,aAA+B,gBAAA,EAC1C,SAAA,EAAW,gBAAA,CAAiB,CAAA,GAC5B,QAAA,EAAU,WAAA,CAAY,CAAA;;;;KCVnB,iBAAA;AAAA,KAEA,uBAAA,GAA0B,mBAAA,GAAsB,iBAAA;AAAA,KAEhD,yBAAA,GAA4B,WAAA,GAAc,UAAA;AAAA,cAmBlC,UAAA,EAAY,eAAA,CAAgB,yBAAA,EAA2B,uBAAA"}
package/dist/index.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import{ForesightManager as e,ForesightManager as t,createUnregisteredSnapshot as n}from"js.foresight";import{computed as r,isRef as i,markRaw as a,onScopeDispose as o,reactive as s,readonly as c,toRefs as l,toValue as u,watch as d}from"vue";const f=e=>{if(!e)return null;if(e instanceof Element)return e;let t=e.$el;return t instanceof Node&&t.nodeType===Node.COMMENT_NODE?null:t??null},p=e=>{let r=s(n(!1)),i=null,a=null,p=null,m=t=>u(e).callback(t),h=(e,n)=>{a=t.instance.register({...n,element:e,callback:m}),Object.assign(r,a.getSnapshot()),p=a.subscribe(()=>{a&&Object.assign(r,a.getSnapshot())})},g=()=>{p?.(),p=null,a?.unregister(),a=null,Object.assign(r,n(!1))},_=t=>{let n=f(t)??null;n!==i&&(i&&a&&g(),i=n,n&&h(n,u(e)))};return d(()=>u(e),e=>{i&&a&&t.instance.updateElementOptions(i,{...e,callback:m})},{deep:!0,flush:`post`}),o(()=>{g()}),{...l(c(r)),elementRef:_}},m=e=>{let i=r(()=>u(e)),l=[],p=s([]),m=(e,n)=>{let r=i.value[n];if(!r)return;let o=a(t.instance.register({...r,element:e.element,callback:e=>i.value[n]?.callback(e)}));e.result=o,Object.assign(e.state,o.getSnapshot()),e.unsubscribe=o.subscribe(()=>{e.result&&Object.assign(e.state,e.result.getSnapshot())})},h=e=>{e.unsubscribe?.(),e.unsubscribe=null,e.result?.unregister(),e.result=null,Object.assign(e.state,n(!1))},g=e=>({element:null,result:null,unsubscribe:null,state:s({...n(!1),elementRef:t=>{let n=f(t)??null,r=l[e];!r||r.element===n||(r.result&&h(r),r.element=n,n&&m(r,e))}})});return d(i,e=>{for(;l.length>e.length;){let e=l.pop();p.pop(),e.result&&h(e)}for(let n=0;n<Math.min(l.length,e.length);n++){let r=l[n];r.element&&r.result&&t.instance.updateElementOptions(r.element,{...e[n],callback:e=>i.value[n]?.callback(e)})}let n=l.length;for(let t=n;t<e.length;t++){let e=g(t);l.push(e),p.push(c(e.state))}},{deep:!0,immediate:!0}),o(()=>{for(let e of l)e.result&&h(e);l.length=0,p.length=0}),p},h=(e,n)=>{let r=null,a=i(n)?()=>n.value:()=>n,s=e=>{r?.abort(),r=new AbortController,t.instance.addEventListener(e,e=>a()(e),{signal:r.signal})};d(()=>u(e),e=>s(e),{immediate:!0}),o(()=>{r?.abort(),r=null})},g=new WeakMap,_=e=>typeof e==`function`,v=e=>_(e)?{callback:e}:e,y=(e,n)=>{g.set(e,t.instance.register({element:e,...n}))},b=e=>{g.get(e)?.unregister(),g.delete(e)},x={mounted(e,t){y(e,v(t.value))},updated(e,n){n.value!==n.oldValue&&t.instance.updateElementOptions(e,v(n.value))},unmounted(e){b(e)}};export{e as ForesightManager,p as useForesight,h as useForesightEvent,m as useForesights,x as vForesight};
2
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":["ForesightManager","ForesightManager","ForesightManager"],"sources":["../src/utils/resolveElement.ts","../src/composables/useForesight.ts","../src/composables/useForesights.ts","../src/composables/useForesightEvent.ts","../src/directives/vForesight.ts"],"sourcesContent":["import type { ComponentPublicInstance } from \"vue\"\nimport type { MaybeElement, ResolvedElement } from \"../types\"\n\n/**\n * Resolves a MaybeElement to a raw DOM Element or null.\n * Handles ComponentPublicInstance by extracting $el.\n * Filters out comment nodes (components that render nothing).\n */\nexport const resolveElement = <T extends MaybeElement>(target: T): ResolvedElement<T> | null => {\n if (!target) {\n return null\n }\n\n if (target instanceof Element) {\n return target as ResolvedElement<T>\n }\n\n const el = (target as ComponentPublicInstance).$el\n // Filter comment nodes - a component with v-if=\"false\" or empty template\n // leaves a #comment placeholder that has no size or position.\n if (el instanceof Node && el.nodeType === Node.COMMENT_NODE) {\n return null\n }\n\n return (el ?? null) as ResolvedElement<T> | null\n}\n","import {\n reactive,\n readonly,\n toRefs,\n toValue,\n onScopeDispose,\n watch,\n type MaybeRefOrGetter,\n} from \"vue\"\nimport {\n ForesightManager,\n createUnregisteredSnapshot,\n type ForesightElementState,\n type ForesightRegisterResult,\n} from \"js.foresight\"\nimport type { MaybeElement, UseForesightOptions, UseForesightReturn } from \"../types\"\nimport { resolveElement } from \"../utils/resolveElement\"\n\n/**\n * Registers a single element with ForesightManager.\n *\n * @param options - Registration options as a plain object, ref, or getter.\n *\n * Returns reactive refs for all element state (`isPredicted`, `hitCount`, etc.)\n * plus an `elementRef` function to bind the target element.\n *\n * @example\n * ```ts\n * const { isPredicted, elementRef } = useForesight({\n * callback: () => prefetch('/about'),\n * name: 'about-link',\n * })\n * ```\n * ```vue\n * <a :ref=\"elementRef\" href=\"/about\">About</a>\n * ```\n */\nexport const useForesight = (\n options: MaybeRefOrGetter<UseForesightOptions>\n): UseForesightReturn => {\n const state = reactive(createUnregisteredSnapshot(false))\n\n let currentElement: Element | null = null\n let registerResults: ForesightRegisterResult | null = null\n let unsubscribe: (() => void) | null = null\n\n const callback = (s: ForesightElementState) => toValue(options).callback(s)\n\n const registerElement = (element: Element, registerOptions: UseForesightOptions) => {\n registerResults = ForesightManager.instance.register({\n ...registerOptions,\n element,\n callback,\n })\n\n Object.assign(state, registerResults.getSnapshot())\n unsubscribe = registerResults.subscribe(() => {\n if (registerResults) {\n Object.assign(state, registerResults.getSnapshot())\n }\n })\n }\n\n const unregisterElement = () => {\n unsubscribe?.()\n unsubscribe = null\n registerResults?.unregister()\n registerResults = null\n Object.assign(state, createUnregisteredSnapshot(false))\n }\n\n const elementRef = (el: MaybeElement) => {\n const resolved = resolveElement(el) ?? null\n\n if (resolved === currentElement) {\n return\n }\n\n // Tear down the old registration before swapping the element.\n if (currentElement && registerResults) {\n unregisterElement()\n }\n\n currentElement = resolved\n if (resolved) {\n registerElement(resolved, toValue(options))\n }\n }\n\n // Patch options (incl. enabled) on change. Deep so in-place mutations of a\n // ref/reactive options object fire too; no same-ref guard — on in-place\n // mutation new and old are the same object, so the manager's internal\n // diffing is the only correct dedupe.\n watch(\n () => toValue(options),\n newOptions => {\n if (currentElement && registerResults) {\n ForesightManager.instance.updateElementOptions(currentElement, { ...newOptions, callback })\n }\n },\n { deep: true, flush: \"post\" }\n )\n\n onScopeDispose(() => {\n unregisterElement()\n })\n\n return { ...toRefs(readonly(state)), elementRef }\n}\n","import {\n computed,\n markRaw,\n reactive,\n readonly,\n toValue,\n watch,\n onScopeDispose,\n type MaybeRefOrGetter,\n} from \"vue\"\nimport {\n ForesightManager,\n createUnregisteredSnapshot,\n type ForesightElementState,\n type ForesightRegisterResult,\n} from \"js.foresight\"\nimport { resolveElement } from \"../utils/resolveElement\"\nimport type { MaybeElement, UseForesightOptions } from \"../types\"\n\nexport type UseForesightSlot = Readonly<ForesightElementState> & {\n /** Template ref function - bind to an element with `:ref=\"slot.elementRef\"`. */\n elementRef: (el: MaybeElement) => void\n}\n\ntype Slot = {\n element: Element | null\n result: ForesightRegisterResult | null\n unsubscribe: (() => void) | null\n state: ForesightElementState & { elementRef: (el: MaybeElement) => void }\n}\n\n/**\n * Registers multiple elements with ForesightManager from a single composable.\n *\n * @param options - Array of registration options (plain array, ref, or getter).\n * The array length determines the number of slots.\n *\n * Returns a reactive array of `UseForesightSlot` objects. Each slot contains:\n * - `elementRef` - a template ref function to bind an element (`:ref=\"slot.elementRef\"`)\n * - All `ForesightElementState` properties (`isPredicted`, `hitCount`, etc.)\n *\n * @example\n * ```ts\n * const items = ref([{ name: 'a' }, { name: 'b' }])\n *\n * const slots = useForesights(() =>\n * items.value.map(item => ({\n * callback: () => prefetch(item.name),\n * name: item.name,\n * }))\n * )\n * ```\n * ```vue\n * <button v-for=\"(item, i) in items\" :ref=\"slots[i].elementRef\">\n * {{ slots[i].isPredicted ? 'predicted!' : item.name }}\n * </button>\n * ```\n */\nexport const useForesights = (\n options: MaybeRefOrGetter<UseForesightOptions[]>\n): UseForesightSlot[] => {\n const resolvedOptions = computed(() => toValue(options))\n const managed: Slot[] = []\n const slots: UseForesightSlot[] = reactive([])\n\n const register = (slot: Slot, index: number) => {\n const slotOptions = resolvedOptions.value[index]\n if (!slotOptions) {\n return\n }\n\n const result = markRaw(\n ForesightManager.instance.register({\n ...slotOptions,\n element: slot.element!,\n callback: (state: ForesightElementState) => resolvedOptions.value[index]?.callback(state),\n })\n )\n\n slot.result = result\n Object.assign(slot.state, result.getSnapshot())\n\n slot.unsubscribe = result.subscribe(() => {\n if (slot.result) {\n Object.assign(slot.state, slot.result.getSnapshot())\n }\n })\n }\n\n const unregister = (slot: Slot) => {\n slot.unsubscribe?.()\n slot.unsubscribe = null\n slot.result?.unregister()\n slot.result = null\n Object.assign(slot.state, createUnregisteredSnapshot(false))\n }\n\n const createSlot = (index: number): Slot => {\n const state = reactive({\n ...createUnregisteredSnapshot(false),\n // `elementRef` owns unregistering when the element detaches or swaps.\n elementRef: (el: MaybeElement) => {\n const resolved = resolveElement(el) ?? null\n const slot = managed[index]\n if (!slot || slot.element === resolved) {\n return\n }\n\n if (slot.result) {\n unregister(slot)\n }\n\n slot.element = resolved\n if (resolved) {\n register(slot, index)\n }\n },\n }) as Slot[\"state\"]\n\n return { element: null, result: null, unsubscribe: null, state }\n }\n\n // Single watch handles both length changes and option updates. Deep so\n // in-place mutations of a ref/reactive options array fire too.\n watch(\n resolvedOptions,\n newOptions => {\n // Shrink\n while (managed.length > newOptions.length) {\n const removed = managed.pop()!\n slots.pop()\n if (removed.result) {\n unregister(removed)\n }\n }\n\n // Patch every surviving slot. On in-place mutation new and old options\n // are the same objects, so there is nothing to diff here — the manager's\n // updateElementOptions no-ops internally when values are unchanged.\n for (let i = 0; i < Math.min(managed.length, newOptions.length); i++) {\n const slot = managed[i]\n if (slot.element && slot.result) {\n ForesightManager.instance.updateElementOptions(slot.element, {\n ...newOptions[i],\n callback: (state: ForesightElementState) => resolvedOptions.value[i]?.callback(state),\n })\n }\n }\n\n // Grow\n const previousLength = managed.length\n for (let i = previousLength; i < newOptions.length; i++) {\n const slot = createSlot(i)\n managed.push(slot)\n slots.push(readonly(slot.state) as UseForesightSlot)\n }\n },\n { deep: true, immediate: true }\n )\n\n onScopeDispose(() => {\n for (const slot of managed) {\n if (slot.result) {\n unregister(slot)\n }\n }\n managed.length = 0\n slots.length = 0\n })\n\n return slots\n}\n","import { watch, toValue, onScopeDispose, isRef, type MaybeRef, type MaybeRefOrGetter } from \"vue\"\nimport { ForesightManager, type ForesightEvent, type ForesightEventMap } from \"js.foresight\"\n\ntype ListenerArg<K extends ForesightEvent> = MaybeRef<(event: ForesightEventMap[K]) => void>\n\n/**\n * Subscribes to a ForesightManager event for the lifetime of the calling scope.\n *\n * The listener is always invoked with its latest reference - no stale closures\n * when passed as a `ref()`. Changing `eventType` automatically tears down the\n * previous subscription and creates a new one; changing only the `listener`\n * does not re-subscribe.\n */\nexport const useForesightEvent = <K extends ForesightEvent>(\n eventType: MaybeRefOrGetter<K>,\n listener: ListenerArg<K>\n): void => {\n let controller: AbortController | null = null\n\n const resolveListener = isRef(listener) ? () => listener.value : () => listener\n\n const subscribe = (type: K) => {\n controller?.abort()\n controller = new AbortController()\n\n const stableListener = (event: ForesightEventMap[K]) => resolveListener()(event)\n\n ForesightManager.instance.addEventListener(type, stableListener, {\n signal: controller.signal,\n })\n }\n\n watch(\n () => toValue(eventType),\n newType => subscribe(newType),\n { immediate: true }\n )\n\n onScopeDispose(() => {\n controller?.abort()\n controller = null\n })\n}\n","import type { ObjectDirective } from \"vue\"\nimport { ForesightManager, type ForesightRegisterResult } from \"js.foresight\"\nimport type { UseForesightOptions } from \"../types\"\n\n/** Shorthand: pass just the callback instead of a full options object. */\ntype CallbackShorthand = () => void\n\ntype ForesightDirectiveValue = UseForesightOptions | CallbackShorthand\n\ntype ForesightDirectiveElement = HTMLElement | SVGElement\n\nconst resultMap = new WeakMap<ForesightDirectiveElement, ForesightRegisterResult>()\n\nconst isCallbackShorthand = (value: ForesightDirectiveValue): value is CallbackShorthand =>\n typeof value === \"function\"\n\nconst resolveOptions = (value: ForesightDirectiveValue): UseForesightOptions =>\n isCallbackShorthand(value) ? { callback: value } : value\n\nconst register = (element: ForesightDirectiveElement, options: UseForesightOptions) => {\n resultMap.set(element, ForesightManager.instance.register({ element, ...options }))\n}\n\nconst unregister = (element: ForesightDirectiveElement) => {\n resultMap.get(element)?.unregister()\n resultMap.delete(element)\n}\n\nexport const vForesight: ObjectDirective<ForesightDirectiveElement, ForesightDirectiveValue> = {\n mounted(element, binding) {\n register(element, resolveOptions(binding.value))\n },\n\n // Patch options (incl. enabled) on change without tearing down.\n updated(element, binding) {\n if (binding.value === binding.oldValue) {\n return\n }\n\n ForesightManager.instance.updateElementOptions(element, resolveOptions(binding.value))\n },\n\n unmounted(element) {\n unregister(element)\n },\n}\n"],"mappings":"iPAQA,MAAa,EAA0C,GAAyC,CAC9F,GAAI,CAAC,EACH,OAAO,KAGT,GAAI,aAAkB,QACpB,OAAO,EAGT,IAAM,EAAM,EAAmC,IAO/C,OAJI,aAAc,MAAQ,EAAG,WAAa,KAAK,aACtC,KAGD,GAAM,MCaH,EACX,GACuB,CACvB,IAAM,EAAQ,EAAS,EAA2B,GAAM,CAAC,CAErD,EAAiC,KACjC,EAAkD,KAClD,EAAmC,KAEjC,EAAY,GAA6B,EAAQ,EAAQ,CAAC,SAAS,EAAE,CAErE,GAAmB,EAAkB,IAAyC,CAClF,EAAkBA,EAAiB,SAAS,SAAS,CACnD,GAAG,EACH,UACA,WACD,CAAC,CAEF,OAAO,OAAO,EAAO,EAAgB,aAAa,CAAC,CACnD,EAAc,EAAgB,cAAgB,CACxC,GACF,OAAO,OAAO,EAAO,EAAgB,aAAa,CAAC,EAErD,EAGE,MAA0B,CAC9B,KAAe,CACf,EAAc,KACd,GAAiB,YAAY,CAC7B,EAAkB,KAClB,OAAO,OAAO,EAAO,EAA2B,GAAM,CAAC,EAGnD,EAAc,GAAqB,CACvC,IAAM,EAAW,EAAe,EAAG,EAAI,KAEnC,IAAa,IAKb,GAAkB,GACpB,GAAmB,CAGrB,EAAiB,EACb,GACF,EAAgB,EAAU,EAAQ,EAAQ,CAAC,GAsB/C,OAdA,MACQ,EAAQ,EAAQ,CACtB,GAAc,CACR,GAAkB,GACpB,EAAiB,SAAS,qBAAqB,EAAgB,CAAE,GAAG,EAAY,WAAU,CAAC,EAG/F,CAAE,KAAM,GAAM,MAAO,OAAQ,CAC9B,CAED,MAAqB,CACnB,GAAmB,EACnB,CAEK,CAAE,GAAG,EAAO,EAAS,EAAM,CAAC,CAAE,aAAY,ECjDtC,EACX,GACuB,CACvB,IAAM,EAAkB,MAAe,EAAQ,EAAQ,CAAC,CAClD,E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B,SAAS,qBAAqB,EAAS,EAAe,EAAQ,MAAM,CAAC,EAGxF,UAAU,EAAS,CACjB,EAAW,EAAQ,EAEtB"}
package/package.json ADDED
@@ -0,0 +1,67 @@
1
+ {
2
+ "name": "@foresightjs/vue",
3
+ "version": "0.1.0",
4
+ "description": "Vue composables for ForesightJS - register elements with the ForesightManager from Vue components.",
5
+ "type": "module",
6
+ "sideEffects": false,
7
+ "main": "./dist/index.mjs",
8
+ "module": "./dist/index.mjs",
9
+ "types": "./dist/index.d.mts",
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.mts",
13
+ "default": "./dist/index.mjs"
14
+ }
15
+ },
16
+ "homepage": "https://foresightjs.com/",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "git+https://github.com/spaansba/ForesightJS",
20
+ "directory": "packages/foresightjs-vue"
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "files": [
26
+ "dist",
27
+ "README.md",
28
+ "LICENSE"
29
+ ],
30
+ "keywords": [
31
+ "vue",
32
+ "foresight",
33
+ "js.foresight",
34
+ "foresightjs",
35
+ "vue-composable",
36
+ "prefetch",
37
+ "interaction-prediction",
38
+ "mouse-trajectory",
39
+ "useForesight"
40
+ ],
41
+ "author": "Bart Spaans",
42
+ "license": "MIT",
43
+ "llms": "https://foresightjs.com/llms.txt",
44
+ "llmsFull": "https://foresightjs.com/llms-full.txt",
45
+ "peerDependencies": {
46
+ "js.foresight": "^4.0.0",
47
+ "vue": "^3.5.0"
48
+ },
49
+ "devDependencies": {
50
+ "@vue/test-utils": "^2.4.6",
51
+ "jsdom": "^29.0.1",
52
+ "tsdown": "^0.21.7",
53
+ "typescript": "^6.0.2",
54
+ "vitest": "^4.1.2",
55
+ "vue": "^3.5.17",
56
+ "js.foresight": "4.0.0"
57
+ },
58
+ "scripts": {
59
+ "build": "tsdown --sourcemap",
60
+ "build:prod": "tsdown",
61
+ "dev": "tsdown --sourcemap --watch",
62
+ "lint": "eslint . --fix",
63
+ "test": "vitest",
64
+ "test:run": "vitest run",
65
+ "test:watch": "vitest --watch"
66
+ }
67
+ }