All files / blong-browser/src/components/Portal Portal.tsx

91.07% Statements 255/280
73.17% Branches 30/41
66.66% Functions 6/9
91.07% Lines 255/280

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 2811x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x                     6x 1x 1x 1x 3x 3x 2x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 14x 14x 14x 14x       14x 14x 14x 14x 14x 14x 14x 14x 14x 5x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 56x 4x 5x 1x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 2x 2x 2x 7x 7x 7x 7x 6x 6x 6x 6x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 6x 6x 6x 6x           6x 6x 6x 6x 6x 6x 6x     6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x           6x 6x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Portal — top-level application shell.
 *
 * Renders a Menubar at the top, a TabView of open pages below it,
 * and wires menu item clicks to action dispatches.
 */
import {
    Menubar,
    ProgressSpinner,
    TabPanel,
    TabView,
    type MenuItem,
} from '../../primereact/index.js';
import './Portal.css';
 
import React, {Suspense, useCallback} from 'react';
import {useBlong} from '../../context/BlongContext.js';
import {usePortal} from '../../hooks/usePortal.js';
import testid from '../../lib/testid.js';
import {useAppStore} from '../../state/appStore.js';
import type {IMenuItem} from '../../types/portal.js';
import {Button} from '../Button/Button.js';
import {ErrorDialog} from '../Error/Error.js';
import {Hint} from '../Hint/Hint.js';
import {Loader} from '../Loader/Loader.js';
import {Text} from '../Text/Text.js';
 
// ── Per-tab error boundary ─────────────────────────────────────────────────
 
interface ITabErrorBoundaryState {
    error: Error | null;
}
 
class TabErrorBoundary extends React.Component<
    {children: React.ReactNode},
    ITabErrorBoundaryState
> {
    state: ITabErrorBoundaryState = {error: null};
 
    static getDerivedStateFromError(error: Error): ITabErrorBoundaryState {
        return {error};
    }
 
    render() {
        if (this.state.error) {
            return (
                <div className="blong-tab-error">
                    <i className="pi pi-exclamation-triangle blong-tab-error__icon" />
                    <p className="blong-tab-error__message">{this.state.error.message}</p>
                </div>
            );
        }
        return this.props.children;
    }
}
 
// ── Menu helpers ───────────────────────────────────────────────────────────
 
async function buildMenuModel(
    items: IMenuItem[] | undefined,
    command: MenuItem['command'],
    handler: ReturnType<typeof useBlong>['handler'],
): Promise<MenuItem[] | undefined> {
    if (!items) return undefined;
    return Promise.all(
        items.map(async item => {
            const action = typeof item === 'string' ? {method: item} : item;
            if ('items' in action) {
                // Derive a stable, language-independent group id from the first child method name.
                // e.g. items=['marine.coral.browse', ...] → groupId='marine'
                const firstChild = action.items?.find(
                    (i): i is string | {method: string} =>
                        typeof i === 'string' ||
                        (typeof i === 'object' && i !== null && 'method' in i),
                );
                const firstMethod =
                    typeof firstChild === 'string' ? firstChild : (firstChild?.method ?? '');
                const groupId = firstMethod.split('.')[0] || '';
                return {
                    label: action.title,
                    icon: action.icon,
                    items: await buildMenuModel(action.items, command, handler),
                    ...(groupId && {
                        template: (
                            item: MenuItem,
                            options: {
                                className: string;
                                labelClassName: string;
                                iconClassName: string;
                                onClick: (e: React.MouseEvent) => void;
                            },
                        ) => (
                            <a
                                className={options.className}
                                data-testid={`portal-menu-${groupId}`}
                                onClick={options.onClick}
                            >
                                {item.icon && <span className={options.iconClassName} />}
                                <span className={options.labelClassName}>{item.label}</span>
                            </a>
                        ),
                    }),
                } as MenuItem;
            } else if ('method' in action) {
                const {title, permission, icon, component} = (await handler[
                    `component/${action.method}`
                ](
                    typeof action.params === 'function'
                        ? action.params({})
                        : ((action.params as Record<string, unknown>) ?? {}),
                    {},
                )) as {
                    title: string;
                    permission?: string;
                    icon?: string;
                    component: React.ComponentType;
                };
                const menuId = (action.method ?? '').replace(/\./g, '-');
                return {
                    label: title,
                    icon,
                    data: {
                        action: action.method,
                        params: action.params,
                        title,
                        permission,
                        component,
                    },
                    command,
                    template: (
                        item: MenuItem,
                        options: {
                            className: string;
                            labelClassName: string;
                            iconClassName: string;
                            onClick: (e: React.MouseEvent) => void;
                        },
                    ) => (
                        <a
                            className={options.className}
                            data-testid={`portal-menu-${menuId}`}
                            onClick={options.onClick}
                        >
                            {item.icon && <span className={options.iconClassName} />}
                            <span className={options.labelClassName}>{item.label}</span>
                        </a>
                    ),
                } as MenuItem;
            } else return {label: action.title, icon: action.icon};
        }),
    );
}
 
