@webtides/element-js 1.0.0-alpha.1 → 1.0.0-alpha.3

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/src/util/Store.js CHANGED
@@ -1,18 +1,63 @@
1
- import { isObjectLike, deepEquals } from './AttributeParser.js';
2
- import { BaseElement } from '../BaseElement';
1
+ import { deepEquals, isObjectLike } from './AttributeParser.js';
2
+ import {
3
+ hasSerializedState,
4
+ serializeState,
5
+ deserializeState,
6
+ serializableObjectsCache,
7
+ } from './SerializeStateHelper.js';
8
+ import { BaseElement } from '../BaseElement.js';
3
9
 
10
+ /**
11
+ * Options object for the Store
12
+ * @typedef {Object} StoreOptions
13
+ * @property {string} [key] - A unique key so that the store instance can be serialized and deserialized correctly across multiple shared parents/hosts.
14
+ */
15
+
16
+ /**
17
+ * @implements {Serializable}
18
+ */
4
19
  export class Store {
5
- _observer = new Set();
20
+ _serializationKey;
21
+ _observer = new Set([]);
6
22
  _singlePropertyMode = false;
7
23
  _state = {};
8
24
 
9
- constructor(value) {
10
- // wrap primitives with a generic "value" field to generate getter and setter
25
+ /**
26
+ * @param {* | object} [value]
27
+ * @param {StoreOptions} [options]
28
+ */
29
+ constructor(value, options) {
30
+ if (options?.key && serializableObjectsCache.has(options?.key)) {
31
+ return serializableObjectsCache.get(options?.key);
32
+ }
33
+
11
34
  this._singlePropertyMode = arguments.length > 0 && !isObjectLike(value);
35
+
36
+ if (options?.key) {
37
+ this._serializationKey = options?.key;
38
+ } else {
39
+ this._serializationKey = globalThis.crypto.randomUUID();
40
+ }
41
+
42
+ if (options?.serializedState) {
43
+ deserializeState(this, options.serializedState);
44
+ } else if (hasSerializedState(this._serializationKey)) {
45
+ deserializeState(this);
46
+ }
47
+
48
+ // wrap primitives with a generic "value" field to generate getter and setter
12
49
  const specificValues = this._singlePropertyMode ? { value } : value;
13
- this._state = { ...(!this._singlePropertyMode && this.properties()), ...specificValues };
50
+ const properties = { ...(!this._singlePropertyMode && this.properties()), ...specificValues };
51
+
52
+ const serializationKeys = Object.keys(this.serializeState());
53
+ Object.entries(properties).map(([key, value]) => {
54
+ this._state[key] =
55
+ hasSerializedState(this._serializationKey) && serializationKeys.includes(key) ? this[key] : value;
56
+
57
+ if (value instanceof Store) {
58
+ value.subscribe(this);
59
+ }
14
60
 
15
- Object.entries(this._state).map(([key, value]) => {
16
61
  Object.defineProperty(this, key, {
17
62
  get: () => {
18
63
  return this._state[key];
@@ -20,6 +65,11 @@ export class Store {
20
65
  set: (newValue) => {
21
66
  const oldValue = this._state[key];
22
67
  this._state[key] = newValue;
68
+ if (value instanceof Store) {
69
+ value.subscribe(this);
70
+ }
71
+
72
+ serializeState(this);
23
73
 
24
74
  if (!deepEquals(newValue, oldValue)) {
25
75
  const watch = this.watch();
@@ -31,8 +81,15 @@ export class Store {
31
81
  },
32
82
  });
33
83
  });
84
+
85
+ serializableObjectsCache.set(this._serializationKey, this);
34
86
  }
35
87
 
88
+ /**
89
+ * Properties to be defined and assigned on the store. Can be overridden in extended classes.
90
+ * Properties defined here will also trigger an update cycle when changed.
91
+ * @return {{}}
92
+ */
36
93
  properties() {
37
94
  return {};
38
95
  }
@@ -40,47 +97,66 @@ export class Store {
40
97
  /**
41
98
  * When a property as the key was changed in the store, the callback function defined as value
42
99
  * will be called with `newValue` and `oldValue`
43
- * eg. { property: (oldValue, newValue) => { console.log('property changed!, oldValue, newValue); } }
44
100
  * @return {{}}
45
101
  */
46
102
  watch() {
47
103
  return {};
48
104
  }
49
105
 
106
+ /**
107
+ * Overrides `valueOf` to automatically return .value
108
+ * @returns {* | {}}
109
+ */
50
110
  valueOf() {
51
111
  return this._singlePropertyMode ? this._state.value : this._state;
52
112
  }
53
113
 
114
+ /**
115
+ * Overrides `toString` to automatically return .value
116
+ * @returns {string}
117
+ */
54
118
  toString() {
55
119
  return `${this._singlePropertyMode ? this._state.value : this._state}`;
56
120
  }
57
121
 
58
122
  /**
59
- * @param {BaseElement|Function} observer
123
+ * Add an observer
124
+ * @param {BaseElement|Function|Store} observer
60
125
  */
61
126
  subscribe(observer) {
62
127
  this._observer.add(observer);
63
128
  }
129
+
64
130
  /**
65
- * @param {BaseElement|Function} observer
131
+ * Remove an observer
132
+ * @param {BaseElement | Function} observer
66
133
  */
67
134
  unsubscribe(observer) {
68
135
  this._observer.delete(observer);
69
136
  }
70
137
 
138
+ /**
139
+ * Request and batch an asynchronous update cycle
140
+ */
71
141
  requestUpdate() {
72
142
  this._observer.forEach(async (observer) => {
73
- if (observer instanceof BaseElement) {
74
- await observer.requestUpdate();
143
+ if (observer instanceof BaseElement || observer instanceof Store) {
144
+ if (observer?._options?.autoUpdate !== false) {
145
+ await observer.requestUpdate();
146
+ }
75
147
  // check if store is watched by an observer
76
148
  if (Object.keys(observer.watch() ?? {}).length > 0) {
77
149
  // observer actually has watched properties
78
- const properties = observer.properties();
79
150
  Object.keys(observer.watch() ?? {}).forEach((key) => {
80
151
  if (observer._state[key] === this) {
81
152
  // observer is actually watching store changes provide new and old values
82
- observer.callPropertyWatcher(key, this, this);
83
- observer.notifyPropertyChange(key, this);
153
+ if (observer instanceof Store) {
154
+ // observer is a foreign store / call watcher
155
+ observer.watch?.()[key](this, this);
156
+ } else {
157
+ observer.callPropertyWatcher(key, this, this);
158
+ observer.notifyPropertyChange(key, this);
159
+ }
84
160
  }
85
161
  });
86
162
  }
@@ -91,4 +167,24 @@ export class Store {
91
167
  }
92
168
  });
93
169
  }
170
+
171
+ /**
172
+ * This method will be used to serialize this stores state.
173
+ * By default, it will generate an object with all properties from this.properties().
174
+ * You can override this and return a different object with more/less/different properties.
175
+ * @return {{[string: any]: *}}
176
+ */
177
+ serializeState() {
178
+ const keys = Object.keys(this.properties());
179
+ return Object.fromEntries(keys.map((key) => [key, this[key]]));
180
+ }
181
+
182
+ /**
183
+ * This method will be used to restore properties on the store from a previously serialized state.
184
+ * You can override this and handle the deserialization differently if the default is not enough.
185
+ * @param {{[string: any]: *}} serializedState
186
+ */
187
+ restoreState(serializedState) {
188
+ Object.assign(this, serializedState);
189
+ }
94
190
  }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Wrapper for defining custom elements so that registering an element multiple times won't crash
3
- * @param name for the tag
4
- * @param constructor for the custom element
3
+ * @param {string} name - name for the element tag
4
+ * @param {CustomElementConstructor} constructor for the custom element
5
5
  */
6
6
  export function defineElement(name, constructor) {
7
7
  try {
@@ -1,8 +1,8 @@
1
1
  /**
2
2
  * Little wrapper function for JSON.stringify() to easily convert objects and arrays to strings
3
3
  * to be able to set them as attributes on custom elements
4
- * @param value to be stringified
5
- * @return String of the stringified value
4
+ * @param {object | array} value - to be stringified
5
+ * @return {string}
6
6
  */
7
7
  export function toString(value) {
8
8
  try {
package/src/util/i18n.js DELETED
@@ -1,20 +0,0 @@
1
- /**
2
- * Retrieves a translated key from a dictionary on the window object
3
- * Example: ${i18n('CustomElement.buttonLabel', 'Label')}
4
- * @param key to be translated
5
- * @param fallback to be used if key is not defined
6
- * @return String of the translated key or fallback or original key
7
- */
8
- export function i18n(key, fallback) {
9
- try {
10
- const translations = window.elementjs.i18n();
11
- if (translations[key] === undefined) {
12
- throw 'Translation Missing';
13
- }
14
-
15
- return translations[key];
16
- } catch (err) {
17
- if (fallback) return fallback;
18
- else return key;
19
- }
20
- }