# Clusterflux

Welcome to **Clusterflux**, a lighthearted and modular library of UI components designed to bring fresh, atomic, and well-designed ideas to your applications. Clusterflux provides developers with small, reusable UI elements that are both functional and delightful, allowing you to build innovative user interfaces with ease.

---

## Structure

Clusterflux is organized into several categories of components:

### 1. **Sprockets**
Sprockets are the atomic UI elements in Clusterflux. They are standalone, reusable, and fall into two subcategories:

- **Toots**: Ephemeral UI elements designed for temporary use. These are typically DOM-based (like Floater) and create temporary visual effects that disappear after a short time. They don't require initialization and are used directly through static methods.

- **Nuggets**: Longer-lasting UI components. These are SVG-based and can be used to display information (e.g., indicators, LEDs, tickers) or offer interactivity (e.g., buttons, sliders, knobs). They require proper initialization and instance management.

### 2. **Clusters**
Clusters are supersets, or combinations, of Sprockets. They are containers of **Toots** and **Nuggets**, with an emphasis on **Nuggets**, designed to create common, functional UI widgets like control panels or grouped interface elements.

### 3. **Cogs**
Cogs are the utility functions and shared resources that power Clusterflux components. They provide common functionality like animation handling, state management, and SVG manipulation. However, they are not directly used by the user, but rather by the components themselves. 

---

## Repository Layout
The repository is structured as follows (this is descriptive, not exact):

```
/Clusterflux/
  /sprockets/
    /toots/
      /notification/
        - notification.js
        - notification.svg
        - README.md
    /nuggets/
      /informational/
        /led/
          - led.js
          - led.svg
          - README.md
      /interactive/
        /button/
          - button.js
          - button.svg
          - README.md
  /clusters/
    /control-panel/
      - control-panel.js
      - control-panel.svg
      - README.md
  /cogs/
    /animation/
      - fade.js
      - pulse.js
    /color/
      - color.js         # Color manipulation utilities
      - css-color-names.json
    /utils/
      - svg-loader.js
      - state-manager.js
    /styles/
      - common.css
  /docs/
    - getting-started.md
    - api-reference.md
  README.md
  package.json
```

---

## Getting Started

To get started with Clusterflux:

1. **Install via npm:**
   ```bash
   npm install @clusterflux
   ```

2. **Import and Initialize:**
   ```javascript
   import { initClusterflux } from '@clusterflux';
   await initClusterflux();
   ```

3. **Add Components to HTML:**
   ```html
   <div data-clusterflux="led" id="myLed"></div>
   <div data-clusterflux="radio" id="myRadio"></div>
   ```

4. **Access Component Instances:**
   ```javascript
   const led = document.getElementById('myLed').__clusterflux_instance;
   const radio = document.getElementById('myRadio').__clusterflux_instance;
   ```

---

## Component Types and Initialization

### SVG-based Nuggets
SVG-based components (like LED, Radio, Checkbox) follow these patterns:
1. Use placeholder divs with `data-clusterflux` attributes
2. Load SVGs via fetch for CDN compatibility
3. Store instance on element via `__clusterflux_instance`
4. Support both automatic and manual initialization
5. Extract defaults from SVG metadata
6. Use ES6 module URL resolution for assets
7. Use metadata instead of :root variables for configuration

### DOM-based Nuggets
Some Nuggets (like Dropdown) are DOM-based rather than SVG-based. These components:
1. Use pure DOM elements for better performance with dynamic content
2. Support configuration via constructor options
3. Maintain instance isolation through unique IDs
4. Handle their own cleanup via destroy() method
5. Support both automatic and manual initialization
6. Follow the same instance management patterns as SVG Nuggets
7. Inject their styles programmatically during initialization for complete self-containment
8. Use scoped CSS with unique instance IDs to prevent style leakage
9. Use a two-step initialization pattern (initialize then configure) for better control
10. Support auto-sizing based on content
11. Handle text styling appropriately (e.g., bold for buttons, normal for items)
12. Manage scrolling based on number of items rather than fixed height
13. Support consistent styling inheritance (e.g., border colors)
14. Use subtle visual effects (e.g., brightness-based hover)

