All files / core/blong-browser/src/widgets/table useTableDropdowns.ts

77.27% Statements 34/44
65.21% Branches 15/23
78.26% Functions 18/23
75.67% Lines 28/37

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                                                                        124x   124x 292x 292x       124x   124x 124x 124x 124x 5x 5x   5x   5x   5x     5x   5x 5x         124x           124x 29x             124x   124x 292x 292x           124x 124x 124x                                       124x    
/**
 * The option lists a table needs before it can render a cell.
 *
 * A column that names a dropdown holds a key, and a key is not what a reader wants:
 * the cell shows the option's label. The caller may pass the options, and a model page
 * does not — so the missing ones are loaded through the portal orchestrator, the same
 * call a dropdown widget makes. A pivot's slot list is loaded the same way.
 *
 * The hook also reports what the rendered rows depend on: PrimeReact keeps a row as it
 * painted it, so options that arrive after the first paint would leave the stored id on
 * screen until something remounts the table. That is what the signature is for.
 */
import type {IDropdownOption} from '@feasibleone/blong';
import {useEffect, useMemo, useState} from 'react';
import {dropdownRegistry, useDropdownVersion} from '../../model/dropdownRegistry.js';
import type {Row} from './model.js';
 
export interface ITableDropdownsOptions {
    /** The columns the table renders, and the schema they came from. */
    columns: string[];
    properties?: Record<string, {widget?: {dropdown?: string; body?: string}}>;
    /** The options the caller already has, by dropdown name. */
    dropdowns?: Record<string, unknown[]>;
    /** The dropdown naming a pivot's slots, when the table is a pivot. */
    pivotDropdown?: string;
    /** Loads the named lists — `handler.portalDropdownList`. */
    load?: (names: string[]) => Promise<Record<string, unknown>>;
}
 
export function useTableDropdowns({
    columns,
    properties,
    dropdowns,
    pivotDropdown,
    load,
}: ITableDropdownsOptions) {
    const columnDropdownKeys = useMemo(
        () =>
            columns
                .map(field => properties?.[field]?.widget?.dropdown)
                .filter((key): key is string => typeof key === 'string' && key.length > 0),
        [columns, properties],
    );
 
    const [loaded, setLoaded] = useState<Record<string, unknown[]>>({});
    // Re-read the labels when a write empties the cache.
    const dropdownVersion = useDropdownVersion();
    useEffect(() => {
        const missing = columnDropdownKeys.filter(key => !dropdowns?.[key] && !loaded[key]);
        if (!missing.length || !load) return;
        let cancelled = false;
        Promise.all(
            missing.map(name =>
                load([name])
                    .then(
                        result => [name, Array.isArray(result[name]) ? result[name] : []] as const,
                    )
                    .catch(() => [name, []] as const),
            ),
        ).then(entries => {
            if (!cancelled) setLoaded(prev => ({...prev, ...Object.fromEntries(entries)}));
        });
        return () => {
            cancelled = true;
        };
    }, [columnDropdownKeys, dropdowns, loaded, load, dropdownVersion]);
 
    /** The caller's map wins; the loaded one fills the gaps. */
    const resolvedDropdowns = useMemo(() => ({...loaded, ...dropdowns}), [loaded, dropdowns]);
 
    /**
     * What the rendered rows depend on, beyond the data: how many options each label
     * column has. A table keyed on it remounts exactly once, when they arrive. @@D-612
     */
    const signature = columnDropdownKeys
        .map(key => `${key}:${resolvedDropdowns[key]?.length ?? 0}`)
        .join('|');
 
    /**
     * The label columns a list read should project instead of the keys: a row then
     * arrives with its names attached and no cell is resolved on the fly. @@D-614
     */
    const labelFields = useMemo(
        () =>
            columns
                .map(field => properties?.[field]?.widget?.body)
                .filter((field): field is string => typeof field === 'string'),
        [columns, properties],
    );
 
    // A pivot's slot rows come from a named dropdown, which the caller may not have
    // passed either.
    const [pivotOptions, setPivotOptions] = useState<Row[] | undefined>(undefined);
    useEffect(() => {
        Eif (!pivotDropdown || dropdowns?.[pivotDropdown] || !load) return;
        let cancelled = false;
        const loader = (name: string): Promise<IDropdownOption[]> =>
            load([name]).then(result => {
                const data = result[name];
                return (Array.isArray(data) ? data : []) as IDropdownOption[];
            });
        dropdownRegistry
            .get(pivotDropdown, loader)
            .then(data => {
                if (!cancelled) setPivotOptions(data as Row[]);
            })
            .catch(() => {
                // Error surfaced by the central dispatch wrapper; render without rows.
            });
        return () => {
            cancelled = true;
        };
    }, [pivotDropdown, dropdowns, load, dropdownVersion]);
 
    return {resolvedDropdowns, signature, labelFields, pivotOptions};
}