rellx 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/README.md +317 -71
  2. package/package.json +1 -1
package/README.md CHANGED
@@ -1,50 +1,50 @@
1
1
  # Rellx
2
2
 
3
- Универсальный менеджер состояния для JavaScript и TypeScript приложений. Rellx предоставляет простой и мощный API для управления состоянием с поддержкой реактивности, middleware, плагинов и DevTools.
3
+ Universal state manager for JavaScript and TypeScript applications. Rellx provides a simple and powerful API for state management with support for reactivity, middleware, plugins, and DevTools.
4
4
 
5
- ## Что это такое?
5
+ ## What is it?
6
6
 
7
- Rellx - это библиотека для управления состоянием, которая решает проблему синхронизации данных между различными частями приложения. Она создана с учетом простоты использования, производительности и гибкости.
7
+ Rellx is a state management library that solves the problem of data synchronization between different parts of an application. It's built with simplicity, performance, and flexibility in mind.
8
8
 
9
- Библиотека предлагает три режима работы:
10
- - **Light** - минималистичный вариант с базовым функционалом
11
- - **Full** - полная версия с поддержкой middleware
12
- - **Reactive** - реактивная версия с автоматическим отслеживанием изменений
9
+ The library offers three modes of operation:
10
+ - **Light** - minimalistic version with basic functionality
11
+ - **Full** - full version with middleware support
12
+ - **Reactive** - reactive version with automatic change tracking
13
13
 
14
- ## Основные возможности
14
+ ## Key Features
15
15
 
16
- - **Простой API** - интуитивно понятный интерфейс для работы с состоянием
17
- - **TypeScript поддержка** - полная типизация из коробки
18
- - **Реактивность** - автоматическое отслеживание изменений вложенных объектов
19
- - **Middleware** - расширяемость через систему middleware
20
- - **Плагины** - поддержка кастомных плагинов для расширения функциональности
21
- - **DevTools** - инструменты для отладки и мониторинга состояния
22
- - **Небольшой размер** - легковесная библиотека без лишних зависимостей
23
- - **Универсальность** - работает в браузере и Node.js
16
+ - **Simple API** - intuitive interface for working with state
17
+ - **TypeScript support** - full type definitions out of the box
18
+ - **Reactivity** - automatic tracking of nested object changes
19
+ - **Middleware** - extensibility through middleware system
20
+ - **Plugins** - support for custom plugins to extend functionality
21
+ - **DevTools** - tools for debugging and monitoring state
22
+ - **Small size** - lightweight library without unnecessary dependencies
23
+ - **Universal** - works in browser and Node.js
24
24
 
25
- ## Установка
25
+ ## Installation
26
26
 
27
27
  ```bash
28
28
  npm install rellx
29
29
  ```
30
30
 
31
- или
31
+ or
32
32
 
33
33
  ```bash
34
34
  yarn add rellx
35
35
  ```
36
36
 
37
- или
37
+ or
38
38
 
39
39
  ```bash
40
40
  pnpm add rellx
41
41
  ```
42
42
 
43
- ## Быстрый старт
43
+ ## Quick Start
44
44
 
45
- ### Light версия
45
+ ### Light Version
46
46
 
47
- Самая простая версия для базового управления состоянием:
47
+ The simplest version for basic state management:
48
48
 
49
49
  ```typescript
50
50
  import { createLightStore } from 'rellx';
@@ -59,27 +59,27 @@ const store = createLightStore<State>({
59
59
  user: null
60
60
  });
61
61
 
62
- // Подписка на изменения
62
+ // Subscribe to changes
63
63
  const unsubscribe = store.subscribe((state) => {
64
64
  console.log('State changed:', state);
65
65
  });
66
66
 
67
- // Обновление состояния
67
+ // Update state
68
68
  store.setState((prev) => ({
69
69
  ...prev,
70
70
  count: prev.count + 1
71
71
  }));
72
72
 
73
- // Получение текущего состояния
73
+ // Get current state
74
74
  const currentState = store.getState();
75
75
 
76
- // Отписка
76
+ // Unsubscribe
77
77
  unsubscribe();
78
78
  ```
