# Sync Scroll Module

A React module for synchronizing scroll positions between multiple components with master-slave-drag relationships.

## Features

- 🔄 **Master-Slave Architecture** - Masters control slaves, slaves can't control masters
- 🎯 **Drag Role** - Special role for drag-based scroll controls
- ⚡ **High performance** - Uses requestAnimationFrame for smooth syncing
- 🎮 **Full control** - Enable/disable syncing dynamically
- 📦 **TypeScript support** - Fully typed for excellent DX
- 🧹 **Auto cleanup** - Proper cleanup on unmount

## Quick Start

### Basic Example

```tsx
import { SyncScrollProvider, useSyncScroll } from "@/components/waterfall/SyncScroll";

function App() {
  return (
    <SyncScrollProvider>
      <MasterPanel />
      <SlavePanel />
    </SyncScrollProvider>
  );
}

function MasterPanel() {
  const scrollRef = useSyncScroll({
    id: "master",
    role: "master", // Controls all panels
  });

  return (
    <div ref={scrollRef} className="h-96 overflow-y-auto">
      {/* Content */}
    </div>
  );
}

function SlavePanel() {
  const scrollRef = useSyncScroll({
    id: "slave",
    role: "slave", // Controlled by master
  });

  return (
    <div ref={scrollRef} className="h-96 overflow-y-auto">
      {/* Content */}
    </div>
  );
}
```

### Complete Example with Drag Control

```tsx
"use client";

import React from "react";
import { SyncScrollProvider, useSyncScroll, ScrollRole } from "@/components/waterfall/SyncScroll";

// Scrollable panel component
function Panel({
  id,
  title,
  color,
  role = "slave",
  isDraggable = false,
}: {
  id: string;
  title: string;
  color: string;
  role?: ScrollRole;
  isDraggable?: boolean;
}) {
  const scrollRef = useSyncScroll({ id, role });
  const [isDragging, setIsDragging] = React.useState(false);
  const dragStartY = React.useRef(0);
  const scrollStartTop = React.useRef(0);

  const handleMouseDown = (e: React.MouseEvent) => {
    if (!isDraggable || !scrollRef.current) return;

    setIsDragging(true);
    dragStartY.current = e.clientY;
    scrollStartTop.current = scrollRef.current.scrollTop;
    e.preventDefault();
  };

  React.useEffect(() => {
    if (!isDraggable) return;

    const handleMouseMove = (e: MouseEvent) => {
      if (!isDragging || !scrollRef.current) return;

      const deltaY = e.clientY - dragStartY.current;
      scrollRef.current.scrollTop = scrollStartTop.current - deltaY * 2;
    };

    const handleMouseUp = () => {
      setIsDragging(false);
    };

    if (isDragging) {
      document.addEventListener("mousemove", handleMouseMove);
      document.addEventListener("mouseup", handleMouseUp);

      return () => {
        document.removeEventListener("mousemove", handleMouseMove);
        document.removeEventListener("mouseup", handleMouseUp);
      };
    }
  }, [isDragging, isDraggable, scrollRef]);

  return (
    <div className="h-96 overflow-hidden rounded-lg border">
      <div className={`p-3 font-semibold ${color} flex justify-between text-white`}>
        <span>{title}</span>
        <span className="rounded bg-black/20 px-2 py-1 text-xs">{role.toUpperCase()}</span>
      </div>
      <div
        ref={scrollRef}
        className={`h-full overflow-y-auto p-4 ${isDraggable ? "cursor-grab active:cursor-grabbing" : ""}`}
        onMouseDown={handleMouseDown}
        style={{ userSelect: isDragging ? "none" : "auto" }}
      >
        {isDraggable && (
          <div className="mb-4 rounded bg-yellow-100 p-2 text-sm dark:bg-yellow-900">
            🖱️ Click and drag to scroll all panels
          </div>
        )}
        {Array.from({ length: 50 }, (_, i) => (
          <div key={i} className="border-b py-3">
            Item {i + 1}
          </div>
        ))}
      </div>
    </div>
  );
}

export default function SyncScrollDemo() {
  return (
    <main className="min-h-screen p-8">
      <div className="mx-auto max-w-6xl space-y-8">
        <h1 className="mb-2 text-center text-3xl font-bold">Master-Slave Sync Scroll Demo</h1>

        <SyncScrollProvider>
          <div className="grid grid-cols-3 gap-4">
            <Panel id="master" title="Master Panel" color="bg-red-500" role="master" />
            <Panel
              id="drag"
              title="Drag Control"
              color="bg-yellow-500"
              role="drag"
              isDraggable={true}
            />
            <Panel id="slave" title="Slave Panel" color="bg-blue-500" role="slave" />
          </div>
        </SyncScrollProvider>
      </div>
    </main>
  );
}
```

