summaryrefslogtreecommitdiffstats
path: root/pkg/lib/hooks.js
blob: 10c929746a7f979bb8fd62394cce065ac4d16f00 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
/*
 * This file is part of Cockpit.
 *
 * Copyright (C) 2020 Red Hat, Inc.
 *
 * Cockpit is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
 * (at your option) any later version.
 *
 * Cockpit is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
 */

import cockpit from 'cockpit';
import { useState, useEffect, useRef, useReducer } from 'react';
import deep_equal from "deep-equal";

/* HOOKS
 *
 * These are some custom React hooks for Cockpit specific things.
 *
 * Overview:
 *
 * - usePageLocation: For following along with cockpit.location.
 *
 * - useLoggedInUser: For accessing information about the currently
 * logged in user.
 *
 * - useFile: For reading and watching files.
 *
 * - useObject: For maintaining arbitrary stateful objects that get
 * created from the properties of a component.
 *
 * - useEvent: For reacting to events emitted by arbitrary objects.
 *
 * - useInit: For running a function once.
 *
 * - useDeepEqualMemo: A utility hook that can help with things that
 * need deep equal comparisons in places where React only offers
 * Object identity comparisons, such as with useEffect.
 */

/* - usePageLocation()
 *
 * function Component() {
 *   const location = usePageLocation();
 *   const { path, options } = usePageLocation();
 *
 *   ...
 * }
 *
 * This returns the current value of cockpit.location and the
 * component is re-rendered when it changes. "location" is always a
 * valid object and never null.
 *
 * See https://cockpit-project.org/guide/latest/cockpit-location.html
 */

export function usePageLocation() {
    const [location, setLocation] = useState(cockpit.location);

    useEffect(() => {
        function update() { setLocation(cockpit.location) }
        cockpit.addEventListener("locationchanged", update);
        return () => cockpit.removeEventListener("locationchanged", update);
    }, []);

    return location;
}

/* - useLoggedInUser()
 *
 * function Component() {
 *   const user_info = useLoggedInUser();
 *
 *   ...
 * }
 *
 * "user_info" is the object delivered by cockpit.user(), or null
 * while that object is not yet available.
 */

const cockpit_user_promise = cockpit.user();
let cockpit_user = null;
cockpit_user_promise.then(user => { cockpit_user = user });

export function useLoggedInUser() {
    const [user, setUser] = useState(cockpit_user);
    useEffect(() => { if (!cockpit_user) cockpit_user_promise.then(setUser); }, []);
    return user;
}

/* - useDeepEqualMemo(value)
 *
 * function Component(options) {
 *   const memo_options = useDeepEqualMemo(options);
 *   useEffect(() => {
 *       const channel = cockpit.channel(..., memo_options);
 *       ...
 *       return () => channel.close();
 *   }, [memo_options]);
 *
 *   ...
 * }
 *
 * function ParentComponent() {
 *     const options = { superuser: true, host: "localhost" };
 *     return <Component options={options}/>
 * }
 *
 * Sometimes a useEffect hook has a deeply nested object as one of its
 * dependencies, such as options for a Cockpit channel.  However,
 * React will compare dependency values with Object.is, and would run
 * the effect hook too often.  In the example above, the "options"
 * variable of Component is a different object on each render
 * according to Object.is, but we only want to open a new channel when
 * the value of a field such as "superuser" or "host" has actually
 * changed.
 *
 * A call to useDeepEqualMemo will return some object that is deeply
 * equal to its argument, and it will continue to return the same
 * object (according to Object.is) until the parameter is not deeply
 * equal to it anymore.
 *
 * For the example, this means that "memo_options" will always be the
 * very same object, and the effect hook is only run once.  If we
 * would use "options" directly as a dependency of the effect hook,
 * the channel would be closed and opened on every render. This is
 * very inefficient, doesn't give the asynchronous channel time to do
 * its job, and will also lead to infinite loops when events on the
 * channel cause re-renders (which in turn will run the effect hook
 * again, which will cause a new event, ...).
 */

export function useDeepEqualMemo(value) {
    const ref = useRef(value);
    if (!deep_equal(ref.current, value))
        ref.current = value;
    return ref.current;
}

/* - useFile(path, options)
 * - useFileWithError(path, options)
 *
 * function Component() {
 *   const content = useFile("/etc/hostname", { superuser: "try" });
 *   const [content, error] = useFileWithError("/etc/hostname", { superuser: "try" });
 *
 *   ...
 * }
 *
 * The "path" and "options" parameters are passed unchanged to
 * cockpit.file().  Thus, if you need to parse the content of the
 * file, the best way to do that is via the "syntax" option.
 *
 * The "content" variable will reflect the content of the file
 * "/etc/hostname". When the file changes on disk, the component will
 * be re-rendered with the new content.
 *
 * When the file does not exist or there has been some error reading
 * it, "content" will be false.
 *
 * The "error" variable will contain any errors encountered while
 * reading the file.  It is false when there are no errors.
 *
 * When the file does not exist, "error" will be false.
 *
 * The "content" and "error" variables will be null until the file has
 * been read for the first time.
 *
 * useFile and useFileWithError are pretty much the same. useFile will
 * hide the exact error from the caller, which makes it slightly
 * cleaner to use when the exact error is not part of the UI. In the
 * case of error, useFile will log that error to the console and
 * return false.
 */