79
79
 
80
- ### Full версия с middleware
80
+ ### Full Version with Middleware
81
81
 
82
- Версия с поддержкой middleware для более сложных сценариев:
82
+ Version with middleware support for more complex scenarios:
83
83
 
84
84
  ```typescript
85
85
  import { createFullStore, loggerMiddleware } from 'rellx/full';
@@ -94,26 +94,26 @@ const store = createFullStore<State>({
94
94
  filter: 'all'
95
95
  });
96
96
 
97
- // Добавление middleware
97
+ // Add middleware
98
98
  store.use(loggerMiddleware);
99
99
 
100
- // Создание кастомного middleware
100
+ // Create custom middleware
101
101
  store.use((store) => (next) => (updater) => {
102
102
  console.log('Before update:', store.getState());
103
103
  next(updater);
104
104
  console.log('After update:', store.getState());
105
105
  });
106
106
 
107
- // Использование
107
+ // Usage
108
108
  store.setState((prev) => ({
109
109
  ...prev,
110
110
  todos: [...prev.todos, { id: 1, text: 'New todo', completed: false }]
111
111
  }));
112
112
  ```
113
113
 
114
- ### Reactive версия
114
+ ### Reactive Version
115
115
 
116
- Реактивная версия с автоматическим отслеживанием изменений:
116
+ Reactive version with automatic change tracking:
117
117
 
118
118
  ```typescript
119
119
  import { createReactiveStore } from 'rellx';
@@ -140,35 +140,35 @@ const store = createReactiveStore<State>({
140
140
  counter: 0
141
141
  });
142
142
 
143
- // Подписка на изменения
143
+ // Subscribe to changes
144
144
  store.subscribe((state) => {
145
145
  console.log('State updated:', state);
146
146
  });
147
147
 
148
- // Прямое изменение свойств - изменения отслеживаются автоматически
148
+ // Direct property changes - changes are tracked automatically
149
149
  store.reactive.counter = 10;
150
150
  store.reactive.user.name = 'Jane';
151
151
  store.reactive.user.preferences.theme = 'dark';
152
152
 
153
- // Все изменения автоматически триггерят подписчиков
153
+ // All changes automatically trigger subscribers
154
154
  ```
155
155
 
156
156
  ## API
157
157
 
158
158
  ### StoreCore
159
159
 
160
- Базовый класс для всех версий стора.
160
+ Base class for all store versions.
161
161
 
162
- #### Методы
162
+ #### Methods
163
163
 
164
- - `getState(): T` - получить текущее состояние
165
- - `setState(updater: (prevState: T) => T): void` - обновить состояние
166
- - `subscribe(listener: (state: T) => void): () => void` - подписаться на изменения, возвращает функцию отписки
167
- - `destroy(): void` - уничтожить стор и очистить все подписки
164
+ - `getState(): T` - get current state
165
+ - `setState(updater: (prevState: T) => T): void` - update state
166
+ - `subscribe(listener: (state: T) => void): () => void` - subscribe to changes, returns unsubscribe function
167
+ - `destroy(): void` - destroy store and clear all subscriptions
168
168
 
169
169
  ### Light Store
170
170
 
171
- Простая версия без дополнительных функций.
171
+ Simple version without additional features.
172
172
 
173
173
  ```typescript
174
174
  import { createLightStore } from 'rellx';
@@ -178,42 +178,42 @@ const store = createLightStore(initialState);
178
178
 
179
179
  ### Full Store
180
180
 
181
- Версия с поддержкой middleware.
181
+ Version with middleware support.
182
182
 
183
183
  ```typescript
184
184
  import { createFullStore } from 'rellx/full';
185
185
 
186
186
  const store = createFullStore(initialState);
187
187
 
188
- // Добавление middleware
188
+ // Add middleware
189
189
  store.use(middleware);
190
190
  ```
191
191
 
192
192
  ### Reactive Store
193
193
 
194
- Реактивная версия с автоматическим отслеживанием.
194
+ Reactive version with automatic tracking.
195
195
 
196
196
  ```typescript
197
197
  import { createReactiveStore } from 'rellx';
