feat(SW-3644): Storybook v10 * Auto update to Storybook v10 * Add scandic theme and logo * Update yarn.lock * Update formatting of package.json * Update vitest config and playwright plugin * Remove vitest 4 update * Re-added comment * Update the Typography component to explicitly return React.ReactNode * Add an explicit type assertion to the export * Add an explicit type assertion to the export for Checkbox * Explicit return type assertion * Add an explicit type assertion to the export * Update @types/react and fix ts warnings * Updated typings Approved-by: Linus Flood Approved-by: Matilda Landström
79 lines
2.0 KiB
TypeScript
79 lines
2.0 KiB
TypeScript
"use client"
|
|
|
|
import { useCallback, useEffect, useRef, useState } from "react"
|
|
import {
|
|
type Control,
|
|
type FieldValues,
|
|
useFormState,
|
|
type UseFormSubscribe,
|
|
} from "react-hook-form"
|
|
|
|
import {
|
|
type FormType,
|
|
trackFormAbandonment,
|
|
trackFormCompletion,
|
|
trackFormInputStarted,
|
|
} from "./form"
|
|
|
|
export function useFormTracking<T extends FieldValues>(
|
|
formType: FormType,
|
|
subscribe: UseFormSubscribe<T>,
|
|
control: Control<T>,
|
|
nameSuffix: string = ""
|
|
) {
|
|
const [formStarted, setFormStarted] = useState(false)
|
|
const lastAccessedField = useRef<string | undefined>(undefined)
|
|
const formState = useFormState({ control })
|
|
|
|
useEffect(() => {
|
|
const unsubscribe = subscribe({
|
|
formState: { dirtyFields: true },
|
|
callback: (data) => {
|
|
if ("name" in data) {
|
|
lastAccessedField.current = data.name as string
|
|
}
|
|
|
|
if (!formStarted) {
|
|
trackFormInputStarted(formType, nameSuffix)
|
|
setFormStarted(true)
|
|
}
|
|
},
|
|
})
|
|
return () => unsubscribe()
|
|
}, [subscribe, formType, nameSuffix, formStarted])
|
|
|
|
useEffect(() => {
|
|
if (!formStarted || !lastAccessedField.current || formState.isValid) return
|
|
|
|
const lastField = lastAccessedField.current
|
|
|
|
function handleBeforeUnload() {
|
|
trackFormAbandonment(formType, lastField, nameSuffix)
|
|
}
|
|
|
|
function handleVisibilityChange() {
|
|
if (document.visibilityState === "hidden") {
|
|
trackFormAbandonment(formType, lastField, nameSuffix)
|
|
}
|
|
}
|
|
|
|
window.addEventListener("beforeunload", handleBeforeUnload)
|
|
window.addEventListener("visibilitychange", handleVisibilityChange)
|
|
|
|
return () => {
|
|
window.removeEventListener("beforeunload", handleBeforeUnload)
|
|
window.removeEventListener("visibilitychange", handleVisibilityChange)
|
|
}
|
|
}, [formStarted, formType, nameSuffix, formState.isValid])
|
|
|
|
const trackFormSubmit = useCallback(() => {
|
|
if (formState.isValid) {
|
|
trackFormCompletion(formType, nameSuffix)
|
|
}
|
|
}, [formType, nameSuffix, formState.isValid])
|
|
|
|
return {
|
|
trackFormSubmit,
|
|
}
|
|
}
|