All files / core/blong-browser/src/widgets NavigatorWidget.tsx

76.92% Statements 70/91
63.49% Branches 40/63
76.19% Functions 16/21
77.1% Lines 64/83

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                                                              6x 6x   6x 10x           10x     6x 10x 10x 10x 5x   5x 5x       6x       11x       33x 11x 4x       11x 11x 11x 11x 11x 11x 11x     11x   11x 4x 2x   11x 4x 2x 2x 4x 2x     2x   2x   11x                     6x 4x 4x 4x 4x   3x       4x     3x 3x         11x 11x   11x 4x   2x 2x 4x     2x 2x                                 2x       2x                           11x 4x 2x           11x           1x                             11x                                 1x                  
/**
 * NavigatorWidget — tree navigator widget.
 *
 * Wraps the Navigator component as a schema-driven widget. Data is loaded
 * from `widget.listAction` (or supplied as the field value). Selection is
 * published via the `onSelect` prop so sibling table widgets can cascade-
 * filter using `widget.parent` / `widget.master`.
 *
 * Schema config:
 *   widget.type: 'navigator'
 *   widget.listAction   — action name to load tree nodes
 *   widget.resultSet    — response property containing rows (default 'items')
 *   widget.keyField     — primary key field (default 'id')
 *   widget.parentField  — parent key field (default 'parentId')
 *   widget.labelField   — display label field (default 'name')
 *   widget.label        — panel title
 */
import type {IWidgetProps} from '@feasibleone/blong';
import React, {useEffect, useMemo, useState} from 'react';
import {useBlong} from '../context/BlongContext.js';
import {Tree, type TreeNode} from '../primereact/index.js';
import {useAppStore} from '../state/appStore.js';
 
type Row = Record<string, unknown>;
 
function buildTree(
    items: Row[],
    keyField: string,
    parentField: string,
    labelField: string,
): TreeNode[] {
    const roots: TreeNode[] = [];
    const map = new Map<unknown, TreeNode>();
 
    for (const item of items) {
        const node: TreeNode = {
            key: String(item[keyField]),
            label: String(item[labelField] ?? item[keyField]),
            data: item,
            children: [],
        };
        map.set(item[keyField], node);
    }
 
    for (const item of items) {
        const parentKey = item[parentField];
        const node = map.get(item[keyField])!;
        if (parentKey == null || !map.has(parentKey)) {
            roots.push(node);
        } else {
            const parent = map.get(parentKey)!;
            parent.children = [...(parent.children ?? []), node];
        }
    }
 
    return roots;
}
 