198
198
 
199
199
  const store = createReactiveStore(initialState);
200
200
 
201
- // Доступ к реактивному состоянию
201
+ // Access reactive state
202
202
  store.reactive.property = value;
203
203
 
204
- // Получение состояния
204
+ // Get state
205
205
  const state = store.getState();
206
206
 
207
- // Установка свойства
207
+ // Set property
208
208
  store.setProperty('key', value);
209
209
 
210
- // Получение свойства
210
+ // Get property
211
211
  const value = store.getProperty('key');
212
212
  ```
213
213
 
214
- ## Плагины
214
+ ## Plugins
215
215
 
216
- Rellx поддерживает систему плагинов для расширения функциональности:
216
+ Rellx supports a plugin system for extending functionality:
217
217
 
218
218
  ```typescript
219
219
  import { StoreCore } from 'rellx';
@@ -225,7 +225,7 @@ const myPlugin: StorePlugin<MyState> = {
225
225
  },
226
226
 
227
227
  onBeforeUpdate(newState, oldState) {
228
- // Можете модифицировать состояние перед обновлением
228
+ // You can modify state before update
229
229
  return newState;
230
230
  },
231
231
 
@@ -234,9 +234,9 @@ const myPlugin: StorePlugin<MyState> = {
234
234
  },
235
235
 
236
236
  onSubscribe(listener) {
237
- // Дополнительная логика при подписке
237
+ // Additional logic on subscribe
238
238
  return () => {
239
- // Очистка при отписке
239
+ // Cleanup on unsubscribe
240
240
  };
241
241
  },
242
242
 
@@ -250,7 +250,7 @@ const store = new StoreCore(initialState, [myPlugin]);
250
250
 
251
251
  ## DevTools
252
252
 
253
- Rellx включает инструменты разработчика для отладки состояния:
253
+ Rellx includes developer tools for state debugging:
254
254
 
255
255
  ```typescript
256
256
  import { createFullStore } from 'rellx/full';
@@ -264,15 +264,261 @@ const devTools = createDevToolsPlugin(store, {
264
264
  maxHistorySize: 50
265
265
  });
266
266
 
267
- // Подключение к DevTools серверу
267
+ // Connect to DevTools server
268
268
  devTools.connect('ws://localhost:8097');
269
269
  ```
270
270
 
271
- Подробнее о DevTools смотрите в документации [rellx-devtools](rellx-devtools/README.md).
271
+ For more information about DevTools, see the [rellx-devtools](../rellx-devtools/README.md) documentation.
272
272
 
273
- ## Примеры использования
273
+ ## Framework Integration
274
274
 
