import {Meta} from '@storybook/addon-docs/blocks'

<Meta title='@dxtmisha/en/functional-basic/Classes/Hash - URL Hash State'/>

# Hash Class

A static facade class for managing data stored in the URL hash (`#`). It delegates execution to the `HashInstance` class, providing centralized access and state isolation (e.g., for SSR).

It automatically synchronizes application state with the URL — every `set` call updates the browser's hash string, while the `hashchange` event refreshes the internal state.

## Key Features

- **URL Synchronization** — Data is stored in a human-readable format in the hash string.
- **Reactivity via Watchers** — The `addWatch` method allows subscribing to changes on a specific variable.
- **Auto-initialization** — When the page loads, data is automatically read from the URL.
- **Smart Typing** — Values are deserialized from a string: numbers, booleans, and objects are restored to their original types.
- **SSR Isolation** — `ServerStorage` ensures a unique data instance for each request on the server.

## Initialization

The class is static and initializes automatically upon the first access.

```javascript
// URL: https://myapp.com/#page=2;filter=active

import { Hash } from '@dxtmisha/functional-basic'

const page = Hash.get('page')    // 2 (number)
const filter = Hash.get('filter') // 'active' (string)
```

## Methods

### Instance
- `static getItem(): HashInstance` — Returns the current `HashInstance` (isolated for the current request).

### Reading and Writing
- `static get<T>(name: string, defaultValue?: T | (() => T)): T` — Returns the value of a hash variable.
- `static set<T>(name: string, callback: T | (() => T)): void` — Sets a variable's value and updates the URL hash.

### Watchers
- `static addWatch<T>(name: string, callback: (value: T) => void): void` — Subscribes to changes for a specific hash variable.
- `static removeWatch<T>(name: string, callback: (value: T) => void): void` — Unsubscribes from changes for a specific variable.

### Management
- `static reload(): void` — Forces synchronization of the state with the current URL hash.

## Examples

### Reading and Writing
```javascript
import { Hash } from '@dxtmisha/functional-basic'

// Reading with a default value
const page = Hash.get<number>('page', 1)

// Writing (URL changes to #page=3)
Hash.set('page', 3)

// Writing via a function
Hash.set('page', () => page + 1)
```

### Subscribing to Changes
```javascript
Hash.addWatch<string>('filter', (newFilter) => {
  console.log('Filter changed to:', newFilter)
})

// Unsubscribe (callback must be a reference to the same function)
Hash.removeWatch('filter', callback)
```

### Managing Page State
```javascript
// Initialize filters with a default value
const filter = Hash.get('filter', 'all')
const sort = Hash.get('sort', 'date')

// Change on user action
Hash.set('filter', 'active')
// URL: #filter=active;sort=date
```