export function useFileWithError(path, options, hook_options) {
    const [content_and_error, setContentAndError] = useState([null, null]);
    const memo_options = useDeepEqualMemo(options);
    const memo_hook_options = useDeepEqualMemo(hook_options);

    useEffect(() => {
        const handle = cockpit.file(path, memo_options);
        handle.watch((data, tag, error) => {
            setContentAndError([data || false, error || false]);
            if (!data && memo_hook_options?.log_errors)
                console.warn("Can't read " + path + ": " + (error ? error.toString() : "not found"));
        });
        return handle.close;
    }, [path, memo_options, memo_hook_options]);

    return content_and_error;
}

export function useFile(path, options) {
    const [content] = useFileWithError(path, options, { log_errors: true });
    return content;
}

/* - useObject(create, destroy, dependencies, comparators)
 *
 * function Component(param) {
 *   const obj = useObject(() => create_object(param),
 *                         obj => obj.close(),
 *                         [param], [deep_equal])
 *
 *   ...
 * }
 *
 * This will call "create_object(param)" before the first render of
 * the component, and will call "obj.close()" after the last render.
 *
 * More precisely, create_object will be called as part of the first
 * call to useObject, i.e., at the very beginning of the first render.
 *
 * When "param" changes compared to the previous call to useObject
 * (according to the deep_equal function in the example above), the
 * object will also be destroyed and a new one will be created for the
 * new value of "param" (as part of the call to useObject).
 *
 * There is no time when the "obj" variable is null in the example
 * above; the first render already has a fully created object.  This
 * is an advantage that useObject has over useEffect, which you might
 * otherwise use to only create objects when dependencies have
 * changed.
 *
 * And unlike useMemo, useObject will run a cleanup function when a
 * component is removed.  Also unlike useMemo, useObject guarantees
 * that it will not ignore the dependencies.
 *
 * The dependencies are an array of values that are by default
 * compared with Object.is.  If you need to use a custom comparator
 * function instead of Object.is, you can provide a second
 * "comparators" array that parallels the "dependencies" array.  The
 * values at a given index in the old and new "dependencies" arrays
 * are compared with the function at the same index in "comparators".
 */

function deps_changed(old_deps, new_deps, comps) {
    return (!old_deps || old_deps.length != new_deps.length ||
            old_deps.findIndex((o, i) => !(comps[i] || Object.is)(o, new_deps[i])) >= 0);
}

export function useObject(create, destroy, deps, comps) {
    const ref = useRef(null);
    const deps_ref = useRef(null);
    const destroy_ref = useRef(null);

    if (deps_changed(deps_ref.current, deps, comps || [])) {
        if (ref.current && destroy)
            destroy(ref.current);
        ref.current = create();
        deps_ref.current = deps;
    }

    destroy_ref.current = destroy;
    useEffect(() => {
        return () => destroy_ref.current?.(ref.current);
    }, []);

    return ref.current;
}

/* - useEvent(obj, event, handler)
 *
 * function Component(proxy) {
 *   useEvent(proxy, "changed");
 *
 *   ...
 * }
 *
 * The component will be re-rendered whenever "proxy" emits the
 * "changed" signal.  The "proxy" parameter can be null.
 *
 * When the optional "handler" is given, it will be called with the
 * arguments of the event.
 */

export function useEvent(obj, event, handler) {
    // We increase a (otherwise unused) state variable whenever the event
    // happens.  That reliably triggers a re-render.

    const [, forceUpdate] = useReducer(x => x + 1, 0);

    useEffect(() => {
        function update() {
            if (handler)
                handler.apply(null, arguments);
            forceUpdate();
        }

        obj?.addEventListener(event, update);
        return () => obj?.removeEventListener(event, update);
    }, [obj, event, handler]);
}

/* - useInit(func, deps, comps)
 *
 * function Component(arg) {
 *   useInit(() => {
 *     cockpit.spawn([ ..., arg ]);
 *   }, [arg]);
 *
 *   ...
 * }
 *
 * The function will be called once during the first render, and
 * whenever "arg" changes.
 *
 * "useInit(func, deps, comps)" is the same as "useObject(func, null,
 * deps, comps)" but if you want to emphasize that you just want to
 * run a function (instead of creating a object), it is clearer to use
 * the "useInit" name for that.  Also, "deps" are optional for
 * "useInit" and default to "[]".
 */

export function useInit(func, deps, comps, destroy = null) {
    return useObject(func, destroy, deps || [], comps);
}