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