$ show serkanyersen/ifvisible.js
ifvisible.js is a modern, dependency-free browser library that provides a clean, event-driven API for detecting page visibility and user activity. It wraps the standard Page Visibility API to surface focus/blur events, and adds an idle-detection system that fires `idle`/`wakeup` events after a configurable period of user inactivity (mouse, keyboard, touch, scroll). Version 3 is a complete rewrite in TypeScript with per-instance event isolation, SSR-safe construction (no DOM access at import time), and support for the Page Lifecycle API (`freeze`/`resume` for bfcache). The library ships as an ESM module, CommonJS, and an IIFE global, with bundled type definitions. It is designed for use in any client-side JavaScript projectβSPA frameworks, traditional websites, or even server-side rendering environments (where it becomes a safe no-op). The architecture is simple: a single `IfVisible` class holds an internal `EventEmitter` and a `Timer` class for smart intervals that auto-pause when the user is idle. The codebase is well-structured, thoroughly tested (including an SSR test), and follows modern best practices. It is not a data research project; it is a reusable application library.
The LLM identified 2 files worth highlighting for reuse:
A minimal, self-contained event emitter implemented with a Map of Sets. It isolates events per instance, solving a known v2 bug where multiple IfVisible instances shared a global event store. The `fire` method clones listeners before iterating to avoid mutation during iteration. This component could be extracted and reused as a generic event emitter in any TypeScript project with minimal modification.
A timer class that automatically pauses and resumes based on the user's visibility and idle status. It listens to `statusChanged` events on the parent IfVisible instance: when the status is `active` the interval runs; otherwise it pauses. A `stopped` flag allows permanent cessation via `stop()`. This pattern is reusable for any scenario needing lifecycle-aware intervals (e.g., polling, animations). The class depends only on the IfVisible interface (for event subscription) and could be adapted to other event sources.