]> BookStack Code Mirror - bookstack/blob - resources/js/wysiwyg/lexical/utils/mergeRegister.ts
Images: Added testing to cover animated avif handling
[bookstack] / resources / js / wysiwyg / lexical / utils / mergeRegister.ts
1 /**
2  * Copyright (c) Meta Platforms, Inc. and affiliates.
3  *
4  * This source code is licensed under the MIT license found in the
5  * LICENSE file in the root directory of this source tree.
6  *
7  */
8
9 type Func = () => void;
10
11 /**
12  * Returns a function that will execute all functions passed when called. It is generally used
13  * to register multiple lexical listeners and then tear them down with a single function call, such
14  * as React's useEffect hook.
15  * @example
16  * ```ts
17  * useEffect(() => {
18  *   return mergeRegister(
19  *     editor.registerCommand(...registerCommand1 logic),
20  *     editor.registerCommand(...registerCommand2 logic),
21  *     editor.registerCommand(...registerCommand3 logic)
22  *   )
23  * }, [editor])
24  * ```
25  * In this case, useEffect is returning the function returned by mergeRegister as a cleanup
26  * function to be executed after either the useEffect runs again (due to one of its dependencies
27  * updating) or the component it resides in unmounts.
28  * Note the functions don't neccesarily need to be in an array as all arguments
29  * are considered to be the func argument and spread from there.
30  * The order of cleanup is the reverse of the argument order. Generally it is
31  * expected that the first "acquire" will be "released" last (LIFO order),
32  * because a later step may have some dependency on an earlier one.
33  * @param func - An array of cleanup functions meant to be executed by the returned function.
34  * @returns the function which executes all the passed cleanup functions.
35  */
36 export default function mergeRegister(...func: Array<Func>): () => void {
37   return () => {
38     for (let i = func.length - 1; i >= 0; i--) {
39       func[i]();
40     }
41     // Clean up the references and make future calls a no-op
42     func.length = 0;
43   };
44 }