# Splade.js Documentation

## Overview

Splade is a JavaScript framework that enhances web applications with SPA-like (Single Page Application) features while maintaining the server-side rendering paradigm. It manages page transitions, navigation, modals, state persistence, and other UI interactions without requiring a full page reload.

## Core Concepts

- **Page Management**: Handles navigation between pages while maintaining history state
- **Modal System**: Supports modals and slideovers with a built-in stack management
- **Event Bus**: Facilitates communication between components
- **State Management**: Persists state across page visits
- **Dynamic Components**: Supports lazy-loaded components

## Installation & Setup

### Basic Initialization

```javascript
import { Splade } from "./Splade";

// Initialize Splade with initial HTML, dynamics, and data
Splade.init(initialHtml, initialDynamics, initialSpladeData);

// Configure handlers
Splade.setOnHead((head) => {
  // Update document head
});

Splade.setOnHtml((html, scrollY, animate) => {
  // Update document body
});

Splade.setOnModal((html, type) => {
  // Handle modal content
});

Splade.setOnServerError((html) => {
  // Handle server errors
});
```

## Navigation

### Basic Navigation

```javascript
// Visit a URL (pushes to browser history)
Splade.visit('/users');

// Replace current URL (replaces browser history)
Splade.replace('/users?page=2');

// Refresh current page
Splade.refresh();

// Refresh with scroll position preservation
Splade.refresh(true);
```

### Advanced Navigation

```javascript
// Update URL of current page without refreshing
Splade.replaceUrlOfCurrentPage('/users?filter=active');

// Custom request with specific method and data
Splade.request('/users', 'POST', {name: 'John'}, {'X-Custom-Header': 'value'}, false);
```

## Modal System

```javascript
// Open a URL in modal
Splade.modal('/users/create');

// Open a URL in slideover
Splade.slideover('/users/edit/1');

// Create a confirmation dialog
Splade.confirm(
  'Delete User',           // title
  'Are you sure?',         // text
  'Delete',                // confirmButton text
  'Cancel',                // cancelButton text
  false,                   // confirmPassword
  false,                   // confirmPasswordOnce
  true                     // confirmDanger
).then(() => {
  // User confirmed
}).catch(() => {
  // User cancelled
});

// Close a modal
Splade.popStack();

// Check current stack depth
const stackDepth = Splade.currentStack.value;
```

## State Management

```javascript
// Remember data for current session
Splade.remember('filters', {status: 'active'});

// Remember data with persistence to localStorage
Splade.remember('filters', {status: 'active'}, true);

// Retrieve remembered data
const filters = Splade.restore('filters');

// Retrieve from localStorage
const filters = Splade.restore('filters', true);

// Forget remembered data
Splade.forget('filters');
```

## Event System

```javascript
// Listen for an event
Splade.on('users:created', (data) => {
  console.log('User created:', data);
});

// Remove event listener
Splade.off('users:created', handlerFunction);

// Emit an event
Splade.emit('users:updated', {id: 1, name: 'John'});
```

## Data Access

```javascript
// Access shared data from the server
const user = Splade.sharedData.value.user;

// Access flash messages
const message = Splade.flashData(Splade.currentStack.value).message;

// Access validation errors
if (Splade.hasValidationErrors(Splade.currentStack.value)) {
  const errors = Splade.validationErrors(Splade.currentStack.value);
}
```

## Toasts

```javascript
// Push a toast notification
Splade.pushToast({
  autoDismiss: true,
  message: 'User created successfully',
  type: 'success'
});

// Dismiss a toast
Splade.dismissToast(toastIndex);

// Access all toasts (reversed for display)
const toasts = Splade.toastsReversed.value;
```

## Dynamic Components

```javascript
// Load a lazy component
Splade.lazy('/component/chart', 'chart-component');

// Rehydrate a component
Splade.rehydrate('/component/chart/data', 'chart-component');

// Get HTML for a dynamic component
const html = Splade.htmlForDynamicComponent('chart-component');
```

## Preloaded Modals

```javascript
// Register a preloaded modal
Splade.registerPreloadedModal('user-create', '<div>Modal content</div>', 'modal');

// Open a preloaded modal
Splade.openPreloadedModal('user-create');
```

## Server-Side Rendering Support

Splade automatically detects server-side rendering environments and adapts its behavior accordingly. The `Splade.isSsr` property can be used to check if the code is running in a server-side rendering context.

## Advanced Features

### File Downloads

Splade automatically handles file downloads when a response contains the appropriate headers.

### Browser History Navigation

Splade manages browser history state and handles popstate events to ensure proper back/forward navigation.

### Persistent Layouts

Support for persistent layouts across page navigations to maintain UI state.

## Internal Reactive Properties

- `pageVisitId`: Unique identifier for the current page visit
- `dynamicVisitId`: Unique identifier for dynamic component updates
- `currentStack`: Current modal stack depth
- `sharedData`: Data shared from the server
- `confirmModal`: Current confirmation modal data
- `toasts`: Toast notifications

## Events

- `internal:request`: Emitted when a request starts
- `internal:request-progress`: Emitted during file uploads
- `internal:request-response`: Emitted when a request completes successfully
- `internal:request-error`: Emitted when a request fails
- `history:pushed-state`: Emitted when a new state is pushed to history
- `history:replaced-state`: Emitted when a state is replaced in history
- `history:popped-state`: Emitted when navigating with browser back/forward buttons