export interface IPortalProps {
    /** Logo component or element */
    logo?: React.ReactNode;
    /** Right side content for the menubar */
    menubarEnd?: React.ReactNode;
    className?: string;
}
 
export function Portal({logo, menubarEnd, className = ''}: IPortalProps) {
    const {tabs, activeTabId, setActiveTab, closeTab, portalConfig} = usePortal();
    const {handler} = useBlong();
    const openTab = useAppStore(s => s.openTab);
 
    const command = useCallback(
        ({
            item: {
                data: {component, title, action, params},
            },
        }: {
            item: MenuItem;
        }) => {
            void (async () => {
                try {
                    openTab({
                        id: `${action}?${JSON.stringify(params)}`,
                        actionName: action,
                        params,
                        title,
                        component: await component(),
                    });
                } catch {
                    // Tab stays as loading spinner; dispatch may have shown an error already
                }
            })();
        },
        [openTab],
    );
 
    const activeIndex = tabs.findIndex(t => t.id === activeTabId);
    const [menu, setMenu] = React.useState<MenuItem[] | undefined>(undefined);
    React.useEffect(() => {
        buildMenuModel(portalConfig?.menu, command, handler).then(setMenu);
    }, [portalConfig?.menu, command, handler]);
 
    const start =
        logo ??
        (portalConfig?.title ? (
            <span className="blong-portal-brand">{portalConfig.title}</span>
        ) : undefined);
 
    return (
        <div className={`blong-portal ${className}`}>
            <Loader />
            <Hint />
            <ErrorDialog />
 
            <Menubar
                start={start}
                end={menubarEnd}
                className="blong-portal-menubar"
                {...(menu && {model: menu})}
            />
 
            <div className="blong-portal-body">
                <TabView
                    activeIndex={activeIndex >= 0 ? activeIndex : 0}
                    onTabChange={e => setActiveTab(tabs[e.index]?.id ?? null)}
                    scrollable
                    className="blong-portal-tabs"
                    renderActiveOnly={false}
                >
                    {tabs.map(tab => (
                        <TabPanel
                            __TYPE="TabPanel"
                            key={tab.id}
                            header={
                                <span
                                    className="blong-tab-header"
                                    {...testid(`portal.tab${tab.id}`)}
                                >
                                    {tab.dirty && <span className="blong-tab-dirty">● </span>}
                                    <Text>{tab.title}</Text>

                                    <Button
                                        icon="pi pi-times"
                                        className="p-button-text p-button-sm blong-tab-close p-0 vertical-align-baseline"
                                        onClick={e => {
                                            e.stopPropagation();
                                            closeTab(tab.id);
                                        }}
                                        {...testid(`portal.tab.close${tab.id}`)}
                                    />
                                </span>
                            }
                        >
                            {tab.component ? (
                                <TabErrorBoundary>
                                    <Suspense
                                        fallback={
                                            <div style={{padding: 32}}>
                                                <ProgressSpinner />
                                            </div>
                                        }
                                    >
                                        {React.createElement(
                                            tab.component as React.ComponentType<
                                                Record<string, unknown>
                                            >,
                                            {
                                                ...(tab.params as Record<string, unknown>),
                                                tabId: tab.id,
                                            },
                                        )}
                                    </Suspense>
                                </TabErrorBoundary>
                            ) : (
                                <div className="blong-portal-loading">
                                    <ProgressSpinner />
                                </div>
                            )}
                        </TabPanel>
                    ))}
                </TabView>
            </div>
        </div>
    );
}