@apia/dom-store 1.0.4 → 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.
package/dist/index.d.ts CHANGED
@@ -2,224 +2,225 @@ import { RefObject } from 'react';
2
2
  import { Draft } from 'immer';
3
3
  export { Draft } from 'immer';
4
4
 
5
- /**
6
- * Las acciones reciben este objeto como terecer parámetro.
7
- *
8
- * Sirve para decidir cuáles serán los keys afectados por la ejecución
9
- * exitosa de la acción actual, de esta forma se evita la necesidad de
10
- * iterar sobre cada elemento ejecutando acciones selectoras y
11
- * haciendo comparación entre la selección actual y la anterior.
12
- *
13
- * Si este objeto no es utilizado en una acción, se seguirá el
14
- * comportamiento por defecto que es recorrer todas las keys del
15
- * store.
16
- */
17
- type TKeysDefine = {
18
- /**
19
- * Acepta un método que será llamado con el conjunto de todas las
20
- * keys y deberá responder con las keys que deben ser afectadas.
21
- */
22
- filter: (filterCallback: Parameters<string[]['filter']>[0]) => void;
23
- /**
24
- * Agrega keys al array de búsqueda. La primera vez que se llama, se
25
- * agregan sobre un array vacío.
26
- */
27
- push: (...newKeys: string[]) => void;
28
- /**
29
- * Acepta un array de keys que serán las que se recorrerán en
30
- * la propagación del nuevo estado.
31
- */
32
- set: (newKeys: string[]) => void;
33
- };
34
- /**
35
- * Las operaciones son métodos que alteran el estado de alguna manera.
36
- *
37
- * Idealmente, cada operación indica qué keys afectó, de forma que no
38
- * sea necesario realizar comparaciones para saber qué elementos deben
39
- * ser modificados dentro del store.
40
- *
41
- * Cada operación recibe state que es un drat de Immer, de igual manera
42
- * como lo hacen los reducers de createSlice de Redux-toolkit.
43
- *
44
- * El payload es arbitrario.
45
- *
46
- * defineKeys es un objeto que contiene distintos métodos que permiten
47
- * alterar el listado de keys que serán iteradas para notificar del
48
- * cambio de estado.
49
- */
50
- type TOperation<State, Payload> = (state: Draft<State>, payload: Payload, defineKeys: TKeysDefine) => void;
51
- /**
52
- * Representa el conjunto de todas las operaciones de un store.
53
- */
54
- type TOperations<State> = Record<string, TOperation<State, any>>;
55
- /**
56
- * Conjunto de elementos que distinguen a cada tipo de elemento del
57
- * store. Se toma a partir de la definición del objeto distinctors
58
- * del método create.
59
- */
60
- type TDistinctions<Distinctors extends TDistinctors<any>, K extends keyof Distinctors> = Parameters<Distinctors[K][0]>[0];
61
- /**
62
- * Es el hook encargado de registrar los callbacks necesarios a los
63
- * eventos que corresponda de forma de garantizar que las propiedades
64
- * se apliquen sobre el elemento que corresponda.
65
- */
66
- type TUseProperties<State, Distinctors extends TDistinctors<State>> = <RefType, K extends keyof Distinctors = keyof Distinctors>(which: K, distinctions: TDistinctions<Distinctors, K>, comparator?: (prevSelection: TDistinctorProperties, newSelection: TDistinctorProperties) => boolean) => RefObject<RefType>;
67
- type TStateChangeListener<State> = (state: State, previousState: State) => unknown;
68
- /**
69
- * Permite obtener una copia del estado local
70
- */
71
- type TGetState<State> = () => State;
72
- /**
73
- * Permite registrar un callback que será llamado con cada actualización del
74
- * estado
75
- */
76
- type TRegisterStateChangeListener<State> = (callback: TStateChangeListener<State>) => () => void;
77
- /**
78
- * Es un método que dadas las distinciones de un elemento particular
79
- * construye un string que lo identifica.
80
- */
81
- type TKeyMaker<State, Distinctors extends TDistinctors<State> = TDistinctors<State>, Key extends keyof Distinctors = keyof Distinctors> = (distinctions: TDistinctions<Distinctors, Key>) => string;
82
- /**
83
- * Es un mapa que contiene un TKeyMaker por cada tipo de elemento.
84
- */
85
- type TKeysMaker<State, Distinctors extends TDistinctors<State>> = {
86
- [key in keyof Distinctors]: TKeyMaker<State, Distinctors, key>;
87
- };
88
- /**
89
- * Tipo que permite extraer el tipo del payload de una operación.
90
- */
91
- type TOperationParameter<Operation extends TOperation<any, any>> = Parameters<Operation>[1];
92
- /**
93
- * Representa una acción asociada a una operación. Es el método
94
- * que es llamado desde fuera del store para ejecutar una operación
95
- * y actualizar el estado. Como consecuencia de la ejecución de esta
96
- * acción, el estado será actualizado y se harán las notificaciones
97
- * y actualización de propiedades que correspondan en los elementos
98
- * afectados.
99
- */
100
- type TOperationAction<Payload> = (props: Payload extends void ? void : Payload) => void;
101
- /**
102
- * Objeto que contiene todas las acciones de un store.
103
- */
104
- type TActionsMap<State, Operations extends TOperations<State>> = {
105
- [Key in keyof Operations]: TOperationAction<TOperationParameter<Operations[Key]>>;
106
- };
107
- /**
108
- * Método que es llamado luego de que se actualizan los elementos
109
- * pertenecientes a un tipo del store.
110
- */
111
- type TAfterActionCallback<State> = (prevState: State, nextState: State) => unknown;
112
- type TClassListComposer = Partial<{
113
- add: string[];
114
- remove: string[];
115
- toggle: string[];
116
- }>;
117
- type TDatasetComposer = Partial<{
118
- add: Record<string, any>;
119
- remove: string[];
120
- }>;
121
- type TDistinctorProperties = Partial<{
122
- classList: TClassListComposer;
123
- dataset: TDatasetComposer;
124
- etc: Record<string, any>;
125
- styles: CSSStyleDeclaration;
126
- }>;
127
- /**
128
- * Objeto que representa un tipo de elemento del store.
129
- */
130
- type TDistinctor<State, Distinctions extends Record<string, any>> = [
131
- (distinctions: Distinctions, state: State) => TDistinctorProperties,
132
- TAfterActionCallback<State>
133
- ] | [(distinctions: Distinctions, state: State) => TDistinctorProperties];
134
- /**
135
- * Los distinctors determinan para cada tipo de elemento aceptado,
136
- * si dado un cambio en el estado del store, este elemento debe ser
137
- * actualizado o no
138
- * */
139
- type TDistinctors<State> = Record<string, TDistinctor<State, any>>;
140
- /**
141
- * Falta documentar, a grandes rasgos:
142
- *
143
- * Este store propone el máximo rendimiento: afectar solamente los registros
144
- * que sean estrictamente necesarios y no renderizar.
145
- *
146
- * Para lograr evitar el renderizado, el estado se guarda en internamente en el
147
- * store, pero también en el elemento asociado a cada registro. De esta manera,
148
- * cuando se actualiza el estado, se procesan los keys afectados, se genera el
149
- * estado para cada uno de ellos de acuerdo a su distintor correspondiente y se
150
- * actualiza el DOM en el momento. Si por algún motivo, el componente afectado
151
- * vuelve a renderizar, el hook devuelve el estado actualizado, de forma de
152
- * evitar pérdida de información.
153
- *
154
- * @returns
155
- *
156
- * Al crear un store se devuelve un array compuesto por 3 elementos en el
157
- * siguiente orden:
158
- *
159
- * - acciones: Un mapa de métodos correspondientes a las operaciones
160
- * definidas.
161
- * - useProperties: Un hook utilizado para obtener las propiedades
162
- * de un elemento, de acuerdo a su distinción.
163
- * - getState: Un método que permite obtener el estado actual del store.
164
- *
165
- * @example
166
- *
167
- *
168
- * const [actions, useProperties, getState, registerStateListener] =
169
- * createFAsomeStore({
170
- // Se puede utilizar un estado con estructura arbitraria
171
- initialState: {
172
- people: [],
173
- // El as ... es necesario para que typescript pueda realizar la inferencia
174
- // correctamente. Siempre que se cree un store se debe seguir la estructura
175
- // propuesta en este ejemplo
176
- } as { people: { name: string }[] },
177
- // Los distinguidores "distinctors" establecen qué tipos de elementos existen
178
- // dentro del store y qué estado utiliza cada uno de ellos
179
- distinctors: {
180
- person: [
181
- // El tipado asignado al parámetro distinctions será tomado por el store
182
- // para pasarlo luego al keymaker a la hora de seleccionar un registro del
183
- // store
184
- (distinctions: { name: string }, state) => {
185
- return {
186
- name: state.people.find(
187
- (current) => current.name === distinctions.name,
188
- ),
189
- };
190
- },
191
- ],
192
- },
193
- // Los keymakers se encargan de generar claves únicas para cada elemento del
194
- // store
195
- keysMakers: {
196
- person: (distinctions) => {
197
- // Debe crear una key única dentro del store
198
- return distinctions.name;
199
- },
200
- },
201
- // Los operadores permiten alterar el estado actual
202
- operations: {
203
- addPerson(state, payload: { name: string }, affectedKeys) {
204
- // El estado se altera de cualquier forma que sea conveniente
205
- state.people.push({ name: payload.name });
206
- // Este key debe ser idéntico al generado por el keyMaker de person (Más
207
- // arriba)
208
- affectedKeys.set([payload.name]);
209
- },
210
- },
211
- });
212
- */
213
- declare function createFAsomeStore<State, Distinctors extends TDistinctors<State> = TDistinctors<State>, Operations extends TOperations<State> = TOperations<State>>({ initialState, operations, distinctors, keysMakers, }: {
214
- initialState: State;
215
- operations: Operations;
216
- distinctors: Distinctors;
217
- keysMakers: TKeysMaker<State, Distinctors>;
218
- }): [
219
- TActionsMap<State, Operations>,
220
- TUseProperties<State, Distinctors>,
221
- TGetState<State>,
222
- TRegisterStateChangeListener<State>
5
+ /**
6
+ * Las acciones reciben este objeto como terecer parámetro.
7
+ *
8
+ * Sirve para decidir cuáles serán los keys afectados por la ejecución
9
+ * exitosa de la acción actual, de esta forma se evita la necesidad de
10
+ * iterar sobre cada elemento ejecutando acciones selectoras y
11
+ * haciendo comparación entre la selección actual y la anterior.
12
+ *
13
+ * Si este objeto no es utilizado en una acción, se seguirá el
14
+ * comportamiento por defecto que es recorrer todas las keys del
15
+ * store.
16
+ */
17
+ type TKeysDefine = {
18
+ /**
19
+ * Acepta un método que será llamado con el conjunto de todas las
20
+ * keys y deberá responder con las keys que deben ser afectadas.
21
+ */
22
+ filter: (filterCallback: Parameters<string[]['filter']>[0]) => void;
23
+ /**
24
+ * Agrega keys al array de búsqueda. La primera vez que se llama, se
25
+ * agregan sobre un array vacío.
26
+ */
27
+ push: (...newKeys: string[]) => void;
28
+ /**
29
+ * Acepta un array de keys que serán las que se recorrerán en
30
+ * la propagación del nuevo estado.
31
+ */
32
+ set: (newKeys: string[]) => void;
33
+ };
34
+ /**
35
+ * Las operaciones son métodos que alteran el estado de alguna manera.
36
+ *
37
+ * Idealmente, cada operación indica qué keys afectó, de forma que no
38
+ * sea necesario realizar comparaciones para saber qué elementos deben
39
+ * ser modificados dentro del store.
40
+ *
41
+ * Cada operación recibe state que es un drat de Immer, de igual manera
42
+ * como lo hacen los reducers de createSlice de Redux-toolkit.
43
+ *
44
+ * El payload es arbitrario.
45
+ *
46
+ * defineKeys es un objeto que contiene distintos métodos que permiten
47
+ * alterar el listado de keys que serán iteradas para notificar del
48
+ * cambio de estado.
49
+ */
50
+ type TOperation<State, Payload> = (state: Draft<State>, payload: Payload, defineKeys: TKeysDefine) => void;
51
+ /**
52
+ * Representa el conjunto de todas las operaciones de un store.
53
+ */
54
+ type TOperations<State> = Record<string, TOperation<State, any>>;
55
+ /**
56
+ * Conjunto de elementos que distinguen a cada tipo de elemento del
57
+ * store. Se toma a partir de la definición del objeto distinctors
58
+ * del método create.
59
+ */
60
+ type TDistinctions<Distinctors extends TDistinctors<any>, K extends keyof Distinctors> = Parameters<Distinctors[K][0]>[0];
61
+ /**
62
+ * Es el hook encargado de registrar los callbacks necesarios a los
63
+ * eventos que corresponda de forma de garantizar que las propiedades
64
+ * se apliquen sobre el elemento que corresponda.
65
+ */
66
+ type TUseProperties<State, Distinctors extends TDistinctors<State>> = <RefType, K extends keyof Distinctors = keyof Distinctors>(which: K, distinctions: TDistinctions<Distinctors, K>, comparator?: (prevSelection: TDistinctorProperties, newSelection: TDistinctorProperties) => boolean) => RefObject<RefType>;
67
+ type TStateChangeListener<State> = (state: State, previousState: State) => unknown;
68
+ /**
69
+ * Permite obtener una copia del estado local
70
+ */
71
+ type TGetState<State> = () => State;
72
+ /**
73
+ * Permite registrar un callback que será llamado con cada actualización del
74
+ * estado
75
+ */
76
+ type TRegisterStateChangeListener<State> = (callback: TStateChangeListener<State>) => () => void;
77
+ /**
78
+ * Es un método que dadas las distinciones de un elemento particular
79
+ * construye un string que lo identifica.
80
+ */
81
+ type TKeyMaker<State, Distinctors extends TDistinctors<State> = TDistinctors<State>, Key extends keyof Distinctors = keyof Distinctors> = (distinctions: TDistinctions<Distinctors, Key>) => string;
82
+ /**
83
+ * Es un mapa que contiene un TKeyMaker por cada tipo de elemento.
84
+ */
85
+ type TKeysMaker<State, Distinctors extends TDistinctors<State>> = {
86
+ [key in keyof Distinctors]: TKeyMaker<State, Distinctors, key>;
87
+ };
88
+ /**
89
+ * Tipo que permite extraer el tipo del payload de una operación.
90
+ */
91
+ type TOperationParameter<Operation extends TOperation<any, any>> = Parameters<Operation>[1];
92
+ /**
93
+ * Representa una acción asociada a una operación. Es el método
94
+ * que es llamado desde fuera del store para ejecutar una operación
95
+ * y actualizar el estado. Como consecuencia de la ejecución de esta
96
+ * acción, el estado será actualizado y se harán las notificaciones
97
+ * y actualización de propiedades que correspondan en los elementos
98
+ * afectados.
99
+ */
100
+ type TOperationAction<Payload> = (props: Payload extends void ? void : Payload) => void;
101
+ /**
102
+ * Objeto que contiene todas las acciones de un store.
103
+ */
104
+ type TActionsMap<State, Operations extends TOperations<State>> = {
105
+ [Key in keyof Operations]: TOperationAction<TOperationParameter<Operations[Key]>>;
106
+ };
107
+ /**
108
+ * Método que es llamado luego de que se actualizan los elementos
109
+ * pertenecientes a un tipo del store.
110
+ */
111
+ type TAfterActionCallback<State> = (prevState: State, nextState: State) => unknown;
112
+ type TClassListComposer = Partial<{
113
+ add: string[];
114
+ remove: string[];
115
+ toggle: string[];
116
+ }>;
117
+ type TDatasetComposer = Partial<{
118
+ add: Record<string, any>;
119
+ remove: string[];
120
+ }>;
121
+ type TDistinctorProperties = Partial<{
122
+ classList: TClassListComposer;
123
+ dataset: TDatasetComposer;
124
+ etc: Record<string, any>;
125
+ styles: CSSStyleDeclaration;
126
+ }>;
127
+ /**
128
+ * Objeto que representa un tipo de elemento del store.
129
+ */
130
+ type TDistinctor<State, Distinctions extends Record<string, any>> = [
131
+ (distinctions: Distinctions, state: State) => TDistinctorProperties,
132
+ TAfterActionCallback<State>
133
+ ] | [(distinctions: Distinctions, state: State) => TDistinctorProperties];
134
+ /**
135
+ * Los distinctors determinan para cada tipo de elemento aceptado,
136
+ * si dado un cambio en el estado del store, este elemento debe ser
137
+ * actualizado o no
138
+ * */
139
+ type TDistinctors<State> = Record<string, TDistinctor<State, any>>;
140
+ /**
141
+ * Falta documentar, a grandes rasgos:
142
+ *
143
+ * Este store propone el máximo rendimiento: afectar solamente los registros
144
+ * que sean estrictamente necesarios y no renderizar.
145
+ *
146
+ * Para lograr evitar el renderizado, el estado se guarda en internamente en el
147
+ * store, pero también en el elemento asociado a cada registro. De esta manera,
148
+ * cuando se actualiza el estado, se procesan los keys afectados, se genera el
149
+ * estado para cada uno de ellos de acuerdo a su distintor correspondiente y se
150
+ * actualiza el DOM en el momento. Si por algún motivo, el componente afectado
151
+ * vuelve a renderizar, el hook devuelve el estado actualizado, de forma de
152
+ * evitar pérdida de información.
153
+ *
154
+ * @returns
155
+ *
156
+ * Al crear un store se devuelve un array compuesto por 3 elementos en el
157
+ * siguiente orden:
158
+ *
159
+ * - acciones: Un mapa de métodos correspondientes a las operaciones
160
+ * definidas.
161
+ * - useProperties: Un hook utilizado para obtener las propiedades
162
+ * de un elemento, de acuerdo a su distinción.
163
+ * - getState: Un método que permite obtener el estado actual del store.
164
+ *
165
+ * @example
166
+ *
167
+ *
168
+ * const [actions, useProperties, getState, registerStateListener] =
169
+ * createFAsomeStore({
170
+ // Se puede utilizar un estado con estructura arbitraria
171
+ initialState: {
172
+ people: [],
173
+ // El as ... es necesario para que typescript pueda realizar la inferencia
174
+ // correctamente. Siempre que se cree un store se debe seguir la estructura
175
+ // propuesta en este ejemplo
176
+ } as { people: { name: string }[] },
177
+ // Los distinguidores "distinctors" establecen qué tipos de elementos existen
178
+ // dentro del store y qué estado utiliza cada uno de ellos
179
+ distinctors: {
180
+ person: [
181
+ // El tipado asignado al parámetro distinctions será tomado por el store
182
+ // para pasarlo luego al keymaker a la hora de seleccionar un registro del
183
+ // store
184
+ (distinctions: { name: string }, state) => {
185
+ return {
186
+ name: state.people.find(
187
+ (current) => current.name === distinctions.name,
188
+ ),
189
+ };
190
+ },
191
+ ],
192
+ },
193
+ // Los keymakers se encargan de generar claves únicas para cada elemento del
194
+ // store
195
+ keysMakers: {
196
+ person: (distinctions) => {
197
+ // Debe crear una key única dentro del store
198
+ return distinctions.name;
199
+ },
200
+ },
201
+ // Los operadores permiten alterar el estado actual
202
+ operations: {
203
+ addPerson(state, payload: { name: string }, affectedKeys) {
204
+ // El estado se altera de cualquier forma que sea conveniente
205
+ state.people.push({ name: payload.name });
206
+ // Este key debe ser idéntico al generado por el keyMaker de person (Más
207
+ // arriba)
208
+ affectedKeys.set([payload.name]);
209
+ },
210
+ },
211
+ });
212
+ */
213
+ declare function createFAsomeStore<State, Distinctors extends TDistinctors<State> = TDistinctors<State>, Operations extends TOperations<State> = TOperations<State>>({ initialState, operations, distinctors, keysMakers, }: {
214
+ initialState: State;
215
+ operations: Operations;
216
+ distinctors: Distinctors;
217
+ keysMakers: TKeysMaker<State, Distinctors>;
218
+ }): [
219
+ TActionsMap<State, Operations>,
220
+ TUseProperties<State, Distinctors>,
221
+ TGetState<State>,
222
+ TRegisterStateChangeListener<State>
223
223
  ];
224
224
 
225
- export { TActionsMap, TClassListComposer, TDatasetComposer, TDistinctorProperties, TDistinctors, TGetState, TKeysDefine, TKeysMaker, TOperations, TRegisterStateChangeListener, TStateChangeListener, TUseProperties, createFAsomeStore };
225
+ export { type TActionsMap, type TClassListComposer, type TDatasetComposer, type TDistinctorProperties, type TDistinctors, type TGetState, type TKeysDefine, type TKeysMaker, type TOperations, type TRegisterStateChangeListener, type TStateChangeListener, type TUseProperties, createFAsomeStore };
226
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,36 +1,35 @@
1
1
  import { useRef, useCallback, useEffect } from 'react';
2
2
  import { produce } from 'immer';
3
- import { cloneDeep } from 'lodash';
3
+ import cloneDeep from 'lodash-es/cloneDeep';
4
4
 
5
5
  function setAriaAttributes(element, attribute, value) {
6
6
  element.setAttribute(attribute, value);
7
7
  }
8
8
  function applyProperties(element, props) {
9
- var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l;
10
9
  if (!element || !(element instanceof HTMLElement))
11
10
  return;
12
- ((_b = (_a = props.classList) == null ? void 0 : _a.add) != null ? _b : []).forEach((current) => {
11
+ (props.classList?.add ?? []).forEach((current) => {
13
12
  if (current)
14
13
  element.classList.add(current);
15
14
  });
16
- ((_d = (_c = props.classList) == null ? void 0 : _c.remove) != null ? _d : []).forEach((current) => {
15
+ (props.classList?.remove ?? []).forEach((current) => {
17
16
  if (current)
18
17
  element.classList.remove(current);
19
18
  });
20
- ((_f = (_e = props.classList) == null ? void 0 : _e.toggle) != null ? _f : []).forEach((current) => {
19
+ (props.classList?.toggle ?? []).forEach((current) => {
21
20
  if (current)
22
21
  element.classList.toggle(current);
23
22
  });
24
- Object.entries((_h = (_g = props.dataset) == null ? void 0 : _g.add) != null ? _h : {}).forEach(([key, value]) => {
23
+ Object.entries(props.dataset?.add ?? {}).forEach(([key, value]) => {
25
24
  element.dataset[key] = value;
26
25
  });
27
- ((_j = (_i = props.dataset) == null ? void 0 : _i.remove) != null ? _j : []).forEach(
26
+ (props.dataset?.remove ?? []).forEach(
28
27
  (current) => delete element.dataset[current]
29
28
  );
30
- Object.entries((_k = props.styles) != null ? _k : {}).forEach(([prop, value]) => {
29
+ Object.entries(props.styles ?? {}).forEach(([prop, value]) => {
31
30
  element.style[prop] = value;
32
31
  });
33
- Object.entries((_l = props.etc) != null ? _l : {}).forEach(([prop, value]) => {
32
+ Object.entries(props.etc ?? {}).forEach(([prop, value]) => {
34
33
  if (value === void 0) {
35
34
  delete element[prop];
36
35
  return;
@@ -54,12 +53,11 @@ function createFAsomeStore({
54
53
  const callbacks = {};
55
54
  const keysMap = /* @__PURE__ */ new Map();
56
55
  function registerCallback(which, distinctions, callback) {
57
- var _a;
58
56
  if (!callbacks[which]) {
59
57
  callbacks[which] = /* @__PURE__ */ new Map();
60
58
  }
61
59
  const key = keysMakers[which](distinctions);
62
- keysMap.set(key, ((_a = keysMap.get(key)) != null ? _a : 0) + 1);
60
+ keysMap.set(key, (keysMap.get(key) ?? 0) + 1);
63
61
  callbacks[which].set(key, callback);
64
62
  return () => {
65
63
  callbacks[which].delete(key);
@@ -114,12 +112,10 @@ function createFAsomeStore({
114
112
  current(nextState, state);
115
113
  });
116
114
  Object.keys(callbacks).forEach((which) => {
117
- var _a, _b;
118
115
  actualKeys.forEach((key) => {
119
- var _a2;
120
- (_a2 = callbacks[which].get(key)) == null ? void 0 : _a2(nextState);
116
+ callbacks[which].get(key)?.(nextState);
121
117
  });
122
- (_b = (_a = distinctors[which])[1]) == null ? void 0 : _b.call(_a, state, nextState);
118
+ distinctors[which][1]?.(state, nextState);
123
119
  });
124
120
  state = nextState;
125
121
  }
@@ -167,3 +163,4 @@ function createFAsomeStore({
167
163
  }
168
164
 
169
165
  export { createFAsomeStore };
166
+ //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-dynamic-delete */\r\n/* eslint-disable no-param-reassign */\r\n/* eslint-disable @typescript-eslint/no-explicit-any */\r\nimport {\r\n useEffect,\r\n useRef,\r\n RefObject,\r\n useCallback,\r\n MutableRefObject,\r\n} from 'react';\r\nimport { Draft, produce } from 'immer';\r\nimport { cloneDeep } from 'lodash';\r\n\r\n/**\r\n * Las acciones reciben este objeto como terecer parámetro.\r\n *\r\n * Sirve para decidir cuáles serán los keys afectados por la ejecución\r\n * exitosa de la acción actual, de esta forma se evita la necesidad de\r\n * iterar sobre cada elemento ejecutando acciones selectoras y\r\n * haciendo comparación entre la selección actual y la anterior.\r\n *\r\n * Si este objeto no es utilizado en una acción, se seguirá el\r\n * comportamiento por defecto que es recorrer todas las keys del\r\n * store.\r\n */\r\nexport type TKeysDefine = {\r\n /**\r\n * Acepta un método que será llamado con el conjunto de todas las\r\n * keys y deberá responder con las keys que deben ser afectadas.\r\n */\r\n filter: (filterCallback: Parameters<string[]['filter']>[0]) => void;\r\n /**\r\n * Agrega keys al array de búsqueda. La primera vez que se llama, se\r\n * agregan sobre un array vacío.\r\n */\r\n push: (...newKeys: string[]) => void;\r\n /**\r\n * Acepta un array de keys que serán las que se recorrerán en\r\n * la propagación del nuevo estado.\r\n */\r\n set: (newKeys: string[]) => void;\r\n};\r\n\r\n/**\r\n * Las operaciones son métodos que alteran el estado de alguna manera.\r\n *\r\n * Idealmente, cada operación indica qué keys afectó, de forma que no\r\n * sea necesario realizar comparaciones para saber qué elementos deben\r\n * ser modificados dentro del store.\r\n *\r\n * Cada operación recibe state que es un drat de Immer, de igual manera\r\n * como lo hacen los reducers de createSlice de Redux-toolkit.\r\n *\r\n * El payload es arbitrario.\r\n *\r\n * defineKeys es un objeto que contiene distintos métodos que permiten\r\n * alterar el listado de keys que serán iteradas para notificar del\r\n * cambio de estado.\r\n */\r\ntype TOperation<State, Payload> = (\r\n state: Draft<State>,\r\n payload: Payload,\r\n defineKeys: TKeysDefine,\r\n) => void;\r\n\r\n/**\r\n * Representa el conjunto de todas las operaciones de un store.\r\n */\r\nexport type TOperations<State> = Record<string, TOperation<State, any>>;\r\n\r\n/**\r\n * Conjunto de elementos que distinguen a cada tipo de elemento del\r\n * store. Se toma a partir de la definición del objeto distinctors\r\n * del método create.\r\n */\r\ntype TDistinctions<\r\n Distinctors extends TDistinctors<any>,\r\n K extends keyof Distinctors,\r\n> = Parameters<Distinctors[K][0]>[0];\r\n\r\n/**\r\n * Es el hook encargado de registrar los callbacks necesarios a los\r\n * eventos que corresponda de forma de garantizar que las propiedades\r\n * se apliquen sobre el elemento que corresponda.\r\n */\r\nexport type TUseProperties<State, Distinctors extends TDistinctors<State>> = <\r\n RefType,\r\n K extends keyof Distinctors = keyof Distinctors,\r\n>(\r\n which: K,\r\n distinctions: TDistinctions<Distinctors, K>,\r\n comparator?: (\r\n prevSelection: TDistinctorProperties,\r\n newSelection: TDistinctorProperties,\r\n ) => boolean,\r\n) => RefObject<RefType>;\r\n\r\nexport type TStateChangeListener<State> = (\r\n state: State,\r\n previousState: State,\r\n) => unknown;\r\n\r\n/**\r\n * Permite obtener una copia del estado local\r\n */\r\nexport type TGetState<State> = () => State;\r\n\r\n/**\r\n * Permite registrar un callback que será llamado con cada actualización del\r\n * estado\r\n */\r\nexport type TRegisterStateChangeListener<State> = (\r\n callback: TStateChangeListener<State>,\r\n) => () => void;\r\n\r\n/**\r\n * Es un método que dadas las distinciones de un elemento particular\r\n * construye un string que lo identifica.\r\n */\r\ntype TKeyMaker<\r\n State,\r\n Distinctors extends TDistinctors<State> = TDistinctors<State>,\r\n Key extends keyof Distinctors = keyof Distinctors,\r\n> = (distinctions: TDistinctions<Distinctors, Key>) => string;\r\n\r\n/**\r\n * Es un mapa que contiene un TKeyMaker por cada tipo de elemento.\r\n */\r\nexport type TKeysMaker<State, Distinctors extends TDistinctors<State>> = {\r\n [key in keyof Distinctors]: TKeyMaker<State, Distinctors, key>;\r\n};\r\n\r\n/**\r\n * Tipo que permite extraer el tipo del payload de una operación.\r\n */\r\ntype TOperationParameter<Operation extends TOperation<any, any>> =\r\n Parameters<Operation>[1];\r\n\r\n/**\r\n * Representa una acción asociada a una operación. Es el método\r\n * que es llamado desde fuera del store para ejecutar una operación\r\n * y actualizar el estado. Como consecuencia de la ejecución de esta\r\n * acción, el estado será actualizado y se harán las notificaciones\r\n * y actualización de propiedades que correspondan en los elementos\r\n * afectados.\r\n */\r\ntype TOperationAction<Payload> = (\r\n props: Payload extends void ? void : Payload,\r\n) => void;\r\n\r\n/**\r\n * Objeto que contiene todas las acciones de un store.\r\n */\r\nexport type TActionsMap<State, Operations extends TOperations<State>> = {\r\n [Key in keyof Operations]: TOperationAction<\r\n TOperationParameter<Operations[Key]>\r\n >;\r\n};\r\n\r\n/**\r\n * Método que es llamado luego de que se actualizan los elementos\r\n * pertenecientes a un tipo del store.\r\n */\r\ntype TAfterActionCallback<State> = (\r\n prevState: State,\r\n nextState: State,\r\n) => unknown;\r\n\r\nexport type TClassListComposer = Partial<{\r\n add: string[];\r\n remove: string[];\r\n toggle: string[];\r\n}>;\r\n\r\nexport type TDatasetComposer = Partial<{\r\n add: Record<string, any>;\r\n remove: string[];\r\n}>;\r\n\r\nexport type TDistinctorProperties = Partial<{\r\n classList: TClassListComposer;\r\n dataset: TDatasetComposer;\r\n etc: Record<string, any>;\r\n styles: CSSStyleDeclaration;\r\n}>;\r\n\r\n/**\r\n * Objeto que representa un tipo de elemento del store.\r\n */\r\ntype TDistinctor<State, Distinctions extends Record<string, any>> =\r\n | [\r\n (distinctions: Distinctions, state: State) => TDistinctorProperties,\r\n TAfterActionCallback<State>,\r\n ]\r\n | [(distinctions: Distinctions, state: State) => TDistinctorProperties];\r\n\r\n/**\r\n * Los distinctors determinan para cada tipo de elemento aceptado,\r\n * si dado un cambio en el estado del store, este elemento debe ser\r\n * actualizado o no\r\n * */\r\nexport type TDistinctors<State> = Record<string, TDistinctor<State, any>>;\r\n\r\nfunction setAriaAttributes(\r\n element: HTMLElement,\r\n attribute: string,\r\n value: any,\r\n) {\r\n element.setAttribute(attribute, value as string);\r\n}\r\n\r\n/**\r\n * Representa los callbacks internos del store utilizados para comunicar\r\n * acerca del cambio de estado a los elementos correspondientes.\r\n */\r\ntype TInnerStateListener<State> = (currentState: State) => void;\r\n\r\nfunction applyProperties(element: HTMLElement, props: TDistinctorProperties) {\r\n if (!element || !(element instanceof HTMLElement)) return;\r\n\r\n (props.classList?.add ?? []).forEach((current) => {\r\n if (current) element.classList.add(current);\r\n });\r\n (props.classList?.remove ?? []).forEach((current) => {\r\n if (current) element.classList.remove(current);\r\n });\r\n (props.classList?.toggle ?? []).forEach((current) => {\r\n if (current) element.classList.toggle(current);\r\n });\r\n\r\n Object.entries(props.dataset?.add ?? {}).forEach(([key, value]) => {\r\n element.dataset[key] = value;\r\n });\r\n (props.dataset?.remove ?? []).forEach(\r\n (current) => delete element.dataset[current],\r\n );\r\n\r\n Object.entries(props.styles ?? {}).forEach(([prop, value]) => {\r\n (element.style[prop as unknown as number] as any) = value;\r\n });\r\n\r\n Object.entries(props.etc ?? {}).forEach(([prop, value]) => {\r\n if (value === undefined) {\r\n delete (element as Record<string, any>)[prop];\r\n return;\r\n }\r\n\r\n const match = prop.match(/^aria-(\\w+)$/);\r\n if (match) {\r\n setAriaAttributes(element, prop, value);\r\n return;\r\n }\r\n (element as Record<string, any>)[prop] = String(value);\r\n });\r\n}\r\n\r\n/**\r\n * Falta documentar, a grandes rasgos:\r\n * \r\n * Este store propone el máximo rendimiento: afectar solamente los registros\r\n * que sean estrictamente necesarios y no renderizar.\r\n * \r\n * Para lograr evitar el renderizado, el estado se guarda en internamente en el\r\n * store, pero también en el elemento asociado a cada registro. De esta manera,\r\n * cuando se actualiza el estado, se procesan los keys afectados, se genera el\r\n * estado para cada uno de ellos de acuerdo a su distintor correspondiente y se\r\n * actualiza el DOM en el momento. Si por algún motivo, el componente afectado\r\n * vuelve a renderizar, el hook devuelve el estado actualizado, de forma de\r\n * evitar pérdida de información.\r\n * \r\n * @returns\r\n * \r\n * Al crear un store se devuelve un array compuesto por 3 elementos en el\r\n * siguiente orden:\r\n * \r\n * - acciones: Un mapa de métodos correspondientes a las operaciones\r\n * definidas. \r\n * - useProperties: Un hook utilizado para obtener las propiedades\r\n * de un elemento, de acuerdo a su distinción.\r\n * - getState: Un método que permite obtener el estado actual del store.\r\n * \r\n * @example\r\n * \r\n * \r\n * const [actions, useProperties, getState, registerStateListener] =\r\n * createFAsomeStore({\r\n // Se puede utilizar un estado con estructura arbitraria\r\n initialState: {\r\n people: [],\r\n // El as ... es necesario para que typescript pueda realizar la inferencia\r\n // correctamente. Siempre que se cree un store se debe seguir la estructura\r\n // propuesta en este ejemplo\r\n } as { people: { name: string }[] },\r\n // Los distinguidores \"distinctors\" establecen qué tipos de elementos existen\r\n // dentro del store y qué estado utiliza cada uno de ellos\r\n distinctors: {\r\n person: [\r\n // El tipado asignado al parámetro distinctions será tomado por el store\r\n // para pasarlo luego al keymaker a la hora de seleccionar un registro del\r\n // store\r\n (distinctions: { name: string }, state) => {\r\n return {\r\n name: state.people.find(\r\n (current) => current.name === distinctions.name,\r\n ),\r\n };\r\n },\r\n ],\r\n },\r\n // Los keymakers se encargan de generar claves únicas para cada elemento del\r\n // store\r\n keysMakers: {\r\n person: (distinctions) => {\r\n // Debe crear una key única dentro del store\r\n return distinctions.name;\r\n },\r\n },\r\n // Los operadores permiten alterar el estado actual\r\n operations: {\r\n addPerson(state, payload: { name: string }, affectedKeys) {\r\n // El estado se altera de cualquier forma que sea conveniente\r\n state.people.push({ name: payload.name });\r\n // Este key debe ser idéntico al generado por el keyMaker de person (Más\r\n // arriba)\r\n affectedKeys.set([payload.name]);\r\n },\r\n },\r\n });\r\n */\r\nexport function createFAsomeStore<\r\n State,\r\n Distinctors extends TDistinctors<State> = TDistinctors<State>,\r\n Operations extends TOperations<State> = TOperations<State>,\r\n>({\r\n initialState,\r\n operations,\r\n distinctors,\r\n keysMakers,\r\n}: {\r\n initialState: State;\r\n operations: Operations;\r\n distinctors: Distinctors;\r\n keysMakers: TKeysMaker<State, Distinctors>;\r\n}): [\r\n TActionsMap<State, Operations>,\r\n TUseProperties<State, Distinctors>,\r\n TGetState<State>,\r\n TRegisterStateChangeListener<State>,\r\n] {\r\n const actions = {} as TActionsMap<State, Operations>;\r\n let state = initialState;\r\n\r\n const callbacks: Record<string, Map<string, TInnerStateListener<State>>> = {};\r\n const keysMap = new Map<string, number>();\r\n\r\n function registerCallback<K extends keyof Distinctors>(\r\n which: K,\r\n distinctions: TDistinctions<Distinctors, K>,\r\n callback: TInnerStateListener<State>,\r\n ) {\r\n if (!callbacks[which as string]) {\r\n callbacks[which as string] = new Map();\r\n }\r\n const key = keysMakers[which](distinctions);\r\n keysMap.set(key, (keysMap.get(key) ?? 0) + 1);\r\n callbacks[which as string].set(key, callback);\r\n\r\n return () => {\r\n callbacks[which as string].delete(key);\r\n keysMap.set(key, (keysMap.get(key) as number) - 1);\r\n if (keysMap.get(key) === 0) keysMap.delete(key);\r\n };\r\n }\r\n\r\n let stateListenersCallbacks: TStateChangeListener<State>[] = [];\r\n\r\n const registerStateListener: TRegisterStateChangeListener<State> = (\r\n callback: TStateChangeListener<State>,\r\n ) => {\r\n stateListenersCallbacks.push(callback);\r\n\r\n return () => {\r\n stateListenersCallbacks = stateListenersCallbacks.filter(\r\n (current) => current !== callback,\r\n );\r\n };\r\n };\r\n\r\n Object.entries(operations).forEach(([name, operation]) => {\r\n const action: TOperationAction<TOperationParameter<typeof operation>> = (\r\n props,\r\n ) => {\r\n let keys = Array.from(keysMap.keys()) as string[];\r\n const pushedKeys: Record<string, any> = {};\r\n let hasPushed = false;\r\n const nextState = produce(state, (state) =>\r\n operations[name](state, props, {\r\n filter(filterCallback) {\r\n if (hasPushed) {\r\n Object.keys(pushedKeys)\r\n .filter((current, ...e) => filterCallback(current, ...e))\r\n .forEach((current) => delete pushedKeys[current]);\r\n } else keys = keys.filter(filterCallback);\r\n },\r\n push(...newKeys) {\r\n if (!hasPushed) {\r\n hasPushed = true;\r\n }\r\n newKeys.forEach((current) => (pushedKeys[current] = true));\r\n },\r\n set(newKeys) {\r\n if (!hasPushed) {\r\n hasPushed = true;\r\n }\r\n newKeys.forEach((current) => (pushedKeys[current] = true));\r\n },\r\n }),\r\n );\r\n\r\n const actualKeys = hasPushed ? Object.keys(pushedKeys) : keys;\r\n hasPushed ? Object.keys(pushedKeys) : keys;\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n if ((window as any).debugDomStore) {\r\n console.clear();\r\n }\r\n if (nextState !== state) {\r\n stateListenersCallbacks.forEach((current) => {\r\n current(nextState, state);\r\n });\r\n Object.keys(callbacks).forEach((which) => {\r\n actualKeys.forEach((key) => {\r\n callbacks[which].get(key)?.(nextState);\r\n });\r\n distinctors[which][1]?.(state, nextState);\r\n });\r\n state = nextState;\r\n }\r\n };\r\n actions[name as keyof TActionsMap<State, Operations>] = action;\r\n });\r\n\r\n /**\r\n * Este hook permite recuperar el estado asociado a un elemento. \r\n * El siguiente ejemplo está tomado del componente Listbox de \r\n * **@apia/components**. En el mismo se puede ver que se toman las \r\n * props devueltas y se hacen spread sobre el elemento destino. \r\n * En este ejemplo, las acciones y el useListbox vienen por \r\n * contexto pero son exactamente los mismos devueltos por \r\n * createFAsomeStore.\r\n * \r\n * @example\r\n * \r\n * export const ListboxItem: FC<TListboxItem> = ({\r\n children,\r\n rowIndex: outerRowIndex,\r\n }) => {\r\n const { listboxActions, useListbox } = useContext(ListboxContext);\r\n const rowIndex = useMemo(() => outerRowIndex ?? -1, [outerRowIndex]);\r\n const props = useListbox<HTMLDivElement>('row', { rowIndex });\r\n\r\n return (\r\n <div\r\n {...props}\r\n onClick={useCallback(() => {\r\n listboxActions.updateSelectedRows({ newSelectedRows: [rowIndex] });\r\n }, [listboxActions, rowIndex])}\r\n >\r\n {children}\r\n </div>\r\n );\r\n };\r\n */\r\n const useProperties: TUseProperties<State, Distinctors> = <\r\n RefType,\r\n K extends keyof Distinctors = keyof Distinctors,\r\n >(\r\n which: K,\r\n distinctions: TDistinctions<Distinctors, K>,\r\n comparator: (\r\n prevSelection: TDistinctorProperties,\r\n newSelection: TDistinctorProperties,\r\n ) => boolean = (a, b) => a === b,\r\n ) => {\r\n const ref = useRef<RefType>(null);\r\n const returnRef = useCallback((el: RefType) => {\r\n if (el) {\r\n applyProperties(\r\n el as unknown as HTMLElement,\r\n previousSelection.current,\r\n );\r\n }\r\n (ref as MutableRefObject<RefType>).current = el;\r\n }, []) as unknown as MutableRefObject<RefType>;\r\n const previousSelection = useRef<TDistinctorProperties>(\r\n null as unknown as TDistinctorProperties,\r\n );\r\n if (previousSelection.current === null) {\r\n previousSelection.current = distinctors[which][0](\r\n distinctions,\r\n state,\r\n ) as TDistinctorProperties;\r\n }\r\n\r\n useEffect(() => {\r\n return registerCallback(which, distinctions, (current) => {\r\n const newState: TDistinctorProperties = distinctors[which][0](\r\n distinctions,\r\n current,\r\n );\r\n if (!comparator(previousSelection.current, newState)) {\r\n previousSelection.current = newState;\r\n applyProperties(ref.current as HTMLElement, newState);\r\n }\r\n });\r\n }, [comparator, distinctions, which]);\r\n\r\n return returnRef;\r\n };\r\n\r\n const getState = () => {\r\n return cloneDeep(state);\r\n };\r\n\r\n return [actions, useProperties, getState, registerStateListener];\r\n}\r\n\r\nexport type { Draft };\r\n"],"names":["state","_a"],"mappings":";;;;AA2MA,SAAS,iBAAA,CACP,OACA,EAAA,SAAA,EACA,KACA,EAAA;AACA,EAAQ,OAAA,CAAA,YAAA,CAAa,WAAW,KAAe,CAAA,CAAA;AACjD,CAAA;AAQA,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CAAA,OAAA,EAAS,QAAQ,CAAG,EAAA;AACpD,UAAA,iBAAA,CAAkB,OAAU,GAAA,QAAA,CAAA;AAC5B,UAAgB,eAAA,CAAA,GAAA,CAAI,SAAwB,QAAQ,CAAA,CAAA;AAAA,SACtD;AAAA,OACD,CAAA,CAAA;AAAA,KACA,EAAA,CAAC,UAAY,EAAA,YAAA,EAAc,KAAK,CAAC,CAAA,CAAA;AAEpC,IAAO,OAAA,SAAA,CAAA;AAAA,GACT,CAAA;AAEA,EAAA,MAAM,WAAW,MAAM;AACrB,IAAA,OAAO,UAAU,KAAK,CAAA,CAAA;AAAA,GACxB,CAAA;AAEA,EAAA,OAAO,CAAC,OAAA,EAAS,aAAe,EAAA,QAAA,EAAU,qBAAqB,CAAA,CAAA;AACjE;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-dynamic-delete */\r\n/* eslint-disable no-param-reassign */\r\n/* eslint-disable @typescript-eslint/no-explicit-any */\r\nimport {\r\n useEffect,\r\n useRef,\r\n RefObject,\r\n useCallback,\r\n MutableRefObject,\r\n} from 'react';\r\nimport { Draft, produce } from 'immer';\r\nimport cloneDeep from 'lodash-es/cloneDeep';\r\n\r\n/**\r\n * Las acciones reciben este objeto como terecer parámetro.\r\n *\r\n * Sirve para decidir cuáles serán los keys afectados por la ejecución\r\n * exitosa de la acción actual, de esta forma se evita la necesidad de\r\n * iterar sobre cada elemento ejecutando acciones selectoras y\r\n * haciendo comparación entre la selección actual y la anterior.\r\n *\r\n * Si este objeto no es utilizado en una acción, se seguirá el\r\n * comportamiento por defecto que es recorrer todas las keys del\r\n * store.\r\n */\r\nexport type TKeysDefine = {\r\n /**\r\n * Acepta un método que será llamado con el conjunto de todas las\r\n * keys y deberá responder con las keys que deben ser afectadas.\r\n */\r\n filter: (filterCallback: Parameters<string[]['filter']>[0]) => void;\r\n /**\r\n * Agrega keys al array de búsqueda. La primera vez que se llama, se\r\n * agregan sobre un array vacío.\r\n */\r\n push: (...newKeys: string[]) => void;\r\n /**\r\n * Acepta un array de keys que serán las que se recorrerán en\r\n * la propagación del nuevo estado.\r\n */\r\n set: (newKeys: string[]) => void;\r\n};\r\n\r\n/**\r\n * Las operaciones son métodos que alteran el estado de alguna manera.\r\n *\r\n * Idealmente, cada operación indica qué keys afectó, de forma que no\r\n * sea necesario realizar comparaciones para saber qué elementos deben\r\n * ser modificados dentro del store.\r\n *\r\n * Cada operación recibe state que es un drat de Immer, de igual manera\r\n * como lo hacen los reducers de createSlice de Redux-toolkit.\r\n *\r\n * El payload es arbitrario.\r\n *\r\n * defineKeys es un objeto que contiene distintos métodos que permiten\r\n * alterar el listado de keys que serán iteradas para notificar del\r\n * cambio de estado.\r\n */\r\ntype TOperation<State, Payload> = (\r\n state: Draft<State>,\r\n payload: Payload,\r\n defineKeys: TKeysDefine,\r\n) => void;\r\n\r\n/**\r\n * Representa el conjunto de todas las operaciones de un store.\r\n */\r\nexport type TOperations<State> = Record<string, TOperation<State, any>>;\r\n\r\n/**\r\n * Conjunto de elementos que distinguen a cada tipo de elemento del\r\n * store. Se toma a partir de la definición del objeto distinctors\r\n * del método create.\r\n */\r\ntype TDistinctions<\r\n Distinctors extends TDistinctors<any>,\r\n K extends keyof Distinctors,\r\n> = Parameters<Distinctors[K][0]>[0];\r\n\r\n/**\r\n * Es el hook encargado de registrar los callbacks necesarios a los\r\n * eventos que corresponda de forma de garantizar que las propiedades\r\n * se apliquen sobre el elemento que corresponda.\r\n */\r\nexport type TUseProperties<State, Distinctors extends TDistinctors<State>> = <\r\n RefType,\r\n K extends keyof Distinctors = keyof Distinctors,\r\n>(\r\n which: K,\r\n distinctions: TDistinctions<Distinctors, K>,\r\n comparator?: (\r\n prevSelection: TDistinctorProperties,\r\n newSelection: TDistinctorProperties,\r\n ) => boolean,\r\n) => RefObject<RefType>;\r\n\r\nexport type TStateChangeListener<State> = (\r\n state: State,\r\n previousState: State,\r\n) => unknown;\r\n\r\n/**\r\n * Permite obtener una copia del estado local\r\n */\r\nexport type TGetState<State> = () => State;\r\n\r\n/**\r\n * Permite registrar un callback que será llamado con cada actualización del\r\n * estado\r\n */\r\nexport type TRegisterStateChangeListener<State> = (\r\n callback: TStateChangeListener<State>,\r\n) => () => void;\r\n\r\n/**\r\n * Es un método que dadas las distinciones de un elemento particular\r\n * construye un string que lo identifica.\r\n */\r\ntype TKeyMaker<\r\n State,\r\n Distinctors extends TDistinctors<State> = TDistinctors<State>,\r\n Key extends keyof Distinctors = keyof Distinctors,\r\n> = (distinctions: TDistinctions<Distinctors, Key>) => string;\r\n\r\n/**\r\n * Es un mapa que contiene un TKeyMaker por cada tipo de elemento.\r\n */\r\nexport type TKeysMaker<State, Distinctors extends TDistinctors<State>> = {\r\n [key in keyof Distinctors]: TKeyMaker<State, Distinctors, key>;\r\n};\r\n\r\n/**\r\n * Tipo que permite extraer el tipo del payload de una operación.\r\n */\r\ntype TOperationParameter<Operation extends TOperation<any, any>> =\r\n Parameters<Operation>[1];\r\n\r\n/**\r\n * Representa una acción asociada a una operación. Es el método\r\n * que es llamado desde fuera del store para ejecutar una operación\r\n * y actualizar el estado. Como consecuencia de la ejecución de esta\r\n * acción, el estado será actualizado y se harán las notificaciones\r\n * y actualización de propiedades que correspondan en los elementos\r\n * afectados.\r\n */\r\ntype TOperationAction<Payload> = (\r\n props: Payload extends void ? void : Payload,\r\n) => void;\r\n\r\n/**\r\n * Objeto que contiene todas las acciones de un store.\r\n */\r\nexport type TActionsMap<State, Operations extends TOperations<State>> = {\r\n [Key in keyof Operations]: TOperationAction<\r\n TOperationParameter<Operations[Key]>\r\n >;\r\n};\r\n\r\n/**\r\n * Método que es llamado luego de que se actualizan los elementos\r\n * pertenecientes a un tipo del store.\r\n */\r\ntype TAfterActionCallback<State> = (\r\n prevState: State,\r\n nextState: State,\r\n) => unknown;\r\n\r\nexport type TClassListComposer = Partial<{\r\n add: string[];\r\n remove: string[];\r\n toggle: string[];\r\n}>;\r\n\r\nexport type TDatasetComposer = Partial<{\r\n add: Record<string, any>;\r\n remove: string[];\r\n}>;\r\n\r\nexport type TDistinctorProperties = Partial<{\r\n classList: TClassListComposer;\r\n dataset: TDatasetComposer;\r\n etc: Record<string, any>;\r\n styles: CSSStyleDeclaration;\r\n}>;\r\n\r\n/**\r\n * Objeto que representa un tipo de elemento del store.\r\n */\r\ntype TDistinctor<State, Distinctions extends Record<string, any>> =\r\n | [\r\n (distinctions: Distinctions, state: State) => TDistinctorProperties,\r\n TAfterActionCallback<State>,\r\n ]\r\n | [(distinctions: Distinctions, state: State) => TDistinctorProperties];\r\n\r\n/**\r\n * Los distinctors determinan para cada tipo de elemento aceptado,\r\n * si dado un cambio en el estado del store, este elemento debe ser\r\n * actualizado o no\r\n * */\r\nexport type TDistinctors<State> = Record<string, TDistinctor<State, any>>;\r\n\r\nfunction setAriaAttributes(\r\n element: HTMLElement,\r\n attribute: string,\r\n value: any,\r\n) {\r\n element.setAttribute(attribute, value as string);\r\n}\r\n\r\n/**\r\n * Representa los callbacks internos del store utilizados para comunicar\r\n * acerca del cambio de estado a los elementos correspondientes.\r\n */\r\ntype TInnerStateListener<State> = (currentState: State) => void;\r\n\r\nfunction applyProperties(element: HTMLElement, props: TDistinctorProperties) {\r\n if (!element || !(element instanceof HTMLElement)) return;\r\n\r\n (props.classList?.add ?? []).forEach((current) => {\r\n if (current) element.classList.add(current);\r\n });\r\n (props.classList?.remove ?? []).forEach((current) => {\r\n if (current) element.classList.remove(current);\r\n });\r\n (props.classList?.toggle ?? []).forEach((current) => {\r\n if (current) element.classList.toggle(current);\r\n });\r\n\r\n Object.entries(props.dataset?.add ?? {}).forEach(([key, value]) => {\r\n element.dataset[key] = value;\r\n });\r\n (props.dataset?.remove ?? []).forEach(\r\n (current) => delete element.dataset[current],\r\n );\r\n\r\n Object.entries(props.styles ?? {}).forEach(([prop, value]) => {\r\n (element.style[prop as unknown as number] as any) = value;\r\n });\r\n\r\n Object.entries(props.etc ?? {}).forEach(([prop, value]) => {\r\n if (value === undefined) {\r\n delete (element as Record<string, any>)[prop];\r\n return;\r\n }\r\n\r\n const match = prop.match(/^aria-(\\w+)$/);\r\n if (match) {\r\n setAriaAttributes(element, prop, value);\r\n return;\r\n }\r\n (element as Record<string, any>)[prop] = String(value);\r\n });\r\n}\r\n\r\n/**\r\n * Falta documentar, a grandes rasgos:\r\n * \r\n * Este store propone el máximo rendimiento: afectar solamente los registros\r\n * que sean estrictamente necesarios y no renderizar.\r\n * \r\n * Para lograr evitar el renderizado, el estado se guarda en internamente en el\r\n * store, pero también en el elemento asociado a cada registro. De esta manera,\r\n * cuando se actualiza el estado, se procesan los keys afectados, se genera el\r\n * estado para cada uno de ellos de acuerdo a su distintor correspondiente y se\r\n * actualiza el DOM en el momento. Si por algún motivo, el componente afectado\r\n * vuelve a renderizar, el hook devuelve el estado actualizado, de forma de\r\n * evitar pérdida de información.\r\n * \r\n * @returns\r\n * \r\n * Al crear un store se devuelve un array compuesto por 3 elementos en el\r\n * siguiente orden:\r\n * \r\n * - acciones: Un mapa de métodos correspondientes a las operaciones\r\n * definidas. \r\n * - useProperties: Un hook utilizado para obtener las propiedades\r\n * de un elemento, de acuerdo a su distinción.\r\n * - getState: Un método que permite obtener el estado actual del store.\r\n * \r\n * @example\r\n * \r\n * \r\n * const [actions, useProperties, getState, registerStateListener] =\r\n * createFAsomeStore({\r\n // Se puede utilizar un estado con estructura arbitraria\r\n initialState: {\r\n people: [],\r\n // El as ... es necesario para que typescript pueda realizar la inferencia\r\n // correctamente. Siempre que se cree un store se debe seguir la estructura\r\n // propuesta en este ejemplo\r\n } as { people: { name: string }[] },\r\n // Los distinguidores \"distinctors\" establecen qué tipos de elementos existen\r\n // dentro del store y qué estado utiliza cada uno de ellos\r\n distinctors: {\r\n person: [\r\n // El tipado asignado al parámetro distinctions será tomado por el store\r\n // para pasarlo luego al keymaker a la hora de seleccionar un registro del\r\n // store\r\n (distinctions: { name: string }, state) => {\r\n return {\r\n name: state.people.find(\r\n (current) => current.name === distinctions.name,\r\n ),\r\n };\r\n },\r\n ],\r\n },\r\n // Los keymakers se encargan de generar claves únicas para cada elemento del\r\n // store\r\n keysMakers: {\r\n person: (distinctions) => {\r\n // Debe crear una key única dentro del store\r\n return distinctions.name;\r\n },\r\n },\r\n // Los operadores permiten alterar el estado actual\r\n operations: {\r\n addPerson(state, payload: { name: string }, affectedKeys) {\r\n // El estado se altera de cualquier forma que sea conveniente\r\n state.people.push({ name: payload.name });\r\n // Este key debe ser idéntico al generado por el keyMaker de person (Más\r\n // arriba)\r\n affectedKeys.set([payload.name]);\r\n },\r\n },\r\n });\r\n */\r\nexport function createFAsomeStore<\r\n State,\r\n Distinctors extends TDistinctors<State> = TDistinctors<State>,\r\n Operations extends TOperations<State> = TOperations<State>,\r\n>({\r\n initialState,\r\n operations,\r\n distinctors,\r\n keysMakers,\r\n}: {\r\n initialState: State;\r\n operations: Operations;\r\n distinctors: Distinctors;\r\n keysMakers: TKeysMaker<State, Distinctors>;\r\n}): [\r\n TActionsMap<State, Operations>,\r\n TUseProperties<State, Distinctors>,\r\n TGetState<State>,\r\n TRegisterStateChangeListener<State>,\r\n] {\r\n const actions = {} as TActionsMap<State, Operations>;\r\n let state = initialState;\r\n\r\n const callbacks: Record<string, Map<string, TInnerStateListener<State>>> = {};\r\n const keysMap = new Map<string, number>();\r\n\r\n function registerCallback<K extends keyof Distinctors>(\r\n which: K,\r\n distinctions: TDistinctions<Distinctors, K>,\r\n callback: TInnerStateListener<State>,\r\n ) {\r\n if (!callbacks[which as string]) {\r\n callbacks[which as string] = new Map();\r\n }\r\n const key = keysMakers[which](distinctions);\r\n keysMap.set(key, (keysMap.get(key) ?? 0) + 1);\r\n callbacks[which as string].set(key, callback);\r\n\r\n return () => {\r\n callbacks[which as string].delete(key);\r\n keysMap.set(key, (keysMap.get(key) as number) - 1);\r\n if (keysMap.get(key) === 0) keysMap.delete(key);\r\n };\r\n }\r\n\r\n let stateListenersCallbacks: TStateChangeListener<State>[] = [];\r\n\r\n const registerStateListener: TRegisterStateChangeListener<State> = (\r\n callback: TStateChangeListener<State>,\r\n ) => {\r\n stateListenersCallbacks.push(callback);\r\n\r\n return () => {\r\n stateListenersCallbacks = stateListenersCallbacks.filter(\r\n (current) => current !== callback,\r\n );\r\n };\r\n };\r\n\r\n Object.entries(operations).forEach(([name, operation]) => {\r\n const action: TOperationAction<TOperationParameter<typeof operation>> = (\r\n props,\r\n ) => {\r\n let keys = Array.from(keysMap.keys()) as string[];\r\n const pushedKeys: Record<string, any> = {};\r\n let hasPushed = false;\r\n const nextState = produce(state, (state) =>\r\n operations[name](state, props, {\r\n filter(filterCallback) {\r\n if (hasPushed) {\r\n Object.keys(pushedKeys)\r\n .filter((current, ...e) => filterCallback(current, ...e))\r\n .forEach((current) => delete pushedKeys[current]);\r\n } else keys = keys.filter(filterCallback);\r\n },\r\n push(...newKeys) {\r\n if (!hasPushed) {\r\n hasPushed = true;\r\n }\r\n newKeys.forEach((current) => (pushedKeys[current] = true));\r\n },\r\n set(newKeys) {\r\n if (!hasPushed) {\r\n hasPushed = true;\r\n }\r\n newKeys.forEach((current) => (pushedKeys[current] = true));\r\n },\r\n }),\r\n );\r\n\r\n const actualKeys = hasPushed ? Object.keys(pushedKeys) : keys;\r\n hasPushed ? Object.keys(pushedKeys) : keys;\r\n\r\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\r\n if ((window as any).debugDomStore) {\r\n console.clear();\r\n }\r\n if (nextState !== state) {\r\n stateListenersCallbacks.forEach((current) => {\r\n current(nextState, state);\r\n });\r\n Object.keys(callbacks).forEach((which) => {\r\n actualKeys.forEach((key) => {\r\n callbacks[which].get(key)?.(nextState);\r\n });\r\n distinctors[which][1]?.(state, nextState);\r\n });\r\n state = nextState;\r\n }\r\n };\r\n actions[name as keyof TActionsMap<State, Operations>] = action;\r\n });\r\n\r\n /**\r\n * Este hook permite recuperar el estado asociado a un elemento. \r\n * El siguiente ejemplo está tomado del componente Listbox de \r\n * **@apia/components**. En el mismo se puede ver que se toman las \r\n * props devueltas y se hacen spread sobre el elemento destino. \r\n * En este ejemplo, las acciones y el useListbox vienen por \r\n * contexto pero son exactamente los mismos devueltos por \r\n * createFAsomeStore.\r\n * \r\n * @example\r\n * \r\n * export const ListboxItem: FC<TListboxItem> = ({\r\n children,\r\n rowIndex: outerRowIndex,\r\n }) => {\r\n const { listboxActions, useListbox } = useContext(ListboxContext);\r\n const rowIndex = useMemo(() => outerRowIndex ?? -1, [outerRowIndex]);\r\n const props = useListbox<HTMLDivElement>('row', { rowIndex });\r\n\r\n return (\r\n <div\r\n {...props}\r\n onClick={useCallback(() => {\r\n listboxActions.updateSelectedRows({ newSelectedRows: [rowIndex] });\r\n }, [listboxActions, rowIndex])}\r\n >\r\n {children}\r\n </div>\r\n );\r\n };\r\n */\r\n const useProperties: TUseProperties<State, Distinctors> = <\r\n RefType,\r\n K extends keyof Distinctors = keyof Distinctors,\r\n >(\r\n which: K,\r\n distinctions: TDistinctions<Distinctors, K>,\r\n comparator: (\r\n prevSelection: TDistinctorProperties,\r\n newSelection: TDistinctorProperties,\r\n ) => boolean = (a, b) => a === b,\r\n ) => {\r\n const ref = useRef<RefType>(null);\r\n const returnRef = useCallback((el: RefType) => {\r\n if (el) {\r\n applyProperties(\r\n el as unknown as HTMLElement,\r\n previousSelection.current,\r\n );\r\n }\r\n (ref as MutableRefObject<RefType>).current = el;\r\n }, []) as unknown as MutableRefObject<RefType>;\r\n const previousSelection = useRef<TDistinctorProperties>(\r\n null as unknown as TDistinctorProperties,\r\n );\r\n if (previousSelection.current === null) {\r\n previousSelection.current = distinctors[which][0](\r\n distinctions,\r\n state,\r\n ) as TDistinctorProperties;\r\n }\r\n\r\n useEffect(() => {\r\n return registerCallback(which, distinctions, (current) => {\r\n const newState: TDistinctorProperties = distinctors[which][0](\r\n distinctions,\r\n current,\r\n );\r\n if (!comparator(previousSelection.current, newState)) {\r\n previousSelection.current = newState;\r\n applyProperties(ref.current as HTMLElement, newState);\r\n }\r\n });\r\n }, [comparator, distinctions, which]);\r\n\r\n return returnRef;\r\n };\r\n\r\n const getState = () => {\r\n return cloneDeep(state);\r\n };\r\n\r\n return [actions, useProperties, getState, registerStateListener];\r\n}\r\n\r\nexport type { Draft };\r\n"],"names":["state"],"mappings":";;;;AA2MA,SAAS,iBAAA,CACP,OACA,EAAA,SAAA,EACA,KACA,EAAA;AACA,EAAQ,OAAA,CAAA,YAAA,CAAa,WAAW,KAAe,CAAA,CAAA;AACjD,CAAA;AAQA,SAAS,eAAA,CAAgB,SAAsB,KAA8B,EAAA;AAC3E,EAAI,IAAA,CAAC,OAAW,IAAA,EAAE,OAAmB,YAAA,WAAA,CAAA;AAAc,IAAA,OAAA;AAEnD,EAAA,CAAC,MAAM,SAAW,EAAA,GAAA,IAAO,EAAI,EAAA,OAAA,CAAQ,CAAC,OAAY,KAAA;AAChD,IAAI,IAAA,OAAA;AAAS,MAAQ,OAAA,CAAA,SAAA,CAAU,IAAI,OAAO,CAAA,CAAA;AAAA,GAC3C,CAAA,CAAA;AACD,EAAA,CAAC,MAAM,SAAW,EAAA,MAAA,IAAU,EAAI,EAAA,OAAA,CAAQ,CAAC,OAAY,KAAA;AACnD,IAAI,IAAA,OAAA;AAAS,MAAQ,OAAA,CAAA,SAAA,CAAU,OAAO,OAAO,CAAA,CAAA;AAAA,GAC9C,CAAA,CAAA;AACD,EAAA,CAAC,MAAM,SAAW,EAAA,MAAA,IAAU,EAAI,EAAA,OAAA,CAAQ,CAAC,OAAY,KAAA;AACnD,IAAI,IAAA,OAAA;AAAS,MAAQ,OAAA,CAAA,SAAA,CAAU,OAAO,OAAO,CAAA,CAAA;AAAA,GAC9C,CAAA,CAAA;AAED,EAAA,MAAA,CAAO,OAAQ,CAAA,KAAA,CAAM,OAAS,EAAA,GAAA,IAAO,EAAE,CAAE,CAAA,OAAA,CAAQ,CAAC,CAAC,GAAK,EAAA,KAAK,CAAM,KAAA;AACjE,IAAQ,OAAA,CAAA,OAAA,CAAQ,GAAG,CAAI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AE,CAAA,CAAA;AACL,IAAA,MAAM,iBAAoB,GAAA,MAAA;AAAA,MACxB,IAAA;AAAA,KACF,CAAA;AACA,IAAI,IAAA,iBAAA,CAAkB,YAAY,IAAM,EAAA;AACtC,MAAA,iBAAA,CAAkB,OAAU,GAAA,WAAA,CAAY,KAAK,CAAA,CAAE,CAAC,CAAA;AAAA,QAC9C,YAAA;AAAA,QACA,KAAA;AAAA,OACF,CAAA;AAAA,KACF;AAEA,IAAA,SAAA,CAAU,MAAM;AACd,MAAA,OAAO,gBAAiB,CAAA,KAAA,EAAO,YAAc,EAAA,CAAC,OAAY,KAAA;AACxD,QAAA,MAAM,QAAkC,GAAA,WAAA,CAAY,KAAK,CAAA,CAAE,CAAC,CAAA;AAAA,UAC1D,YAAA;AAAA,UACA,OAAA;AAAA,SACF,CAAA;AACA,QAAA,IAAI,CAAC,UAAA,CAAW,iBAAkB,CAAA,OAAA,EAAS,QAAQ,CAAG,EAAA;AACpD,UAAA,iBAAA,CAAkB,OAAU,GAAA,QAAA,CAAA;AAC5B,UAAgB,eAAA,CAAA,GAAA,CAAI,SAAwB,QAAQ,CAAA,CAAA;AAAA,SACtD;AAAA,OACD,CAAA,CAAA;AAAA,KACA,EAAA,CAAC,UAAY,EAAA,YAAA,EAAc,KAAK,CAAC,CAAA,CAAA;AAEpC,IAAO,OAAA,SAAA,CAAA;AAAA,GACT,CAAA;AAEA,EAAA,MAAM,WAAW,MAAM;AACrB,IAAA,OAAO,UAAU,KAAK,CAAA,CAAA;AAAA,GACxB,CAAA;AAEA,EAAA,OAAO,CAAC,OAAA,EAAS,aAAe,EAAA,QAAA,EAAU,qBAAqB,CAAA,CAAA;AACjE;;;;"}
package/package.json CHANGED
@@ -1,49 +1,35 @@
1
1
  {
2
2
  "name": "@apia/dom-store",
3
- "version": "1.0.4",
4
- "author": "alexisleite <alexisleite@live.com>",
5
- "homepage": "",
6
- "license": "MIT",
7
- "main": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
9
- "sideEffects": [
10
- "src/types/window.d.ts"
11
- ],
3
+ "version": "2.0.0",
4
+ "sideEffects": false,
5
+ "author": "Alexis Leite <alexisleite@live.com>",
6
+ "main": "dist/index.js",
7
+ "module": "dist/index.js",
8
+ "type": "module",
9
+ "typings": "dist/index.d.ts",
12
10
  "scripts": {
13
- "build": "rollup -c rollup.config.esb.mjs",
14
- "buildDev": "rollup -c rollup.config.esb.mjs --dev",
15
- "watch": "rollup -c rollup.config.esb.mjs --dev --watch"
16
- },
17
- "devDependencies": {
18
- "@rollup/plugin-commonjs": "^24.0.1",
19
- "@rollup/plugin-json": "^6.0.0",
20
- "@rollup/plugin-node-resolve": "^15.0.1",
21
- "@rollup/plugin-terser": "^0.4.0",
22
- "@rollup/plugin-typescript": "^11.0.0",
23
- "@types/lodash": "^4.14.192",
24
- "esbuild": "^0.17.14",
25
- "rollup": "^3.20.2",
26
- "rollup-plugin-bundle-analyzer": "^1.6.6",
27
- "rollup-plugin-dts": "^5.3.0",
28
- "rollup-plugin-esbuild": "^5.0.0",
29
- "typescript": "^4.9.5"
11
+ "libDev": "rollup --config ../../config/rollup.common.mjs --environment MODE:development,ENTRY:index.ts",
12
+ "libBuild": "rollup --config ../../config/rollup.common.mjs --environment MODE:production,ENTRY:index.ts",
13
+ "libWatch": "rollup --watch --config ../../config/rollup.common.mjs --environment MODE:development,ENTRY:index.ts,WATCH:true"
30
14
  },
31
15
  "dependencies": {
32
- "immer": "^9.0.19",
33
- "lodash": "^4.17.21"
16
+ "immer": "^9.0.19"
17
+ },
18
+ "devDependencies": {
19
+ "@types/react": "^18.2.43",
20
+ "@types/react-dom": "^18.2.17",
21
+ "@typescript-eslint/eslint-plugin": "^6.14.0",
22
+ "axios": "^1.3.5",
23
+ "typescript": "5.4.2"
34
24
  },
35
25
  "peerDependencies": {
26
+ "lodash-es": "^4.17.21",
36
27
  "react": "^18.2.0",
37
28
  "react-dom": "^18.2.0"
38
29
  },
39
- "gitHead": "6c198a4643a693e25634e89cb227c56d9d12476d",
40
- "repository": {
41
- "type": "git",
42
- "url": "http://corp-gitlab-01.domst.st.net/products/apia/ApiaNPMPackages.git",
43
- "directory": "packages/util"
44
- },
45
30
  "publishConfig": {
46
31
  "access": "public",
47
32
  "registry": "https://registry.npmjs.org/"
48
- }
33
+ },
34
+ "gitHead": "755c990cc9875e99922cc0f7194d9f0a479bdc71"
49
35
  }
package/LICENSE.md DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) [year] [fullname]
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
package/README.md DELETED
@@ -1,18 +0,0 @@
1
- # Initiator
2
-
3
- Este package se creó con la única utilidad de copiarlo entero y pegarlo a la hora de crear un nuevo package.
4
-
5
- Este iniciador permite crear un paquete que compila typescript y puede ser importado desde otros packages.
6
-
7
- ## Procedimiento
8
-
9
- - Copiar la carpeta initiator y pegarla con otro nombre dentro de packages.
10
- - Modificar el package.json:
11
- - Eliminar la línea ```private: true```.
12
- - Cambiar el nombre del package en la propiedad "name".
13
- - Cambiar el repositorio en "repository".
14
- - Ejecutar el comando lerna bootstrap desde la carpeta raíz.
15
-
16
- Luego de ejecutar estos pasos, el package estaría listo para comenzar a usarse.
17
-
18
- Este package trae como dependencias por defecto theme-ui y react. Si se desea agregar más dependencias se debe ejecutar el comando ```lerna add --scope="@apia/packageName" dependencyName```. Ejemplo, si creamos un paquete con el nombre @apia/myPackage y queremos agregar lodash como dependencia, ejecutamos el comando ```lerna add --scope="@apia/myPackage" lodash```. **Importante**: lerna no permite instalar de a varias dependencias a la vez como lo hace npm, por lo tanto, si se desea agregar varias dependencias se debe ejecutar el comando anterior tantas veces como dependencias se quiera agregar.
package/cleanDist.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "cleanDist": 0.9690365811095709
3
- }
package/entries.json DELETED
@@ -1 +0,0 @@
1
- ["./src/index.ts"]