export function NavigatorWidget({name, schema, value, onSelect}: IWidgetProps) {
    const {handler, log} = useBlong();
    // The nodes are sorted by the label the reader sees, in the language they are
    // reading: a Bulgarian page whose list mixes translated names with the stored
    // English ones must not push every Cyrillic name below every Latin one.
    const language = useAppStore(state => state.language);
    const collator = useMemo(
        () => new Intl.Collator(language ?? undefined, {sensitivity: 'base', numeric: true}),
        [language],
    );
 
    const widget = schema.widget;
    const listAction = widget?.listAction ?? '';
    const resultSet = widget?.resultSet ?? 'items';
    const keyField = widget?.keyField ?? 'id';
    const parentField = widget?.parentField ?? 'parentId';
    const labelField = widget?.labelField ?? 'name';
    const title = widget?.label;
 
    // Use field value as static data when listAction is not set
    const staticRows = !listAction && Array.isArray(value) ? (value as Row[]) : undefined;
 
    const [treeData, setTreeData] = useState<TreeNode[]>(() => {
        if (staticRows) return buildTree(staticRows, keyField, parentField, labelField);
        return [];
    });
    const [expandedKeys, setExpandedKeys] = useState<Record<string, boolean>>(() => {
        if (staticRows) {
            const keys: Record<string, boolean> = {};
            for (const item of staticRows) {
                if (item[parentField] == null) {
                    keys[String(item[keyField])] = true;
                }
            }
            return keys;
        }
        return {};
    });
    const setTreeDataAndExpand = React.useCallback(
        async (items: Row[]) => {
            // Label order, whatever order the server answered in. A navigator is
            // read by a person scanning for a name, and the read that fills it is a
            // plain `find` over another table: ordering it server-side would mean
            // naming a column this page does not own — the parent's name may live in
            // `core_resource` with no column of its own (`Unknown column
            // 'applicationName' in 'order clause'`). Sorting what arrived costs
            // nothing and cannot fail, and sorting the rows also sorts each
            // sibling group, because `buildTree` appends children in row order.
            // `@@D-827`
            const label = (row: Row) => String(row[labelField] ?? row[keyField] ?? '');
            const rows = [...items].sort((a, b) => collator.compare(label(a), label(b)));
            const data: TreeNode[] = buildTree(rows, keyField, parentField, labelField);
            setTreeData(data);
            setExpandedKeys(
                data.reduce(
                    (acc, node) => ({...acc, [String(node.key)]: true}),
                    {} as Record<string, boolean>,
                ),
            );
            if (rows.length) {
                // The node a reader sees at the top of the list is the one that
                // starts selected, so the tables beside it show that branch.
                setSelectedKey(String(rows[0][keyField]));
                onSelect?.(name, {row: rows[0], index: 0});
            }
        },
        [keyField, parentField, labelField, collator, name, onSelect],
    );
    const [loading, setLoading] = useState(false);
    const [selectedKey, setSelectedKey] = useState<string | null>(null);
 
    useEffect(() => {
        if (!listAction) return;
        // eslint-disable-next-line @eslint-react/set-state-in-effect
        setLoading(true);
        const params = widget?.listParams ?? {};
        void (handler[listAction](params, {}) as Promise<Record<string, unknown>>)
            .then(result => {
                let items: Row[];
                if (resultSet && Array.isArray((result as Record<string, unknown>)[resultSet])) {
                    items = (result as Record<string, unknown>)[resultSet] as Row[];
                } else Eif (Array.isArray(result)) {
                    items = result as Row[];
                } else {
                    // Try first array property as a fallback, warn if used
                    const firstArray = Object.values(result as Record<string, unknown>).find(v =>
                        Array.isArray(v),
                    );
                    if (firstArray) {
                        log?.warn?.(
                            `[NavigatorWidget] listAction "${listAction}" did not return expected resultSet "${resultSet}"; using first array property.`,
                        );
                        items = firstArray as Row[];
                    } else {
                        items = [];
                    }
                }
                setTreeDataAndExpand(items).catch(err => {
                    log?.error?.('[NavigatorWidget] Error setting tree data:', err);
                });
            })
            .finally(() => setLoading(false));
    }, [
        listAction,
        widget?.listParams,
        resultSet,
        keyField,
        parentField,
        labelField,
        handler,
        setTreeDataAndExpand,
        log,
    ]);
 
    // Sync static data changes
    useEffect(() => {
        if (staticRows) {
            setTreeDataAndExpand(staticRows).catch(err => {
                log?.error?.('[NavigatorWidget] Error setting tree data:', err);
            });
        }
    }, [staticRows, setTreeDataAndExpand, log]);
 
    const handleSelection = (key: string | null) => {
        // A navigator has no "nothing selected" state to publish: the tables beside it
        // are filtered by its selection, and the page renders none of them without one.
        // PrimeReact reports a cleared selection when the selected node is clicked again
        // (`metaKeySelection` defaults to false, so a plain click unselects), which is a
        // gesture this widget must not carry into the page — keep the node selected.
        Eif (key == null) return;
        setSelectedKey(key);
        const findNode = (nodes: TreeNode[]): TreeNode | undefined => {
            for (const n of nodes) {
                if (n.key === key) return n;
                const found = findNode(n.children ?? []);
                if (found) return found;
            }
        };
        const node = findNode(treeData);
        // Publish selection as {row, index: 0} via onSelect so sibling table widgets
        // can cascade-filter using widget.parent / widget.master
        onSelect?.(name, node ? {row: node.data as Row, index: 0} : null);
    };
 
    return (
        <div
            className="blong-navigator w-full"
            // `minHeight: 0` on both the column and the tree: a flex item refuses to
            // shrink below its content, so without it a long list pushes the tree past
            // the panel and the page's bottom edge — `overflow: auto` never gets a
            // chance to scroll.
            style={{height: '100%', minHeight: 0, display: 'flex', flexDirection: 'column'}}
        >
            {title && <h4 className="blong-navigator__title">{title}</h4>}
            <Tree
                value={treeData}
                expandedKeys={expandedKeys}
                onToggle={e => setExpandedKeys(e.value)}
                loading={loading}
                selectionMode="single"
                selectionKeys={selectedKey ?? undefined}
                onSelectionChange={e => handleSelection(e.value as string | null)}
                className="border-none p-0 blong-navigator__tree"
                // filter # disabled due to interfering with expandedKeys state; would need to reset expandedKeys on filter change to work properly
                filterPlaceholder="Search…"
                style={{flex: 1, minHeight: 0, overflow: 'auto'}}
            />
        </div>
    );
}