# @hsfx/attr

Auto-initializing JavaScript library for Webflow sites with animations, accessibility, and utility functions.

---

## Installation

### Standard Installation

```html
<script type="module" src="https://cdn.jsdelivr.net/npm/@hsfx/attr@2/dist/main.js"></script>
<script>!function(){history.scrollRestoration='manual';let e=[];window.hsfx||(window.hsfx={ready:t=>e.push(t)});!function t(){window.hsfx.loaded?e.forEach(e=>{try{e()}catch{}}):window.hsfx.ready&&Array.isArray(window.hsfx)?e.forEach(e=>window.hsfx.ready(e)):setTimeout(t,50)}()}()</script>
```

### Next.js Installation

```tsx
<Script src="https://cdn.jsdelivr.net/npm/@hsfx/attr@2/dist/main.js" strategy="afterInteractive" data-hs-wf-off />
<script dangerouslySetInnerHTML={{ __html: `!function(){history.scrollRestoration='manual';let e=[];window.hsfx||(window.hsfx={ready:t=>e.push(t)});!function t(){window.hsfx.loaded?e.forEach(e=>{try{e()}catch{}}):window.hsfx.ready&&Array.isArray(window.hsfx)?e.forEach(e=>window.hsfx.ready(e)):setTimeout(t,50)}()}()` }} />
```

### Local Development

```html
<!-- Local testing (run: npm run dev) -->
<script type="module" src="http://localhost:5173/index.ts"></script>
<script>!function(){history.scrollRestoration='manual';let e=[];window.hsfx||(window.hsfx={ready:t=>e.push(t)});!function t(){window.hsfx.loaded?e.forEach(e=>{try{e()}catch{}}):window.hsfx.ready&&Array.isArray(window.hsfx)?e.forEach(e=>window.hsfx.ready(e)):setTimeout(t,50)}()}()</script>
```

### Inline Helper Script

The inline script ensures `window.hsfx` is available for external scripts:

```html
<script>!function(){history.scrollRestoration='manual';let e=[];window.hsfx||(window.hsfx={ready:t=>e.push(t)});!function t(){window.hsfx.loaded?e.forEach(e=>{try{e()}catch{}}):window.hsfx.ready&&Array.isArray(window.hsfx)?e.forEach(e=>window.hsfx.ready(e)):setTimeout(t,50)}()}()</script>
```

**What it does:**
- Creates a temporary `window.hsfx.ready()` shim immediately
- Queues callbacks from external scripts before hsfx loads
- Polls for real hsfx to load
- Flushes queued callbacks to real hsfx when ready
- Guarantees external scripts can use `window.hsfx.ready()` safely

### SPA Mode

**For Barba.js, Swup, etc.:** Add `data-hs-spa="true"` to the module loader

```html
<script type="module" src="https://cdn.jsdelivr.net/npm/@hsfx/attr@2/dist/main.js" data-hs-spa="true"></script>
<script>!function(){history.scrollRestoration='manual';let e=[];window.hsfx||(window.hsfx={ready:t=>e.push(t)});!function t(){window.hsfx.loaded?e.forEach(e=>{try{e()}catch{}}):window.hsfx.ready&&Array.isArray(window.hsfx)?e.forEach(e=>window.hsfx.ready(e)):setTimeout(t,50)}()}()</script>
```

## Configuration

```javascript
// Example: Barba.js integration
barba.hooks.before(() => {
  window.dispatchEvent(new CustomEvent('hsfx:transition-exit'));
});

barba.hooks.after(() => {
  window.dispatchEvent(new CustomEvent('hsfx:transition-enter'));
});
```

---

## API Usage

### External Script Integration

When using external scripts & libraries (Barba.js, GSAP ScrollTrigger, etc.) that need to wait for hsfx to be ready, the inline helper script (included with standard installation) ensures `window.hsfx` is available.

**External scripts should use the callback pattern:**

```html
<script>
window.hsfx.ready(() => {
  // Your code here - guaranteed to run when hsfx is fully loaded
});
</script>
```

**Why this works:**

The inline helper script creates a temporary `window.hsfx.ready()` shim immediately, so external scripts can safely call it even before the real hsfx library loads. Callbacks are queued and then flushed to the real hsfx when initialization completes.

### Refreshing After Dynamic Content

When injecting new DOM elements after hsfx has initialized (e.g., CMS-driven mockups, dynamic content loaders), use `refresh()` to reinitialize all attribute handlers on the new elements. This re-dupes elements, restarts marquee animations, and re-wires interactive modules — without breaking form state or replaying page transitions.

**Full flow for dynamic content with clickable buttons/links, marquees, and duped elements:**

```javascript
// 1. Restore removed button/link pairs (clickable normalization removed one)
window.hsfx.modules.normalize.clickable.destroy();

// 2. Remove existing dupe clones
window.hsfx.modules.normalize.dupe.destroy();

// 3. Inject your dynamic content (templates now have full button+link structure)
await populateMockup(cmsData);

// 4. Refresh everything (re-dupe → re-clickable → re-enrich → re-marquee → restart all safe modules)
await window.hsfx.refresh();
```

