slicejs-web-framework 2.2.13 → 2.3.1
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.
- package/README.md +155 -156
- package/Slice/Components/Structural/ContextManager/ContextManager.js +361 -0
- package/Slice/Components/Structural/Controller/Controller.js +131 -96
- package/Slice/Components/Structural/EventManager/EventManager.js +329 -0
- package/Slice/Components/Structural/Router/Router.js +112 -103
- package/Slice/Slice.js +83 -35
- package/package.json +1 -1
- package/src/Components/AppComponents/HomePage/HomePage.js +195 -195
- package/src/Components/Visual/CodeVisualizer/CodeVisualizer.js +3 -4
- package/src/Components/components.js +1 -2
- package/src/sliceConfig.json +59 -53
- package/src/Components/Service/Translator/Translator.js +0 -45
- package/src/Components/Service/Translator/messages.json +0 -58
package/README.md
CHANGED
|
@@ -1,156 +1,155 @@
|
|
|
1
|
-
<!-- Improved compatibility of back to top link: See: https://github.com/VKneider/slice.js/pull/73 -->
|
|
2
|
-
<a name="readme-top"></a>
|
|
3
|
-
<!--
|
|
4
|
-
*** Thanks for checking out the slice.js. If you have a suggestion
|
|
5
|
-
*** that would make this better, please fork the repo and create a pull request
|
|
6
|
-
*** or simply open an issue with the tag "enhancement".
|
|
7
|
-
*** Don't forget to give the project a star!
|
|
8
|
-
*** Thanks again! Now go create something AMAZING! :D
|
|
9
|
-
-->
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
<!-- PROJECT SHIELDS -->
|
|
14
|
-
<!--
|
|
15
|
-
*** I'm using markdown "reference style" links for readability.
|
|
16
|
-
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
|
|
17
|
-
*** See the bottom of this document for the declaration of the reference variables
|
|
18
|
-
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
|
|
19
|
-
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
|
|
20
|
-
-->
|
|
21
|
-
[![Contributors][contributors-shield]][contributors-url]
|
|
22
|
-
[![Forks][forks-shield]][forks-url]
|
|
23
|
-
[![Stargazers][stars-shield]][stars-url]
|
|
24
|
-
[![Issues][issues-shield]][issues-url]
|
|
25
|
-
[![MIT License][license-shield]][license-url]
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
<!-- PROJECT LOGO -->
|
|
30
|
-
<br />
|
|
31
|
-
<div align="center">
|
|
32
|
-
<a href="https://github.com/VKneider/slice.js">
|
|
33
|
-
<img src="readme_images/Slice.js-logo.svg" alt="Logo" width="150" height="150">
|
|
34
|
-
</a>
|
|
35
|
-
|
|
36
|
-
<h3 align="center">Slice.js</h3>
|
|
37
|
-
|
|
38
|
-
<p align="center">
|
|
39
|
-
Component-Based Web Development Framework
|
|
40
|
-
<br />
|
|
41
|
-
<a href="https://slice-js-docs.vercel.app/Documentation"><strong>Explore the docs »</strong></a>
|
|
42
|
-
<br />
|
|
43
|
-
<br />
|
|
44
|
-
<a href="https://slice-js-docs.vercel.app/">View Demo</a>
|
|
45
|
-
·
|
|
46
|
-
<a href="https://github.com/VKneider/slice.js/issues/new?labels=bug&template=bug-report---.md">Report Bug</a>
|
|
47
|
-
·
|
|
48
|
-
<a href="https://github.com/VKneider/slice.js/issues/new?labels=enhancement&template=feature-request---.md">Request Feature</a>
|
|
49
|
-
</p>
|
|
50
|
-
</div>
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
<!-- TABLE OF CONTENTS -->
|
|
55
|
-
<details>
|
|
56
|
-
<summary>Table of Contents</summary>
|
|
57
|
-
<ol>
|
|
58
|
-
<li>
|
|
59
|
-
<a href="#about-the-project">About The Project</a>
|
|
60
|
-
</li>
|
|
61
|
-
<li>
|
|
62
|
-
<a href="#getting-started">Getting Started</a>
|
|
63
|
-
<ul>
|
|
64
|
-
<li><a href="#prerequisites">Prerequisites</a></li>
|
|
65
|
-
<li><a href="#installation">Installation</a></li>
|
|
66
|
-
</ul>
|
|
67
|
-
</li>
|
|
68
|
-
<li><a href="#roadmap">Roadmap</a></li>
|
|
69
|
-
<li><a href="#contributing">Contributing</a></li>
|
|
70
|
-
<li><a href="#license">License</a></li>
|
|
71
|
-
<li><a href="#contact">Contact</a></li>
|
|
72
|
-
</ol>
|
|
73
|
-
</details>
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
<!-- ABOUT THE PROJECT -->
|
|
78
|
-
## About The Project
|
|
79
|
-
|
|
80
|
-
[![Product Name Screen Shot][product-screenshot]](https://slice-js-docs.vercel.app/)
|
|
81
|
-
|
|
82
|
-
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
83
|
-
|
|
84
|
-
<!-- GETTING STARTED -->
|
|
85
|
-
## Getting Started
|
|
86
|
-
|
|
87
|
-
This is an example of how you may give instructions on setting up your project locally.
|
|
88
|
-
To get a local copy up and running follow these simple example steps.
|
|
89
|
-
|
|
90
|
-
### Installation
|
|
91
|
-
|
|
92
|
-
_Below is an example of how you can instruct your audience on installing and setting up your app. This template doesn't rely on any external dependencies or services._
|
|
93
|
-
|
|
94
|
-
1. Install slicejs cli dependencies
|
|
95
|
-
```sh
|
|
96
|
-
npm i slicejs-cli
|
|
97
|
-
```
|
|
98
|
-
2. Initialize slice project
|
|
99
|
-
```sh
|
|
100
|
-
npm run slice:init
|
|
101
|
-
```
|
|
102
|
-
3. Start web server
|
|
103
|
-
```sh
|
|
104
|
-
npm run slice:start
|
|
105
|
-
```
|
|
106
|
-
|
|
107
|
-
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
<!-- ROADMAP -->
|
|
112
|
-
## Roadmap
|
|
113
|
-
|
|
114
|
-
- [x] Add Changelog
|
|
115
|
-
- [ ] Add Image visual component
|
|
116
|
-
- [ ] Modify Slice Card Visual Component
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
<!--
|
|
142
|
-
|
|
143
|
-
[contributors-
|
|
144
|
-
[
|
|
145
|
-
[forks-
|
|
146
|
-
[
|
|
147
|
-
[stars-
|
|
148
|
-
[
|
|
149
|
-
[issues-
|
|
150
|
-
[
|
|
151
|
-
[license-
|
|
152
|
-
[
|
|
153
|
-
[linkedin-
|
|
154
|
-
[
|
|
155
|
-
|
|
156
|
-
|
|
1
|
+
<!-- Improved compatibility of back to top link: See: https://github.com/VKneider/slice.js/pull/73 -->
|
|
2
|
+
<a name="readme-top"></a>
|
|
3
|
+
<!--
|
|
4
|
+
*** Thanks for checking out the slice.js. If you have a suggestion
|
|
5
|
+
*** that would make this better, please fork the repo and create a pull request
|
|
6
|
+
*** or simply open an issue with the tag "enhancement".
|
|
7
|
+
*** Don't forget to give the project a star!
|
|
8
|
+
*** Thanks again! Now go create something AMAZING! :D
|
|
9
|
+
-->
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
<!-- PROJECT SHIELDS -->
|
|
14
|
+
<!--
|
|
15
|
+
*** I'm using markdown "reference style" links for readability.
|
|
16
|
+
*** Reference links are enclosed in brackets [ ] instead of parentheses ( ).
|
|
17
|
+
*** See the bottom of this document for the declaration of the reference variables
|
|
18
|
+
*** for contributors-url, forks-url, etc. This is an optional, concise syntax you may use.
|
|
19
|
+
*** https://www.markdownguide.org/basic-syntax/#reference-style-links
|
|
20
|
+
-->
|
|
21
|
+
[![Contributors][contributors-shield]][contributors-url]
|
|
22
|
+
[![Forks][forks-shield]][forks-url]
|
|
23
|
+
[![Stargazers][stars-shield]][stars-url]
|
|
24
|
+
[![Issues][issues-shield]][issues-url]
|
|
25
|
+
[![MIT License][license-shield]][license-url]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
<!-- PROJECT LOGO -->
|
|
30
|
+
<br />
|
|
31
|
+
<div align="center">
|
|
32
|
+
<a href="https://github.com/VKneider/slice.js">
|
|
33
|
+
<img src="readme_images/Slice.js-logo.svg" alt="Logo" width="150" height="150">
|
|
34
|
+
</a>
|
|
35
|
+
|
|
36
|
+
<h3 align="center">Slice.js</h3>
|
|
37
|
+
|
|
38
|
+
<p align="center">
|
|
39
|
+
Component-Based Web Development Framework
|
|
40
|
+
<br />
|
|
41
|
+
<a href="https://slice-js-docs.vercel.app/Documentation"><strong>Explore the docs »</strong></a>
|
|
42
|
+
<br />
|
|
43
|
+
<br />
|
|
44
|
+
<a href="https://slice-js-docs.vercel.app/">View Demo</a>
|
|
45
|
+
·
|
|
46
|
+
<a href="https://github.com/VKneider/slice.js/issues/new?labels=bug&template=bug-report---.md">Report Bug</a>
|
|
47
|
+
·
|
|
48
|
+
<a href="https://github.com/VKneider/slice.js/issues/new?labels=enhancement&template=feature-request---.md">Request Feature</a>
|
|
49
|
+
</p>
|
|
50
|
+
</div>
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
<!-- TABLE OF CONTENTS -->
|
|
55
|
+
<details>
|
|
56
|
+
<summary>Table of Contents</summary>
|
|
57
|
+
<ol>
|
|
58
|
+
<li>
|
|
59
|
+
<a href="#about-the-project">About The Project</a>
|
|
60
|
+
</li>
|
|
61
|
+
<li>
|
|
62
|
+
<a href="#getting-started">Getting Started</a>
|
|
63
|
+
<ul>
|
|
64
|
+
<li><a href="#prerequisites">Prerequisites</a></li>
|
|
65
|
+
<li><a href="#installation">Installation</a></li>
|
|
66
|
+
</ul>
|
|
67
|
+
</li>
|
|
68
|
+
<li><a href="#roadmap">Roadmap</a></li>
|
|
69
|
+
<li><a href="#contributing">Contributing</a></li>
|
|
70
|
+
<li><a href="#license">License</a></li>
|
|
71
|
+
<li><a href="#contact">Contact</a></li>
|
|
72
|
+
</ol>
|
|
73
|
+
</details>
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
<!-- ABOUT THE PROJECT -->
|
|
78
|
+
## About The Project
|
|
79
|
+
|
|
80
|
+
[![Product Name Screen Shot][product-screenshot]](https://slice-js-docs.vercel.app/)
|
|
81
|
+
|
|
82
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
83
|
+
|
|
84
|
+
<!-- GETTING STARTED -->
|
|
85
|
+
## Getting Started
|
|
86
|
+
|
|
87
|
+
This is an example of how you may give instructions on setting up your project locally.
|
|
88
|
+
To get a local copy up and running follow these simple example steps.
|
|
89
|
+
|
|
90
|
+
### Installation
|
|
91
|
+
|
|
92
|
+
_Below is an example of how you can instruct your audience on installing and setting up your app. This template doesn't rely on any external dependencies or services._
|
|
93
|
+
|
|
94
|
+
1. Install slicejs cli dependencies
|
|
95
|
+
```sh
|
|
96
|
+
npm i slicejs-cli
|
|
97
|
+
```
|
|
98
|
+
2. Initialize slice project
|
|
99
|
+
```sh
|
|
100
|
+
npm run slice:init
|
|
101
|
+
```
|
|
102
|
+
3. Start web server
|
|
103
|
+
```sh
|
|
104
|
+
npm run slice:start
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
<!-- ROADMAP -->
|
|
112
|
+
## Roadmap
|
|
113
|
+
|
|
114
|
+
- [x] Add Changelog
|
|
115
|
+
- [ ] Add Image visual component
|
|
116
|
+
- [ ] Modify Slice Card Visual Component
|
|
117
|
+
|
|
118
|
+
See the [open issues](https://github.com/VKneider/slice.js/issues) for a full list of proposed features (and known issues).
|
|
119
|
+
|
|
120
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
<!-- CONTRIBUTING -->
|
|
125
|
+
## Contributing
|
|
126
|
+
|
|
127
|
+
We welcome contributions to the project! Please make sure to review the guidelines in the [CONTRIBUTING.md](docs/CONTRIBUTING.md) file before submitting any changes.
|
|
128
|
+
|
|
129
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
<!-- LICENSE -->
|
|
134
|
+
## License
|
|
135
|
+
|
|
136
|
+
Distributed under the MIT License. See `LICENSE` for more information.
|
|
137
|
+
|
|
138
|
+
<p align="right">(<a href="#readme-top">back to top</a>)</p>
|
|
139
|
+
|
|
140
|
+
<!-- MARKDOWN LINKS & IMAGES -->
|
|
141
|
+
<!-- https://www.markdownguide.org/basic-syntax/#reference-style-links -->
|
|
142
|
+
[contributors-shield]: https://img.shields.io/github/contributors/VKneider/slice.js.svg?style=for-the-badge
|
|
143
|
+
[contributors-url]: https://github.com/VKneider/slice.js/graphs/contributors
|
|
144
|
+
[forks-shield]: https://img.shields.io/github/forks/VKneider/slice.js.svg?style=for-the-badge
|
|
145
|
+
[forks-url]: https://github.com/VKneider/slice.js/network/members
|
|
146
|
+
[stars-shield]: https://img.shields.io/github/stars/VKneider/slice.js.svg?style=for-the-badge
|
|
147
|
+
[stars-url]: https://github.com/VKneider/slice.js/stargazers
|
|
148
|
+
[issues-shield]: https://img.shields.io/github/issues/VKneider/slice.js.svg?style=for-the-badge
|
|
149
|
+
[issues-url]: https://github.com/VKneider/slice.js/issues
|
|
150
|
+
[license-shield]: https://img.shields.io/github/license/VKneider/slice.js.svg?style=for-the-badge
|
|
151
|
+
[license-url]: https://github.com/VKneider/slice.js/blob/master/LICENSE.txt
|
|
152
|
+
[linkedin-shield]: https://img.shields.io/badge/-LinkedIn-black.svg?style=for-the-badge&logo=linkedin&colorB=555
|
|
153
|
+
[linkedin-url]: https://linkedin.com/in/VKneider
|
|
154
|
+
[product-screenshot]: readme_images/screenshot.JPG
|
|
155
|
+
|
|
@@ -0,0 +1,361 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ContextManager - Sistema de contextos compartidos para Slice.js
|
|
3
|
+
* Ubicación: /Slice/Components/Structural/ContextManager/ContextManager.js
|
|
4
|
+
*
|
|
5
|
+
* Características:
|
|
6
|
+
* - Estado compartido entre componentes
|
|
7
|
+
* - Usa EventManager internamente para notificaciones
|
|
8
|
+
* - Selectores para observar campos específicos
|
|
9
|
+
* - Auto-limpieza cuando componentes se destruyen
|
|
10
|
+
* - Persistencia opcional en localStorage
|
|
11
|
+
*/
|
|
12
|
+
export default class ContextManager {
|
|
13
|
+
constructor() {
|
|
14
|
+
// Map<contextName, { state, options }>
|
|
15
|
+
this.contexts = new Map();
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
init() {
|
|
19
|
+
return true;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// ============================================
|
|
23
|
+
// CREAR CONTEXTO
|
|
24
|
+
// ============================================
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Crear un nuevo contexto
|
|
28
|
+
* @param {string} name - Nombre único del contexto
|
|
29
|
+
* @param {Object} initialState - Estado inicial
|
|
30
|
+
* @param {Object} options - Opciones: { persist: boolean }
|
|
31
|
+
*
|
|
32
|
+
* @example
|
|
33
|
+
* slice.context.create('auth', {
|
|
34
|
+
* isLoggedIn: false,
|
|
35
|
+
* user: null
|
|
36
|
+
* });
|
|
37
|
+
*
|
|
38
|
+
* // Con persistencia en localStorage
|
|
39
|
+
* slice.context.create('preferences', {
|
|
40
|
+
* theme: 'light',
|
|
41
|
+
* language: 'es'
|
|
42
|
+
* }, { persist: true });
|
|
43
|
+
*/
|
|
44
|
+
create(name, initialState = {}, options = {}) {
|
|
45
|
+
if (this.contexts.has(name)) {
|
|
46
|
+
slice.logger.logWarning('ContextManager', `El contexto "${name}" ya existe`);
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Cargar estado persistido si existe
|
|
51
|
+
let state = initialState;
|
|
52
|
+
if (options.persist) {
|
|
53
|
+
const persisted = this._loadFromStorage(name);
|
|
54
|
+
if (persisted !== null) {
|
|
55
|
+
state = persisted;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
this.contexts.set(name, {
|
|
60
|
+
state,
|
|
61
|
+
options: {
|
|
62
|
+
persist: options.persist || false,
|
|
63
|
+
storageKey: options.storageKey || `slice_context_${name}`,
|
|
64
|
+
},
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
slice.logger.logInfo('ContextManager', `Contexto "${name}" creado`);
|
|
68
|
+
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// ============================================
|
|
73
|
+
// LEER ESTADO
|
|
74
|
+
// ============================================
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Obtener el estado actual de un contexto
|
|
78
|
+
* @param {string} name - Nombre del contexto
|
|
79
|
+
* @returns {*} Estado actual o null si no existe
|
|
80
|
+
*
|
|
81
|
+
* @example
|
|
82
|
+
* const auth = slice.context.getState('auth');
|
|
83
|
+
* console.log(auth.user.name);
|
|
84
|
+
*/
|
|
85
|
+
getState(name) {
|
|
86
|
+
if (!this.contexts.has(name)) {
|
|
87
|
+
slice.logger.logError('ContextManager', `El contexto "${name}" no existe`);
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return this.contexts.get(name).state;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// ============================================
|
|
95
|
+
// ACTUALIZAR ESTADO
|
|
96
|
+
// ============================================
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Actualizar el estado de un contexto
|
|
100
|
+
* @param {string} name - Nombre del contexto
|
|
101
|
+
* @param {Object|Function} updater - Nuevo estado o función (prevState) => newState
|
|
102
|
+
*
|
|
103
|
+
* @example
|
|
104
|
+
* // Reemplazar con objeto
|
|
105
|
+
* slice.context.setState('auth', {
|
|
106
|
+
* isLoggedIn: true,
|
|
107
|
+
* user: { name: 'Juan' }
|
|
108
|
+
* });
|
|
109
|
+
*
|
|
110
|
+
* // Usar función para acceder al estado anterior
|
|
111
|
+
* slice.context.setState('cart', (prev) => ({
|
|
112
|
+
* ...prev,
|
|
113
|
+
* items: [...prev.items, nuevoProducto],
|
|
114
|
+
* total: prev.total + nuevoProducto.price
|
|
115
|
+
* }));
|
|
116
|
+
*/
|
|
117
|
+
setState(name, updater) {
|
|
118
|
+
if (!this.contexts.has(name)) {
|
|
119
|
+
slice.logger.logError('ContextManager', `El contexto "${name}" no existe`);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const context = this.contexts.get(name);
|
|
124
|
+
const prevState = context.state;
|
|
125
|
+
|
|
126
|
+
// Calcular nuevo estado
|
|
127
|
+
let newState;
|
|
128
|
+
if (typeof updater === 'function') {
|
|
129
|
+
newState = updater(prevState);
|
|
130
|
+
} else {
|
|
131
|
+
newState = updater;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Guardar nuevo estado
|
|
135
|
+
context.state = newState;
|
|
136
|
+
|
|
137
|
+
// Persistir si está habilitado
|
|
138
|
+
if (context.options.persist) {
|
|
139
|
+
this._saveToStorage(name, newState, context.options.storageKey);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// Emitir evento para notificar a los watchers
|
|
143
|
+
slice.events.emit(`context:${name}`, newState, prevState);
|
|
144
|
+
|
|
145
|
+
slice.logger.logInfo('ContextManager', `Contexto "${name}" actualizado`);
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// ============================================
|
|
149
|
+
// WATCH (OBSERVAR CAMBIOS)
|
|
150
|
+
// ============================================
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Observar cambios en un contexto
|
|
154
|
+
* @param {string} name - Nombre del contexto
|
|
155
|
+
* @param {HTMLElement} component - Componente Slice para auto-cleanup
|
|
156
|
+
* @param {Function} callback - Función a ejecutar cuando cambia
|
|
157
|
+
* @param {Function} selector - Opcional. Función para seleccionar campos específicos
|
|
158
|
+
* @returns {string} subscriptionId
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* // Observar todo el estado
|
|
162
|
+
* slice.context.watch('auth', this, (state) => {
|
|
163
|
+
* this.render(state);
|
|
164
|
+
* });
|
|
165
|
+
*
|
|
166
|
+
* // Observar un campo específico
|
|
167
|
+
* slice.context.watch('auth', this, (name) => {
|
|
168
|
+
* this.$name.textContent = name;
|
|
169
|
+
* }, state => state.user.name);
|
|
170
|
+
*
|
|
171
|
+
* // Observar múltiples campos
|
|
172
|
+
* slice.context.watch('auth', this, (data) => {
|
|
173
|
+
* this.$name.textContent = data.name;
|
|
174
|
+
* this.$avatar.src = data.avatar;
|
|
175
|
+
* }, state => ({
|
|
176
|
+
* name: state.user.name,
|
|
177
|
+
* avatar: state.user.avatar
|
|
178
|
+
* }));
|
|
179
|
+
*
|
|
180
|
+
* // Valores computados
|
|
181
|
+
* slice.context.watch('cart', this, (total) => {
|
|
182
|
+
* this.$total.textContent = `$${total}`;
|
|
183
|
+
* }, state => state.items.reduce((sum, i) => sum + i.price, 0));
|
|
184
|
+
*/
|
|
185
|
+
watch(name, component, callback, selector = null) {
|
|
186
|
+
if (!this.contexts.has(name)) {
|
|
187
|
+
slice.logger.logError('ContextManager', `El contexto "${name}" no existe`);
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (!component?.sliceId) {
|
|
192
|
+
slice.logger.logError('ContextManager', 'watch() requiere un componente Slice válido');
|
|
193
|
+
return null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (typeof callback !== 'function') {
|
|
197
|
+
slice.logger.logError('ContextManager', 'El callback debe ser una función');
|
|
198
|
+
return null;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Guardar el valor anterior del selector para comparar
|
|
202
|
+
let lastSelectedValue = selector ? this._getSelectedValue(name, selector) : this.getState(name);
|
|
203
|
+
|
|
204
|
+
// Crear wrapper que aplica el selector y compara
|
|
205
|
+
const wrappedCallback = (newState, prevState) => {
|
|
206
|
+
if (selector) {
|
|
207
|
+
const newSelectedValue = this._applySelector(newState, selector);
|
|
208
|
+
const prevSelectedValue = this._applySelector(prevState, selector);
|
|
209
|
+
|
|
210
|
+
// Solo ejecutar si el valor seleccionado cambió
|
|
211
|
+
if (!this._isEqual(newSelectedValue, prevSelectedValue)) {
|
|
212
|
+
lastSelectedValue = newSelectedValue;
|
|
213
|
+
callback(newSelectedValue);
|
|
214
|
+
}
|
|
215
|
+
} else {
|
|
216
|
+
// Sin selector, siempre ejecutar
|
|
217
|
+
callback(newState);
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
// Suscribirse al evento del contexto
|
|
222
|
+
const subscriptionId = slice.events.subscribe(`context:${name}`, wrappedCallback, { component });
|
|
223
|
+
|
|
224
|
+
slice.logger.logInfo('ContextManager', `Watch registrado en "${name}" para ${component.sliceId}`);
|
|
225
|
+
|
|
226
|
+
return subscriptionId;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// ============================================
|
|
230
|
+
// UTILIDADES
|
|
231
|
+
// ============================================
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Verificar si un contexto existe
|
|
235
|
+
* @param {string} name - Nombre del contexto
|
|
236
|
+
* @returns {boolean}
|
|
237
|
+
*/
|
|
238
|
+
has(name) {
|
|
239
|
+
return this.contexts.has(name);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Eliminar un contexto
|
|
244
|
+
* @param {string} name - Nombre del contexto
|
|
245
|
+
* @returns {boolean}
|
|
246
|
+
*/
|
|
247
|
+
destroy(name) {
|
|
248
|
+
if (!this.contexts.has(name)) {
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const context = this.contexts.get(name);
|
|
253
|
+
|
|
254
|
+
// Limpiar storage si existe
|
|
255
|
+
if (context.options.persist) {
|
|
256
|
+
this._removeFromStorage(context.options.storageKey);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
this.contexts.delete(name);
|
|
260
|
+
|
|
261
|
+
slice.logger.logInfo('ContextManager', `Contexto "${name}" eliminado`);
|
|
262
|
+
|
|
263
|
+
return true;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/**
|
|
267
|
+
* Obtener lista de todos los contextos
|
|
268
|
+
* @returns {Array<string>}
|
|
269
|
+
*/
|
|
270
|
+
list() {
|
|
271
|
+
return Array.from(this.contexts.keys());
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// ============================================
|
|
275
|
+
// MÉTODOS PRIVADOS
|
|
276
|
+
// ============================================
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Aplicar selector al estado
|
|
280
|
+
*/
|
|
281
|
+
_applySelector(state, selector) {
|
|
282
|
+
try {
|
|
283
|
+
return selector(state);
|
|
284
|
+
} catch (error) {
|
|
285
|
+
slice.logger.logWarning('ContextManager', 'Error al aplicar selector', error);
|
|
286
|
+
return undefined;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
/**
|
|
291
|
+
* Obtener valor seleccionado del estado actual
|
|
292
|
+
*/
|
|
293
|
+
_getSelectedValue(name, selector) {
|
|
294
|
+
const state = this.getState(name);
|
|
295
|
+
return this._applySelector(state, selector);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* Comparar dos valores (shallow)
|
|
300
|
+
*/
|
|
301
|
+
_isEqual(a, b) {
|
|
302
|
+
// Mismo valor primitivo o referencia
|
|
303
|
+
if (a === b) return true;
|
|
304
|
+
|
|
305
|
+
// Si alguno es null/undefined
|
|
306
|
+
if (a == null || b == null) return false;
|
|
307
|
+
|
|
308
|
+
// Si no son objetos, ya sabemos que son diferentes
|
|
309
|
+
if (typeof a !== 'object' || typeof b !== 'object') return false;
|
|
310
|
+
|
|
311
|
+
// Comparación shallow de objetos
|
|
312
|
+
const keysA = Object.keys(a);
|
|
313
|
+
const keysB = Object.keys(b);
|
|
314
|
+
|
|
315
|
+
if (keysA.length !== keysB.length) return false;
|
|
316
|
+
|
|
317
|
+
for (const key of keysA) {
|
|
318
|
+
if (a[key] !== b[key]) return false;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return true;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Cargar estado desde localStorage
|
|
326
|
+
*/
|
|
327
|
+
_loadFromStorage(name) {
|
|
328
|
+
try {
|
|
329
|
+
const key = `slice_context_${name}`;
|
|
330
|
+
const data = localStorage.getItem(key);
|
|
331
|
+
if (data) {
|
|
332
|
+
return JSON.parse(data);
|
|
333
|
+
}
|
|
334
|
+
} catch (error) {
|
|
335
|
+
slice.logger.logWarning('ContextManager', `Error cargando "${name}" de localStorage`, error);
|
|
336
|
+
}
|
|
337
|
+
return null;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
/**
|
|
341
|
+
* Guardar estado en localStorage
|
|
342
|
+
*/
|
|
343
|
+
_saveToStorage(name, state, storageKey) {
|
|
344
|
+
try {
|
|
345
|
+
localStorage.setItem(storageKey, JSON.stringify(state));
|
|
346
|
+
} catch (error) {
|
|
347
|
+
slice.logger.logWarning('ContextManager', `Error guardando "${name}" en localStorage`, error);
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
/**
|
|
352
|
+
* Eliminar estado de localStorage
|
|
353
|
+
*/
|
|
354
|
+
_removeFromStorage(storageKey) {
|
|
355
|
+
try {
|
|
356
|
+
localStorage.removeItem(storageKey);
|
|
357
|
+
} catch (error) {
|
|
358
|
+
// Ignorar errores al eliminar
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
}
|