1 |
efrain |
1 |
// This file is part of Moodle - http://moodle.org/
|
|
|
2 |
//
|
|
|
3 |
// Moodle is free software: you can redistribute it and/or modify
|
|
|
4 |
// it under the terms of the GNU General Public License as published by
|
|
|
5 |
// the Free Software Foundation, either version 3 of the License, or
|
|
|
6 |
// (at your option) any later version.
|
|
|
7 |
//
|
|
|
8 |
// Moodle is distributed in the hope that it will be useful,
|
|
|
9 |
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
10 |
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
11 |
// GNU General Public License for more details.
|
|
|
12 |
//
|
|
|
13 |
// You should have received a copy of the GNU General Public License
|
|
|
14 |
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
|
|
|
15 |
|
|
|
16 |
/**
|
|
|
17 |
* A generic single state reactive module.
|
|
|
18 |
*
|
|
|
19 |
* @module core/local/reactive/reactive
|
|
|
20 |
* @class core/local/reactive/reactive
|
|
|
21 |
* @copyright 2021 Ferran Recio <ferran@moodle.com>
|
|
|
22 |
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
|
|
|
23 |
*/
|
|
|
24 |
|
|
|
25 |
import log from 'core/log';
|
|
|
26 |
import StateManager from 'core/local/reactive/statemanager';
|
|
|
27 |
import Pending from 'core/pending';
|
|
|
28 |
|
|
|
29 |
// Count the number of pending operations done to ensure we have a unique id for each one.
|
|
|
30 |
let pendingCount = 0;
|
|
|
31 |
|
|
|
32 |
/**
|
|
|
33 |
* Set up general reactive class to create a single state application with components.
|
|
|
34 |
*
|
|
|
35 |
* The reactive class is used for registering new UI components and manage the access to the state values
|
|
|
36 |
* and mutations.
|
|
|
37 |
*
|
|
|
38 |
* When a new reactive instance is created, it will contain an empty state and and empty mutations
|
|
|
39 |
* lists. When the state data is ready, the initial state can be loaded using the "setInitialState"
|
|
|
40 |
* method. This will protect the state from writing and will trigger all the components "stateReady"
|
|
|
41 |
* methods.
|
|
|
42 |
*
|
|
|
43 |
* State can only be altered by mutations. To replace all the mutations with a specific class,
|
|
|
44 |
* use "setMutations" method. If you need to just add some new mutation methods, use "addMutations".
|
|
|
45 |
*
|
|
|
46 |
* To register new components into a reactive instance, use "registerComponent".
|
|
|
47 |
*
|
|
|
48 |
* Inside a component, use "dispatch" to invoke a mutation on the state (components can only access
|
|
|
49 |
* the state in read only mode).
|
|
|
50 |
*/
|
|
|
51 |
export default class {
|
|
|
52 |
|
|
|
53 |
/**
|
|
|
54 |
* The component descriptor data structure.
|
|
|
55 |
*
|
|
|
56 |
* @typedef {object} description
|
|
|
57 |
* @property {string} eventName the custom event name used for state changed events
|
|
|
58 |
* @property {Function} eventDispatch the state update event dispatch function
|
|
|
59 |
* @property {Element} [target] the target of the event dispatch. If not passed a fake element will be created
|
|
|
60 |
* @property {Object} [mutations] an object with state mutations functions
|
|
|
61 |
* @property {Object} [state] an object to initialize the state.
|
|
|
62 |
*/
|
|
|
63 |
|
|
|
64 |
/**
|
|
|
65 |
* Create a basic reactive manager.
|
|
|
66 |
*
|
|
|
67 |
* Note that if your state is not async loaded, you can pass directly on creation by using the
|
|
|
68 |
* description.state attribute. However, this will initialize the state, this means
|
|
|
69 |
* setInitialState will throw an exception because the state is already defined.
|
|
|
70 |
*
|
|
|
71 |
* @param {description} description reactive manager description.
|
|
|
72 |
*/
|
|
|
73 |
constructor(description) {
|
|
|
74 |
|
|
|
75 |
if (description.eventName === undefined || description.eventDispatch === undefined) {
|
|
|
76 |
throw new Error(`Reactivity event required`);
|
|
|
77 |
}
|
|
|
78 |
|
|
|
79 |
if (description.name !== undefined) {
|
|
|
80 |
this.name = description.name;
|
|
|
81 |
}
|
|
|
82 |
|
|
|
83 |
// Each reactive instance has its own element anchor to propagate state changes internally.
|
|
|
84 |
// By default the module will create a fake DOM element to target custom events but
|
|
|
85 |
// if all reactive components is constrait to a single element, this can be passed as
|
|
|
86 |
// target in the description.
|
|
|
87 |
this.target = description.target ?? document.createTextNode(null);
|
|
|
88 |
|
|
|
89 |
this.eventName = description.eventName;
|
|
|
90 |
this.eventDispatch = description.eventDispatch;
|
|
|
91 |
|
|
|
92 |
// State manager is responsible for dispatch state change events when a mutation happens.
|
|
|
93 |
this.stateManager = new StateManager(this.eventDispatch, this.target);
|
|
|
94 |
|
|
|
95 |
// An internal registry of watchers and components.
|
|
|
96 |
this.watchers = new Map([]);
|
|
|
97 |
this.components = new Set([]);
|
|
|
98 |
|
|
|
99 |
// Mutations can be overridden later using setMutations method.
|
|
|
100 |
this.mutations = description.mutations ?? {};
|
|
|
101 |
|
|
|
102 |
// Register the event to alert watchers when specific state change happens.
|
|
|
103 |
this.target.addEventListener(this.eventName, this.callWatchersHandler.bind(this));
|
|
|
104 |
|
|
|
105 |
// Add a pending operation waiting for the initial state.
|
|
|
106 |
this.pendingState = new Pending(`core/reactive:registerInstance${pendingCount++}`);
|
|
|
107 |
|
|
|
108 |
// Set initial state if we already have it.
|
|
|
109 |
if (description.state !== undefined) {
|
|
|
110 |
this.setInitialState(description.state);
|
|
|
111 |
}
|
|
|
112 |
|
|
|
113 |
// Check if we have a debug instance to register the instance.
|
|
|
114 |
if (M.reactive !== undefined) {
|
|
|
115 |
M.reactive.registerNewInstance(this);
|
|
|
116 |
}
|
|
|
117 |
}
|
|
|
118 |
|
|
|
119 |
/**
|
|
|
120 |
* State changed listener.
|
|
|
121 |
*
|
|
|
122 |
* This function take any state change and send it to the proper watchers.
|
|
|
123 |
*
|
|
|
124 |
* To prevent internal state changes from colliding with other reactive instances, only the
|
|
|
125 |
* general "state changed" is triggered at document level. All the internal changes are
|
|
|
126 |
* triggered at private target level without bubbling. This way any reactive instance can alert
|
|
|
127 |
* only its own watchers.
|
|
|
128 |
*
|
|
|
129 |
* @param {CustomEvent} event
|
|
|
130 |
*/
|
|
|
131 |
callWatchersHandler(event) {
|
|
|
132 |
// Execute any registered component watchers.
|
|
|
133 |
this.target.dispatchEvent(new CustomEvent(event.detail.action, {
|
|
|
134 |
bubbles: false,
|
|
|
135 |
detail: event.detail,
|
|
|
136 |
}));
|
|
|
137 |
}
|
|
|
138 |
|
|
|
139 |
/**
|
|
|
140 |
* Set the initial state.
|
|
|
141 |
*
|
|
|
142 |
* @param {object} stateData the initial state data.
|
|
|
143 |
*/
|
|
|
144 |
setInitialState(stateData) {
|
|
|
145 |
this.pendingState.resolve();
|
|
|
146 |
this.stateManager.setInitialState(stateData);
|
|
|
147 |
}
|
|
|
148 |
|
|
|
149 |
/**
|
|
|
150 |
* Add individual functions to the mutations.
|
|
|
151 |
*
|
|
|
152 |
* Note new mutations will be added to the existing ones. To replace the full mutation
|
|
|
153 |
* object with a new one, use setMutations method.
|
|
|
154 |
*
|
|
|
155 |
* @method addMutations
|
|
|
156 |
* @param {Object} newFunctions an object with new mutation functions.
|
|
|
157 |
*/
|
|
|
158 |
addMutations(newFunctions) {
|
|
|
159 |
// Mutations can provide an init method to do some setup in the statemanager.
|
|
|
160 |
if (newFunctions.init !== undefined) {
|
|
|
161 |
newFunctions.init(this.stateManager);
|
|
|
162 |
}
|
|
|
163 |
// Save all mutations.
|
|
|
164 |
for (const [mutation, mutationFunction] of Object.entries(newFunctions)) {
|
|
|
165 |
this.mutations[mutation] = mutationFunction.bind(newFunctions);
|
|
|
166 |
}
|
|
|
167 |
}
|
|
|
168 |
|
|
|
169 |
/**
|
|
|
170 |
* Replace the current mutations with a new object.
|
|
|
171 |
*
|
|
|
172 |
* This method is designed to override the full mutations class, for example by extending
|
|
|
173 |
* the original one. To add some individual mutations, use addMutations instead.
|
|
|
174 |
*
|
|
|
175 |
* @param {object} manager the new mutations intance
|
|
|
176 |
*/
|
|
|
177 |
setMutations(manager) {
|
|
|
178 |
this.mutations = manager;
|
|
|
179 |
// Mutations can provide an init method to do some setup in the statemanager.
|
|
|
180 |
if (manager.init !== undefined) {
|
|
|
181 |
manager.init(this.stateManager);
|
|
|
182 |
}
|
|
|
183 |
}
|
|
|
184 |
|
|
|
185 |
/**
|
|
|
186 |
* Return the current state.
|
|
|
187 |
*
|
|
|
188 |
* @return {object}
|
|
|
189 |
*/
|
|
|
190 |
get state() {
|
|
|
191 |
return this.stateManager.state;
|
|
|
192 |
}
|
|
|
193 |
|
|
|
194 |
/**
|
|
|
195 |
* Get state data.
|
|
|
196 |
*
|
|
|
197 |
* Components access the state frequently. This convenience method is a shortcut to
|
|
|
198 |
* this.reactive.state.stateManager.get() method.
|
|
|
199 |
*
|
|
|
200 |
* @param {String} name the state object name
|
|
|
201 |
* @param {*} id an optional object id for state maps.
|
|
|
202 |
* @return {Object|undefined} the state object found
|
|
|
203 |
*/
|
|
|
204 |
get(name, id) {
|
|
|
205 |
return this.stateManager.get(name, id);
|
|
|
206 |
}
|
|
|
207 |
|
|
|
208 |
/**
|
|
|
209 |
* Return the initial state promise.
|
|
|
210 |
*
|
|
|
211 |
* Typically, components do not require to use this promise because registerComponent
|
|
|
212 |
* will trigger their stateReady method automatically. But it could be useful for complex
|
|
|
213 |
* components that require to combine state, template and string loadings.
|
|
|
214 |
*
|
|
|
215 |
* @method getState
|
|
|
216 |
* @return {Promise}
|
|
|
217 |
*/
|
|
|
218 |
getInitialStatePromise() {
|
|
|
219 |
return this.stateManager.getInitialPromise();
|
|
|
220 |
}
|
|
|
221 |
|
|
|
222 |
/**
|
|
|
223 |
* Register a new component.
|
|
|
224 |
*
|
|
|
225 |
* Component can provide some optional functions to the reactive module:
|
|
|
226 |
* - getWatchers: returns an array of watchers
|
|
|
227 |
* - stateReady: a method to call when the initial state is loaded
|
|
|
228 |
*
|
|
|
229 |
* It can also provide some optional attributes:
|
|
|
230 |
* - name: the component name (default value: "Unkown component") to customize debug messages.
|
|
|
231 |
*
|
|
|
232 |
* The method will also use dispatchRegistrationSuccess and dispatchRegistrationFail. Those
|
|
|
233 |
* are BaseComponent methods to inform parent components of the registration status.
|
|
|
234 |
* Components should not override those methods.
|
|
|
235 |
*
|
|
|
236 |
* @method registerComponent
|
|
|
237 |
* @param {object} component the new component
|
|
|
238 |
* @param {string} [component.name] the component name to display in warnings and errors.
|
|
|
239 |
* @param {Function} [component.dispatchRegistrationSuccess] method to notify registration success
|
|
|
240 |
* @param {Function} [component.dispatchRegistrationFail] method to notify registration fail
|
|
|
241 |
* @param {Function} [component.getWatchers] getter of the component watchers
|
|
|
242 |
* @param {Function} [component.stateReady] method to call when the state is ready
|
|
|
243 |
* @return {object} the registered component
|
|
|
244 |
*/
|
|
|
245 |
registerComponent(component) {
|
|
|
246 |
|
|
|
247 |
// Component name is an optional attribute to customize debug messages.
|
|
|
248 |
const componentName = component.name ?? 'Unkown component';
|
|
|
249 |
|
|
|
250 |
// Components can provide special methods to communicate registration to parent components.
|
|
|
251 |
let dispatchSuccess = () => {
|
|
|
252 |
return;
|
|
|
253 |
};
|
|
|
254 |
let dispatchFail = dispatchSuccess;
|
|
|
255 |
if (component.dispatchRegistrationSuccess !== undefined) {
|
|
|
256 |
dispatchSuccess = component.dispatchRegistrationSuccess.bind(component);
|
|
|
257 |
}
|
|
|
258 |
if (component.dispatchRegistrationFail !== undefined) {
|
|
|
259 |
dispatchFail = component.dispatchRegistrationFail.bind(component);
|
|
|
260 |
}
|
|
|
261 |
|
|
|
262 |
// Components can be registered only one time.
|
|
|
263 |
if (this.components.has(component)) {
|
|
|
264 |
dispatchSuccess();
|
|
|
265 |
return component;
|
|
|
266 |
}
|
|
|
267 |
|
|
|
268 |
// Components are fully registered only when the state ready promise is resolved.
|
|
|
269 |
const pendingPromise = new Pending(`core/reactive:registerComponent${pendingCount++}`);
|
|
|
270 |
|
|
|
271 |
// Keep track of the event listeners.
|
|
|
272 |
let listeners = [];
|
|
|
273 |
|
|
|
274 |
// Register watchers.
|
|
|
275 |
let handlers = [];
|
|
|
276 |
if (component.getWatchers !== undefined) {
|
|
|
277 |
handlers = component.getWatchers();
|
|
|
278 |
}
|
|
|
279 |
handlers.forEach(({watch, handler}) => {
|
|
|
280 |
|
|
|
281 |
if (watch === undefined) {
|
|
|
282 |
dispatchFail();
|
|
|
283 |
throw new Error(`Missing watch attribute in ${componentName} watcher`);
|
|
|
284 |
}
|
|
|
285 |
if (handler === undefined) {
|
|
|
286 |
dispatchFail();
|
|
|
287 |
throw new Error(`Missing handler for watcher ${watch} in ${componentName}`);
|
|
|
288 |
}
|
|
|
289 |
|
|
|
290 |
const listener = (event) => {
|
|
|
291 |
// Prevent any watcher from losing the page focus.
|
|
|
292 |
const currentFocus = document.activeElement;
|
|
|
293 |
// Execute watcher.
|
|
|
294 |
handler.apply(component, [event.detail]);
|
|
|
295 |
// Restore focus in case it is lost.
|
|
|
296 |
if (document.activeElement === document.body && document.body.contains(currentFocus)) {
|
|
|
297 |
currentFocus.focus();
|
|
|
298 |
}
|
|
|
299 |
};
|
|
|
300 |
|
|
|
301 |
// Save the listener information in case the component must be unregistered later.
|
|
|
302 |
listeners.push({target: this.target, watch, listener});
|
|
|
303 |
|
|
|
304 |
// The state manager triggers a general "state changed" event at a document level. However,
|
|
|
305 |
// for the internal watchers, each component can listen to specific state changed custom events
|
|
|
306 |
// in the target element. This way we can use the native event loop without colliding with other
|
|
|
307 |
// reactive instances.
|
|
|
308 |
this.target.addEventListener(watch, listener);
|
|
|
309 |
});
|
|
|
310 |
|
|
|
311 |
// Register state ready function. There's the possibility a component is registered after the initial state
|
|
|
312 |
// is loaded. For those cases we have a state promise to handle this specific state change.
|
|
|
313 |
if (component.stateReady !== undefined) {
|
|
|
314 |
this.getInitialStatePromise()
|
|
|
315 |
.then(state => {
|
|
|
316 |
component.stateReady(state);
|
|
|
317 |
pendingPromise.resolve();
|
|
|
318 |
return true;
|
|
|
319 |
})
|
|
|
320 |
.catch(reason => {
|
|
|
321 |
pendingPromise.resolve();
|
|
|
322 |
log.error(`Initial state in ${componentName} rejected due to: ${reason}`);
|
|
|
323 |
log.error(reason);
|
|
|
324 |
});
|
|
|
325 |
}
|
|
|
326 |
|
|
|
327 |
// Save unregister data.
|
|
|
328 |
this.watchers.set(component, listeners);
|
|
|
329 |
this.components.add(component);
|
|
|
330 |
|
|
|
331 |
// Dispatch an event to communicate the registration to the debug module.
|
|
|
332 |
this.target.dispatchEvent(new CustomEvent('registerComponent:success', {
|
|
|
333 |
bubbles: false,
|
|
|
334 |
detail: {component},
|
|
|
335 |
}));
|
|
|
336 |
|
|
|
337 |
dispatchSuccess();
|
|
|
338 |
return component;
|
|
|
339 |
}
|
|
|
340 |
|
|
|
341 |
/**
|
|
|
342 |
* Unregister a component and its watchers.
|
|
|
343 |
*
|
|
|
344 |
* @param {object} component the object instance to unregister
|
|
|
345 |
* @returns {object} the deleted component
|
|
|
346 |
*/
|
|
|
347 |
unregisterComponent(component) {
|
|
|
348 |
if (!this.components.has(component)) {
|
|
|
349 |
return component;
|
|
|
350 |
}
|
|
|
351 |
|
|
|
352 |
this.components.delete(component);
|
|
|
353 |
|
|
|
354 |
// Remove event listeners.
|
|
|
355 |
const listeners = this.watchers.get(component);
|
|
|
356 |
if (listeners === undefined) {
|
|
|
357 |
return component;
|
|
|
358 |
}
|
|
|
359 |
|
|
|
360 |
listeners.forEach(({target, watch, listener}) => {
|
|
|
361 |
target.removeEventListener(watch, listener);
|
|
|
362 |
});
|
|
|
363 |
|
|
|
364 |
this.watchers.delete(component);
|
|
|
365 |
|
|
|
366 |
return component;
|
|
|
367 |
}
|
|
|
368 |
|
|
|
369 |
/**
|
|
|
370 |
* Dispatch a change in the state.
|
|
|
371 |
*
|
|
|
372 |
* This method is the only way for components to alter the state. Watchers will receive a
|
|
|
373 |
* read only state to prevent illegal changes. If some user action require a state change, the
|
|
|
374 |
* component should dispatch a mutation to trigger all the necessary logic to alter the state.
|
|
|
375 |
*
|
|
|
376 |
* @method dispatch
|
|
|
377 |
* @param {string} actionName the action name (usually the mutation name)
|
|
|
378 |
* @param {mixed} params any number of params the mutation needs.
|
|
|
379 |
*/
|
|
|
380 |
async dispatch(actionName, ...params) {
|
|
|
381 |
if (typeof actionName !== 'string') {
|
|
|
382 |
throw new Error(`Dispatch action name must be a string`);
|
|
|
383 |
}
|
|
|
384 |
// JS does not have private methods yet. However, we prevent any component from calling
|
|
|
385 |
// a method starting with "_" because the most accepted convention for private methods.
|
|
|
386 |
if (actionName.charAt(0) === '_') {
|
|
|
387 |
throw new Error(`Illegal Private ${actionName} mutation method dispatch`);
|
|
|
388 |
}
|
|
|
389 |
if (this.mutations[actionName] === undefined) {
|
|
|
390 |
throw new Error(`Unkown ${actionName} mutation`);
|
|
|
391 |
}
|
|
|
392 |
|
|
|
393 |
const pendingPromise = new Pending(`core/reactive:${actionName}${pendingCount++}`);
|
|
|
394 |
|
|
|
395 |
const mutationFunction = this.mutations[actionName];
|
|
|
396 |
try {
|
|
|
397 |
await mutationFunction.apply(this.mutations, [this.stateManager, ...params]);
|
|
|
398 |
pendingPromise.resolve();
|
|
|
399 |
} catch (error) {
|
|
|
400 |
// Ensure the state is locked.
|
|
|
401 |
this.stateManager.setReadOnly(true);
|
|
|
402 |
pendingPromise.resolve();
|
|
|
403 |
throw error;
|
|
|
404 |
}
|
|
|
405 |
}
|
|
|
406 |
}
|