275
- ### Todo приложение
275
+ ### React
276
+
277
+ ```typescript
278
+ import React, { useEffect, useState } from 'react';
279
+ import { createFullStore } from 'rellx/full';
280
+
281
+ // Create store
282
+ const store = createFullStore({
283
+ count: 0,
284
+ todos: []
285
+ });
286
+
287
+ // Custom hook
288
+ function useStore<T>(store: ReturnType<typeof createFullStore<T>>) {
289
+ const [state, setState] = useState(store.getState());
290
+
291
+ useEffect(() => {
292
+ const unsubscribe = store.subscribe((newState) => {
293
+ setState(newState);
294
+ });
295
+ return unsubscribe;
296
+ }, [store]);
297
+
298
+ return [state, store.setState.bind(store)] as const;
299
+ }
300
+
301
+ // Component
302
+ function Counter() {
303
+ const [state, setState] = useStore(store);
304
+
305
+ return (
306
+ <div>
307
+ <p>Count: {state.count}</p>
308
+ <button onClick={() => setState(prev => ({ ...prev, count: prev.count + 1 }))}>
309
+ Increment
310
+ </button>
311
+ </div>
312
+ );
313
+ }
314
+ ```
315
+
316
+ ### Vue 3
317
+
318
+ ```typescript
319
+ import { ref, onMounted, onUnmounted } from 'vue';
320
+ import { createFullStore } from 'rellx/full';
321
+
322
+ // Create store
323
+ const store = createFullStore({
324
+ count: 0,
325
+ todos: []
326
+ });
327
+
328
+ // Composable
329
+ function useStore<T>(store: ReturnType<typeof createFullStore<T>>) {
330
+ const state = ref(store.getState());
331
+
332
+ let unsubscribe: (() => void) | null = null;
333
+
334
+ onMounted(() => {
335
+ unsubscribe = store.subscribe((newState) => {
336
+ state.value = newState;
337
+ });
338
+ });
339
+
340
+ onUnmounted(() => {
341
+ unsubscribe?.();
342
+ });
343
+
344
+ return {
345
+ state,
346
+ setState: store.setState.bind(store)
347
+ };
348
+ }
349
+
350
+ // Component
351
+ export default {
352
+ setup() {
353
+ const { state, setState } = useStore(store);
354
+
355
+ const increment = () => {
356
+ setState(prev => ({ ...prev, count: prev.count + 1 }));
357
+ };
358
+
359
+ return {
360
+ state,
361
+ increment
362
+ };
363
+ },
364
+ template: `
365
+ <div>
366
+ <p>Count: {{ state.count }}</p>
367
+ <button @click="increment">Increment</button>
368
+ </div>
369
+ `
370
+ };
371
+ ```
372
+
373
+ ### Angular
374
+
375
+ ```typescript
376
+ import { Injectable, Component, OnDestroy } from '@angular/core';
377
+ import { BehaviorSubject, Observable } from 'rxjs';
378
+ import { createFullStore } from 'rellx/full';
379
+
380
+ // Service
381
+ @Injectable({ providedIn: 'root' })
382
+ export class StoreService {
383
+ private store = createFullStore({
384
+ count: 0,
385
+ todos: []
386
+ });
387
+
388
+ private stateSubject = new BehaviorSubject(this.store.getState());
389
+ public state$: Observable<typeof this.store.getState> = this.stateSubject.asObservable();
390
+
391
+ constructor() {
392
+ this.store.subscribe((state) => {
393
+ this.stateSubject.next(state);
394
+ });
395
+ }
396
+
397
+ getState() {
398
+ return this.store.getState();
399
+ }
400
+
401
+ setState(updater: any) {
402
+ this.store.setState(updater);
403
+ }
404
+ }
405
+
406
+ // Component
407
+ @Component({
408
+ selector: 'app-counter',
409
+ template: `
410
+ <div>
411
+ <p>Count: {{ state.count }}</p>
412
+ <button (click)="increment()">Increment</button>
413
+ </div>
414
+ `
415
+ })
416
+ export class CounterComponent implements OnDestroy {
417
+ state: any;
418
+ private subscription: any;
419
+
420
+ constructor(private storeService: StoreService) {
421
+ this.subscription = this.storeService.state$.subscribe(state => {
422
+ this.state = state;
423
+ });
424
+ }
425
+
426
+ increment() {
427
+ this.storeService.setState((prev: any) => ({
428
+ ...prev,
429
+ count: prev.count + 1
430
+ }));
431
+ }
432
+
433
+ ngOnDestroy() {
434
+ this.subscription.unsubscribe();
435
+ }
436
+ }
437
+ ```
438
+
439
+ ### Svelte
440
+
441
+ ```javascript
442
+ <script lang="ts">
443
+ import { onMount, onDestroy } from 'svelte';
444
+ import { writable } from 'svelte/store';
445
+ import { createFullStore } from 'rellx/full';
446
+
447
+ // Create Rellx store
448
+ const rellxStore = createFullStore({
449
+ count: 0,
450
+ todos: []
451
+ });
452
+
453
+ // Create Svelte store wrapper
454
+ const stateStore = writable(rellxStore.getState());
455
+
456
+ let unsubscribe: (() => void) | null = null;
457
+
458
+ onMount(() => {
459
+ unsubscribe = rellxStore.subscribe((state) => {
460
+ stateStore.set(state);
461
+ });
462
+ });
463
+
464
+ onDestroy(() => {
465
+ unsubscribe?.();
466
+ });
467
+
468
+ function increment() {
469
+ rellxStore.setState(prev => ({
470
+ ...prev,
471
+ count: prev.count + 1
472
+ }));
473
+ }
474
+ </script>
475
+
476
+ <div>
477
+ <p>Count: {$stateStore.count}</p>
478
+ <button on:click={increment}>Increment</button>
479
+ </div>
480
+ ```
481
+
482
+ ### Vanilla JavaScript
483
+
484
+ ```javascript
485
+ import { createFullStore } from 'rellx/full';
486
+
487
+ // Create store
488
+ const store = createFullStore({
489
+ count: 0,
490
+ todos: []
491
+ });
492
+
493
+ // Subscribe to changes
494
+ store.subscribe((state) => {
495
+ // Update UI when state changes
496
+ document.getElementById('count').textContent = state.count;
497
+ renderTodos(state.todos);
498
+ });
499
+
500
+ // Initial render
501
+ document.getElementById('count').textContent = store.getState().count;
502
+
503
+ // Event handlers
504
+ document.getElementById('increment').addEventListener('click', () => {
505
+ store.setState(prev => ({
506
+ ...prev,
507
+ count: prev.count + 1
508
+ }));
509
+ });
510
+
511
+ function renderTodos(todos) {
512
+ const container = document.getElementById('todos');
513
+ container.innerHTML = todos.map(todo => `
514
+ <div>${todo.text}</div>
515
+ `).join('');
516
+ }
517
+ ```
518
+
519
+ ## Usage Examples
520
+
521
+ ### Todo Application
276
522
 
