Debian Codegraph @

pkg/shell/nav.tsx

raw
1 /*
2 * Copyright (C) 2024 Red Hat, Inc.
3 * SPDX-License-Identifier: LGPL-2.1-or-later
4 */
5
6 import cockpit from "cockpit";
7
8 import React, { useEffect, useState } from 'react';
9
10 import { Button } from "@patternfly/react-core/dist/esm/components/Button/index.js";
11 import { Nav } from "@patternfly/react-core/dist/esm/components/Nav/index.js";
12 import { SearchInput } from "@patternfly/react-core/dist/esm/components/SearchInput/index.js";
13 import { Tooltip, TooltipPosition } from "@patternfly/react-core/dist/esm/components/Tooltip/index.js";
14 import { ContainerNodeIcon, ExclamationCircleIcon, ExclamationTriangleIcon, InfoCircleIcon } from '@patternfly/react-icons';
15 import { Icon } from "@patternfly/react-core/dist/esm/components/Icon/index.js";
16
17 import { Status } from "notifications";
18 import { Location, encode_location, ManifestItem } from "./util.jsx";
19 import { ShellState } from "./state";
20 import { ManifestKeyword } from "./manifests";
21
22 const _ = cockpit.gettext;
23
24 export const SidebarToggle = () => {
25 const [active, setActive] = useState(false);
26
27 useEffect(() => {
28 /* This is a HACK for catching lost clicks on the pages which live in iframes so as to close dropdown menus on the shell.
29 * Note: Clicks on an <iframe> element won't trigger document.documentElement listeners, because it's literally different page with different security domain.
30 * However, when clicking on an iframe moves focus to its content's window that triggers the main window.blur event.
31 * Additionally, when clicking on an element in the same iframe make sure to unset the 'active' state of the 'System' dropdown selector.
32 */
33 const handleClickOutside = (ev: Event) => {
34 if ((ev.target as Element).id == "nav-system-item")
35 return;
36
37 setActive(false);
38 };
39
40 ["blur", "click"].map(ev_type => window.addEventListener(ev_type, handleClickOutside));
41
42 return () => {
43 ["blur", "click"].map(ev_type => window.removeEventListener(ev_type, handleClickOutside));
44 };
45 }, []);
46
47 useEffect(() => {
48 document.getElementById("nav-system")!.classList.toggle("interact", active);
49 }, [active]);
50
51 return (
52 <Button icon={
53 <Icon size="xl">
54 <ContainerNodeIcon />
55 </Icon>}
56 className={"pf-v6-c-select__toggle ct-nav-toggle " + (active ? "active" : "")}
57 id="nav-system-item" variant="plain"
58 onClick={() => setActive(!active)}>{_("System")}</Button>
59 );
60 };
61
62 interface ItemGroup<T> {
63 name: string;
64 items: T[];
65 action?: {
66 label: string;
67 target: Partial<Location>;
68 } | undefined;
69 }
70
71 interface CockpitNavProps<T, X extends T> {
72 groups: ItemGroup<T>[];
73 selector: string;
74 current: string;
75 filtering: (item: T, term: string) => X | null;
76 sorting: (a: X, b: X) => number;
77 item_render: (item: X, term: string) => React.ReactNode;
78 jump: (loc: Partial<Location>) => void;
79 }
80
81 interface CockpitNavState {
82 search: string;
83 current: string;
84 }
85
86 export class CockpitNav<T, X extends T> extends React.Component {
87 props: CockpitNavProps<T, X>;
88 state: CockpitNavState;
89
90 constructor(props : CockpitNavProps<T, X>) {
91 super(props);
92
93 this.state = {
94 search: "",
95 current: props.current,
96 };
97
98 this.clearSearch = this.clearSearch.bind(this);
99 this.props = props;
100 }
101
102 componentDidMount() {
103 const sel = this.props.selector;
104 // Click on active menu item (when using arrows to navigate through menu)
105 function clickActiveItem() {
106 const cur = document.activeElement;
107 if (cur instanceof HTMLInputElement) {
108 const el = document.querySelector<HTMLElement>("#" + sel + " li:first-of-type a");
109 if (el)
110 el.click();
111 } else if (cur instanceof HTMLElement) {
112 cur.click();
113 } else {
114 console.error("Active element not a HTMLElement");
115 }
116 }
117
118 // Move focus to next item in menu (when using arrows to navigate through menu)
119 // With arguments it is possible to change direction
120 function focusNextItem(begin: number, step: number) {
121 const cur = document.activeElement;
122 const all = Array.from(document.querySelectorAll<HTMLElement>("#" + sel + " li a"));
123 if (cur instanceof HTMLInputElement && all.length > 0) {
124 if (begin < 0)
125 begin = all.length - 1;
126 all[begin].focus();
127 } else {
128 let i = all.findIndex(item => item === cur);
129 i += step;
130 if (i < 0 || i >= all.length)
131 document.querySelector<HTMLElement>("#" + sel + " .pf-v6-c-text-input-group__text-input")?.focus();
132 else
133 all[i].focus();
134 }
135 }
136
137 const navigate_apps = (ev: KeyboardEvent) => {
138 if (ev.key == "Enter")
139 clickActiveItem();
140 else if (ev.key == "ArrowDown")
141 focusNextItem(0, 1);
142 else if (ev.key == "ArrowUp")
143 focusNextItem(-1, -1);
144 else if (ev.key == "Escape") {
145 this.setState({ search: "" });
146 document.querySelector<HTMLElement>("#" + sel + " .pf-v6-c-text-input-group__text-input")?.focus();
147 }
148 };
149
150 document.getElementById(sel)?.addEventListener("keyup", navigate_apps);
151 }
152
153 static getDerivedStateFromProps(nextProps: CockpitNavProps<void, void>, prevState: CockpitNavState) {
154 if (nextProps.current !== prevState.current)
155 return {
156 search: "",
157 current: nextProps.current,
158 };
159 return null;
160 }
161
162 clearSearch() {
163 this.setState({ search: "" });
164 }
165
166 render() {
167 const groups: ItemGroup<X>[] = [];
168 const term = this.state.search.toLowerCase();
169 this.props.groups.forEach(g => {
170 const new_items = g.items.map(i => this.props.filtering(i, term)).filter(i => i != null);
171 new_items.sort(this.props.sorting);
172 if (new_items.length > 0)
173 groups.push({ name: g.name, items: new_items, action: g.action });
174 });
175
176 return (
177 <>
178 <SearchInput placeholder={_("Search")} value={this.state.search} onChange={(_, search) => this.setState({ search })} onClear={() => this.setState({ search: "" })} className="search" />
179 <Nav>
180 { groups.map(g =>
181 <section className="pf-v6-c-nav__section" aria-labelledby={"section-title-" + g.name} key={g.name}>
182 <div className="nav-group-heading">
183 <h2 className="pf-v6-c-nav__section-title" id={"section-title-" + g.name}>{g.name}</h2>
184 { g.action &&
185 <a className="pf-v6-c-nav__section-title nav-item"
186 href={encode_location(g.action.target)}
187 onClick={ ev => {
188 if (g.action)
189 this.props.jump(g.action.target);
190 ev.preventDefault();
191 }}>
192 {g.action.label}
193 </a>
194 }
195 </div>
196 <ul className="pf-v6-c-nav__list">
197 {g.items.map(i => this.props.item_render(i, this.state.search.toLowerCase()))}
198 </ul>
199 </section>
200 )}
201 { groups.length < 1 && <span className="non-menu-item no-results">{_("No results found")}</span> }
202 { this.state.search !== "" && <span className="non-menu-item"><Button variant="link" onClick={this.clearSearch} className="nav-item-hint">{_("Clear search")}</Button></span> }
203 </Nav>
204 </>
205 );
206 }
207 }
208
209 function PageStatus({ status, name } : { status: Status, name: string }) {
210 // Generate name for the status
211 const desc_parts = name.toLowerCase().split(" ");
212 desc_parts.push(status.type || "");
213 const desc = desc_parts.join("-");
214
215 let statusIcon = <Icon status="info"><InfoCircleIcon /></Icon>;
216 switch (status.type) {
217 case "error":
218 statusIcon = <Icon status="danger"><ExclamationCircleIcon /></Icon>;
219 break;
220 case "warning":
221 statusIcon = <Icon status="warning"><ExclamationTriangleIcon /></Icon>;
222 break;
223 }
224
225 return (
226 <Tooltip id={desc + "-tooltip"} content={status.title}
227 position={TooltipPosition.right}>
228 <span id={desc} className="nav-item-status">
229 {statusIcon}
230 </span>
231 </Tooltip>
232 );
233 }
234
235 function FormattedText({ keyword, term } : { keyword: string, term: string }) {
236 function split_text(text: string, term: string) {
237 const b = text.toLowerCase().indexOf(term);
238 const e = b + term.length;
239 return [text.substring(0, b), text.substring(b, e), text.substring(e, text.length)];
240 }
241
242 const s = split_text(keyword, term);
243 return (
244 <>{s[0]}<mark>{s[1]}</mark>{s[2]}</>
245 );
246 }
247
248 export function CockpitNavItem(props : {
249 name: string;
250 header?: string;
251 className?: string;
252 active: boolean;
253 status: Status | null;
254 keyword: string;
255 term: string;
256 href: string;
257 onClick: () => void;
258 actions?: React.ReactNode;
259 }) {
260 const s = props.status;
261 const name_matches = props.keyword === props.name.toLowerCase();
262 let header_matches = false;
263 if (props.header)
264 header_matches = props.keyword === props.header.toLowerCase();
265
266 const classes = props.className ? [props.className] : [];
267 classes.push("pf-v6-c-nav__item", "nav-item");
268
269 return (
270 <li className={classes.join(" ")}>
271 <a className={"pf-v6-c-nav__link" + (props.active ? " pf-m-current" : "")}
272 aria-current={props.active && "page"}
273 href={props.href}
274 onClick={ev => {
275 props.onClick();
276 ev.preventDefault();
277 }}>
278 <span className="pf-v6-c-nav__link-text">
279 { props.header && <span className="nav-item-hint">{header_matches ? <FormattedText keyword={props.header} term={props.term} /> : props.header}</span> }
280 <span className="nav-item-name">
281 { name_matches ? <FormattedText keyword={props.name} term={props.term} /> : props.name }
282 </span>
283 </span>
284 <span className="pf-v6-c-nav__link-icon">
285 {s && s.type && <PageStatus status={s} name={props.name} />}
286 </span>
287 { !name_matches && !header_matches && props.keyword && <span className="nav-item-hint nav-item-hint-contains">{_("Contains:")} <FormattedText keyword={props.keyword} term={props.term} /></span> }
288 </a>
289 <span className="nav-item-actions nav-host-action-buttons">
290 {props.actions}
291 </span>
292 </li>
293 );
294 }
295
296 interface PageKeyword {
297 keyword: string;
298 score: number;
299 goto: string | null;
300 }
301
302 interface PageItem extends ManifestItem {
303 keyword: PageKeyword;
304 }
305
306 export const PageNav = ({ state } : { state: ShellState }) => {
307 const {
308 current_machine,
309 current_manifest_item,
310 current_machine_manifest_items,
311 page_status,
312 } = state;
313
314 if (!current_machine || current_machine.state != "connected")
315 return null;
316
317 cockpit.assert(current_machine_manifest_items && current_manifest_item);
318
319 // Filtering of navigation by term
320 function keyword_filter(item: ManifestItem, term: string): PageItem | null {
321 function keyword_relevance(current_best: PageKeyword, item: ManifestKeyword) {
322 const translate = item.translate || false;
323 const weight = item.weight || 0;
324 let score;
325 let _m = "";
326 let best: PageKeyword = { keyword: "", score: -1, goto: null };
327 item.matches.forEach(m => {
328 if (translate)
329 _m = _(m);
330 score = -1;
331 // Best score when starts in translate language
332 if (translate && _m.indexOf(term) == 0)
333 score = 4 + weight;
334 // Second best score when starts in English
335 else if (m.indexOf(term) == 0)
336 score = 3 + weight;
337 // Substring consider only when at least 3 letters were used
338 else if (term.length >= 3) {
339 if (translate && _m.indexOf(term) >= 0)
340 score = 2 + weight;
341 else if (m.indexOf(term) >= 0)
342 score = 1 + weight;
343 }
344 if (score > best.score) {
345 best = { keyword: m, score, goto: item.goto || null };
346 }
347 });
348 if (best.score > current_best.score) {
349 current_best = best;
350 }
351 return current_best;
352 }
353
354 const new_item: PageItem = Object.assign({ keyword: { keyword: "", score: -1, goto: null } }, item);
355 if (!term)
356 return new_item;
357 const best_keyword = new_item.keywords.reduce(keyword_relevance, { keyword: "", score: -1, goto: null });
358 if (best_keyword.score > -1) {
359 new_item.keyword = best_keyword;
360 return new_item;
361 }
362 return null;
363 }
364
365 // Rendering of separate navigation menu items
366 function nav_item(item: PageItem, term: string) {
367 const active = current_manifest_item?.path === item.path;
368
369 // Parse path
370 let path = item.path;
371 let hash = item.hash;
372 if (item.keyword.goto) {
373 if (item.keyword.goto[0] === "/")
374 path = item.keyword.goto.substring(1);
375 else
376 hash = item.keyword.goto;
377 }
378
379 // Parse page status
380 let status = null;
381 if (page_status[current_machine!.key])
382 status = page_status[current_machine!.key][item.path];
383
384 const target_location = { host: current_machine!.address, path, hash };
385
386 return (
387 <CockpitNavItem key={item.label}
388 name={item.label}
389 active={active}
390 status={status}
391 keyword={item.keyword.keyword}
392 term={term}
393 href={encode_location(target_location)}
394 onClick={() => state.jump(target_location)} />
395 );
396 }
397
398 const groups: ItemGroup<ManifestItem>[] = [
399 {
400 name: _("Apps"),
401 items: current_machine_manifest_items.ordered("dashboard"),
402 }, {
403 name: _("System"),
404 items: current_machine_manifest_items.ordered("menu"),
405 }, {
406 name: _("Tools"),
407 items: current_machine_manifest_items.ordered("tools"),
408 }
409 ].filter(i => i.items.length > 0);
410
411 if (current_machine_manifest_items.items.apps && groups.length === 3)
412 groups[0].action = {
413 label: _("Edit"),
414 target: {
415 host: current_machine.address,
416 path: current_machine_manifest_items.items.apps.path,
417 }
418 };
419
420 return <CockpitNav groups={groups}
421 selector="host-apps"
422 item_render={nav_item}
423 filtering={keyword_filter}
424 sorting={(a, b) => { return b.keyword.score - a.keyword.score }}
425 current={current_manifest_item.path}
426 jump={state.jump} />;
427 };