**Simple flow (no dupe/marquee, just new accordions/tabs/etc.):**

```javascript
// Inject new content, then refresh
await window.hsfx.refresh();

// Or refresh specific modules only
await window.hsfx.refresh(['tabs', 'accordion']);
```

**Event-based (for external scripts):**

```javascript
window.dispatchEvent(new CustomEvent('hsfx:refresh'));

// With specific modules
window.dispatchEvent(new CustomEvent('hsfx:refresh', {
  detail: { modules: ['tabs', 'accordion'] }
}));
```

**What `refresh()` does internally (in order):**

1. Re-runs dupe (idempotent — destroys existing clones first, then re-scans)
2. Re-runs clickable normalization (re-evaluates button/link pairs based on new hrefs)
3. Re-runs enrich (injects hidden attribution inputs into any new forms, skips already-enriched)
4. Restarts marquee animation (destroys old GSAP timelines, re-initializes with new content)
5. Restarts all safe default modules (accordion, tabs, navbar, etc.)

Pages without dupe, clickable, enrich, or marquee skip those steps automatically.

**Safe modules** (restarted by default): `smooth-scroll`, `navbar`, `accordion`, `toc`, `pagination`, `comparison`, `tabs`, `modal`, `link-prefetch`, `active-link`, `lightbox`, `slider`, `theme-animator`

**Excluded by default**: `form` (stateful — persist data, custom selects, validation state would be lost). Pass `'form'` explicitly to include it: `window.hsfx.refresh(['form', 'tabs'])`

### Enrich — Session Attribution

Automatically captures session and attribution data on every page load and injects it as hidden inputs into forms marked with `data-hs-enrich="form"`. Zero external dependencies — uses localStorage and native browser APIs only.

**What gets captured (localStorage, first-touch preserved):**
- UTM params (`utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`)
- External referrer (`document.referrer`, skips same-hostname)
- Landing page URL (first visit only)
- Page count (incremented each page load)
- Session start timestamp (first visit only)

**What gets injected as hidden inputs:**

| Field | Source |
|-------|--------|
| `_utmSource` | localStorage |
| `_utmMedium` | localStorage |
| `_utmCampaign` | localStorage |
| `_utmTerm` | localStorage |
| `_utmContent` | localStorage |
| `_referrer` | localStorage |
| `_landingPage` | localStorage |
| `_sessionPages` | localStorage |
| `_sessionDuration` | Calculated at inject time (seconds since session start) |
| `_timezone` | `Intl.DateTimeFormat().resolvedOptions().timeZone` |
| `_screenSize` | `window.screen.width x window.screen.height` |
| `_timeToComplete` | Seconds between first field focus and form submit |

All field names use the `_` prefix so downstream systems (n8n, email templates) can filter them from visible lead data using `!key.startsWith('_')`.

**Usage:**

```html
<form data-hs-enrich="form">
  <!-- your form fields -->
  <!-- hidden inputs injected automatically on init -->
</form>
```

Data capture runs on every page (even without forms) so attribution is ready when a form eventually appears. Forms created dynamically are enriched automatically via `refresh()`.

### Cleanup

```javascript
// Destroy all modules (useful for SPA navigation)
window.hsfx.destroy();

// Reinitialize everything (full teardown — use refresh() instead for dynamic content)
await window.hsfx.reinitialize();
```

---

### Manual Module Loading

```javascript
// Load a single module
window.hsfx.load('counter');

// With callback
window.hsfx.push([
  'counter',
  () => {
    console.log('Counter module ready');
  },
]);
```

### Lifecycle Hooks

```javascript
// Execute code after all modules load
window.hsfx.ready(() => {
  console.log('Library fully initialized');
});

// Check module status
const status = window.hsfx.status('counter');
console.log(status); // { loaded: true, loading: false }
```

### Modal Manager & Lenis Integration

Modal manager automatically detects and handles Lenis smooth scroll (stops on modal open, starts on close).

```javascript
// Auto-detection works with zero config
// Just use modals normally - Lenis is handled automatically

// Disable auto Lenis handling if needed
window.hsfx.modal.setLenisEnabled(false);

// Manual modal control
window.hsfx.modal.open();
window.hsfx.modal.close();

// Custom callbacks (run in addition to auto Lenis handling)
window.hsfx.modal.onOpen(() => {
  console.log('Modal opened');
});

window.hsfx.modal.onClose(() => {
  console.log('Modal closed');
});
```

---

## jsDelivr Cache Purge

After publishing to npm, go to https://www.jsdelivr.com/tools/purge and paste:

```
https://cdn.jsdelivr.net/npm/@hsfx/attr@2
```

---

## Architecture

- **TypeScript:** Full type safety with TypeScript source
- **Vite Bundled:** Optimized build with code splitting (~24kb gzipped total)
- **Config-driven:** Centralized configuration in `config.json`
- **SPA Compatible:** Works with Barba.js, Swup, and other routers
- **Memory Safe:** Proper cleanup tracking for observers and event handlers
- **Phase-based Loading:** Optimized initialization sequence