Example:
```javascript
// Automatic initialization with data attributes
await initClusterflux();
const dropdown = document.getElementById('myDropdown').__clusterflux_instance;

// Manual initialization with two-step pattern
const dropdown = new DropdownNugget();
dropdown.initialize(container);  // First step: basic initialization
dropdown.configure({            // Second step: configuration
    buttonText: 'Select Option',
    items: ['Item 1', 'Item 2'],
    maxVisibleItems: 5
});
```

### SVG Configuration Pattern
All configurable values should be stored in SVG metadata:
```xml
<metadata>
  <defaults xmlns:component="http://clusterflux.com/component">
    <component:property>value</component:property>
  </defaults>
</metadata>
```

Key points:
- Use lowercase tag names in metadata to avoid browser inconsistencies
- Group related properties logically
- Use clear, descriptive property names
- Include units where appropriate
- Document the purpose of each property
- Keep values simple and atomic
- Implement fallback for case sensitivity in metadata extraction

Example:
```javascript
// Automatic initialization
await initClusterflux();
const led = document.getElementById('myLed').__clusterflux_instance;

// Manual initialization
const led = new Led();
led.initialize(container);
await led.waitForInit();
```

### Component Implementation Guidelines
1. All SVG-based components must:
   - Use fetch for SVG loading
   - Support instance isolation
   - Extract defaults from metadata
   - Use ES6 module URL resolution
   - Support both auto and manual init
   - Store instance on element
   - Avoid :root variables for configuration

2. All DOM-based Nuggets must:
   - Support constructor configuration
   - Handle own cleanup via destroy()
   - Support instance isolation
   - Support both auto and manual init
   - Store instance on element
   - Maintain proper event handling
   - Support proper height management for scrollable content
   - Inject styles programmatically during initialization
   - Use scoped CSS with unique instance IDs
   - Be completely self-contained with no external CSS dependencies
   - Follow two-step initialization pattern (initialize then configure)
   - Support data attribute configuration for automatic initialization

3. All DOM-based Toots must:
   - Use static methods
   - Handle own cleanup
   - Support multiple instances
   - Not require initialization

4. Common requirements:
   - Follow ES6 module standards
   - Support proper error handling
   - Include TypeScript definitions
   - Provide comprehensive documentation
   - Maintain instance isolation
   - Support proper cleanup

### DOM-based Toots
DOM-based components (like Floater) follow these patterns:
1. Use static methods for simplicity
2. Don't require initialization
3. Handle their own cleanup
4. Support multiple simultaneous instances

Example:
```javascript
import { Floater } from '@clusterflux';

await Floater.createFloater({
    text: 'Hello!',
    origin: { x: 100, y: 100 }
});
```

---

## Internal Utilities

### Color Utilities
The color utilities in `cogs/color/color.js` provide consistent color manipulation across all Clusterflux components. Key features include:

1. **Color Format Support**
   - Hex colors (#RRGGBB)
   - Standard CSS color names
   - RGB string format

2. **Color Transformations**
   - Color name to hex conversion
   - RGB/HSL color space conversions
   - Color scaling and complementary colors
   - Natural-looking gradients
   - Smooth color interpolation

3. **Key Functions**
   - `_setGradient`: Creates natural-looking gradients from a single color
   - `_interpolateColor`: Calculates intermediate colors for smooth transitions
   - Both functions use HSL color space for visually pleasing results

4. **Usage in Components**
   ```javascript
   // Example: LED gradient effect
   await ColorUtils._setGradient('red', 0.2, gradientStops);
   
   // Example: Slider color transition
   const midColor = await ColorUtils._interpolateColor('red', 'green', 0.5);
   ```

Components should use these utilities to ensure consistent color behavior across the library.

---

## License
Clusterflux is open source and available under the [MIT License](LICENSE).

---

## Inspiration
Clusterflux was created to bring a lighthearted yet practical approach to UI design. With names like **Toots**, **Nuggets**, **Clusters**, and **Cogs**, it's a playful take on fresh ideas for UI components.

---

Happy coding with Clusterflux! 🚀

