import { timestamp } from '@robonen/stdlib'; import { ref, watch, type WatchSource, type WatchOptions, type Ref } from 'vue'; export interface UseLastChangedOptions< Immediate extends boolean, InitialValue extends number | null | undefined = undefined, > extends WatchOptions { initialValue?: InitialValue; } /** * @name useLastChanged * @category State * @description Records the last time a value changed * * @param {WatchSource} source The value to track * @param {UseLastChangedOptions} [options={}] The options for the last changed tracker * @returns {Ref} The timestamp of the last change * * @example * const value = ref(0); * const lastChanged = useLastChanged(value); * * @example * const value = ref(0); * const lastChanged = useLastChanged(value, { immediate: true }); * * @since 0.0.1 */ export function useLastChanged(source: WatchSource, options?: UseLastChangedOptions): Ref; export function useLastChanged(source: WatchSource, options: UseLastChangedOptions | UseLastChangedOptions): Ref export function useLastChanged(source: WatchSource, options: UseLastChangedOptions = {}): Ref | Ref { const lastChanged = ref(options.initialValue ?? null); watch(source, () => lastChanged.value = timestamp(), options); return lastChanged; }