277
523
  ```typescript
278
524
  import { createFullStore } from 'rellx/full';
@@ -293,7 +539,7 @@ const store = createFullStore<State>({
293
539
  filter: 'all'
294
540
  });
295
541
 
296
- // Действия
542
+ // Actions
297
543
  const addTodo = (text: string) => {
298
544
  store.setState((prev) => ({
299
545
  ...prev,
@@ -317,14 +563,14 @@ const setFilter = (filter: State['filter']) => {
317
563
  store.setState((prev) => ({ ...prev, filter }));
318
564
  };
319
565
 
320
- // Подписка на изменения
566
+ // Subscribe to changes
321
567
  store.subscribe((state) => {
322
568
  console.log('Todos updated:', state.todos);
323
569
  console.log('Filter:', state.filter);
324
570
  });
325
571
  ```
326
572
 
327
- ### Счетчик с историей
573
+ ### Counter with History
328
574
 
329
575
  ```typescript
330
576
  import { createReactiveStore } from 'rellx';
@@ -344,25 +590,25 @@ store.subscribe((state) => {
344
590
  console.log(`History: ${state.history.join(', ')}`);
345
591
  });
346
592
 
347
- // Увеличение счетчика
593
+ // Increment counter
348
594
  store.reactive.count++;
349
595
  store.reactive.history.push(store.reactive.count);
350
596
  ```
351
597
 
352
- ## Совместимость
598
+ ## Compatibility
353
599
 
354
600
  - Node.js: 14+
355
- - Браузеры: все современные браузеры (ES2020+)
601
+ - Browsers: all modern browsers (ES2020+)
356
602
  - TypeScript: 4.5+
357
603
 
358
- ## Лицензия
604
+ ## License
359
605
 
360
606
  Apache License 2.0
361
607
 
362
- ## Поддержка
608
+ ## Support
363
609
 
364
- Если у вас есть вопросы, предложения или вы нашли баг, пожалуйста, создайте issue в репозитории проекта.
610
+ If you have questions, suggestions, or found a bug, please create an issue in the project repository.
365
611
 
366
- ## Вклад в проект
612
+ ## Contributing
367
613
 
368
- Мы приветствуем вклад в развитие проекта! Пожалуйста, прочитайте руководство по контрибьюции перед отправкой pull request.
614
+ We welcome contributions to the project! Please read the contribution guide before submitting a pull request.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "rellx",
4
- "version": "1.1.0",
4
+ "version": "1.2.0",
5
5
  "description": "Universal state manager for JavaScript and TypeScript applications",
6
6
  "keywords": [
7
7
  "state-management",