## API Reference

### `SyncScrollProvider`

The context provider that manages scroll synchronization.

```tsx
<SyncScrollProvider>{children}</SyncScrollProvider>
```

### `useSyncScroll(options)`

Hook that returns a ref to attach to your scrollable element.

#### Options

| Option    | Type                                   | Default      | Description                                  |
| --------- | -------------------------------------- | ------------ | -------------------------------------------- |
| `id`      | `string`                               | required     | Unique identifier for the scrollable element |
| `role`    | `'master' \| 'slave' \| 'drag'`        | `'slave'`    | Scroll control role (see Roles section)      |
| `enabled` | `boolean`                              | `true`       | Enable/disable scroll syncing                |
| `axis`    | `'vertical' \| 'horizontal' \| 'both'` | `'vertical'` | Axis to synchronize                          |

#### Returns

- `RefObject<HTMLDivElement>` - Ref to attach to your scrollable element

### Scroll Roles

The sync scroll system supports three types of roles:

#### **Master**

- Controls all other elements (masters and slaves)
- Can sync with other masters
- Use case: Main content area that drives the scroll

#### **Slave**

- Controlled by masters
- Can only sync with other slaves (cannot control masters)
- Use case: Secondary panels that follow the main content

#### **Drag**

- Acts like master (controls all elements)
- Designed for drag-based scroll interactions
- Use case: Custom scrollbars or drag handles

#### Role Relationships

| Source → Target | Master | Slave | Drag |
| --------------- | ------ | ----- | ---- |
| **Master →**    | ✅     | ✅    | ✅   |
| **Slave →**     | ❌     | ✅    | ❌   |
| **Drag →**      | ✅     | ✅    | ✅   |

### `useSyncScrollWithRef(ref, options)`

Alternative hook when you already have a ref.

```tsx
const myRef = useRef<HTMLDivElement>(null);
useSyncScrollWithRef(myRef, { id: "sidebar", role: "master" });

return <div ref={myRef}>...</div>;
```

## Use Cases

- **Timeline Components** - Keep timeline and event list synchronized with master-slave control
- **Code Editors** - Line numbers as master, code content as slave
- **Data Tables** - Header as master, scrollable content as slave
- **Documentation** - Navigation as master, content preview as slave
- **Custom Scrollbars** - Drag handle controls multiple panels

## Performance Considerations

- Uses `requestAnimationFrame` for smooth updates
- Prevents circular updates with intelligent tracking
- Passive event listeners for better scroll performance
- Automatic cleanup prevents memory leaks

## Troubleshooting

### Elements not syncing

1. Ensure all elements are wrapped in the same `SyncScrollProvider`
2. Check that each element has a unique `id`
3. Verify `enabled` is `true` (or omitted)
4. Check role relationships - slaves can't control masters

### Jerky scrolling

- This usually happens if elements have different content heights
- Ensure synced elements have similar scroll ranges
- Consider using `transform` instead of scroll for smoother animation

### Memory leaks

- The module automatically cleans up on unmount
- If using `useSyncScrollWithRef`, ensure the ref is stable (not recreated on each render)

## Browser Support

Works in all modern browsers that support:

- React 16.8+ (Hooks)
- `requestAnimationFrame`
- Passive event listeners

## License

Part of the Timeline Waterfall component library.
