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

86.81% Statements 79/91
73.78% Branches 76/103
83.33% Functions 20/24
89.18% Lines 66/74

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                            16x 71x                                                           67x 67x         67x   67x 29x     67x             67x 67x 59x 16x 16x 16x 6x 6x 2x         67x 67x 67x 55x 2x 2x 1x 1x       67x 38x     38x     15x 15x   2x     1x   15x     8x             15x 15x                                                 67x   67x 167x   67x   4x 4x 4x 4x 2x         64x     64x 64x       67x 1x 1x             66x   67x           5x                                                     19x 19x       19x 19x   2x           19x                                       55x 55x 55x   55x 14x                   41x              
import {Dropdown} from '../primereact/index.js';
 
import type {IDropdownOption, IWidgetProps} from '@feasibleone/blong';
import {useEffect, useRef, useState} from 'react';
import {useWatch, type Control} from 'react-hook-form';
import {useBlongForm} from '../components/Form/FormContext.js';
import {useBlong} from '../context/BlongContext.js';
import {useOptionLabel} from '../hooks/useText.js';
import {dropdownRegistry, useDropdownVersion} from '../model/dropdownRegistry.js';
import {narrowingOf, parentKey} from './cascade.js';
 
type SelectOption = IDropdownOption;
 
function toOptions(data: unknown): SelectOption[] {
    if (!Array.isArray(data)) return [];
    return data.map((item: Record<string, unknown>) => ({
        ...item, // preserve extra properties (e.g., parent field keys for cascade filtering)
        label: String(item.label ?? item.name ?? item.value ?? item),
        value: item.value ?? item,
    }));
}
 
/**
 * Core rendering logic for DropdownWidget.
 * Receives `parentValue` already resolved — either from `useWatch` (inside a Form)
 * or `undefined` (standalone / no cascade needed).
 */
function DropdownCore({
    id,
    name,
    schema,
    value,
    onChange,
    onBlur,
    error,
    readOnly,
    disabled,
    parentValue,
    filterValues,
}: IWidgetProps & {parentValue: unknown; filterValues?: Record<string, unknown>}) {
    const {
        fetch: fetchAction,
        options: staticOptions,
        dropdown: dropdownKey,
        parent,
    } = schema.widget ?? {};
    const {handler} = useBlong();
    // A static option label is one the model declares, so it is a dictionary key.
    // An option the server produced is data — translated by the query that read
    // it, in the language the read asked for — and is rendered exactly as it
    // arrived (`D-635`).
    const optionLabel = useOptionLabel();
 
    const [options, setOptions] = useState<SelectOption[]>(() =>
        staticOptions ? toOptions(staticOptions) : [],
    );
    // Re-read the list when a write empties the cache.
    const dropdownVersion = useDropdownVersion();
 
    // Clear this widget's value when the parent selection is replaced. A record
    // the form loads moves the parent from nothing to its saved value, and the
    // pick beside it came from that same record: it survives. Only a narrowing
    // that was already in force, and now says something else, invalidates the
    // pick it narrowed to. @@D-875
    const prevNarrowingRef = useRef(narrowingOf([parentValue]));
    useEffect(() => {
        if (parent === undefined) return;
        const previous = prevNarrowingRef.current;
        const current = narrowingOf([parentValue]);
        if (previous === current) return;
        prevNarrowingRef.current = current;
        if (previous === '') return;
        Eif (value !== undefined && value !== null) onChange(undefined);
    }, [parentValue, parent, onChange, value]);
 
    // The explicit form narrows the same way: a field of `optionsFilter` that the
    // reader replaces drops the pick, and one the record loading fills does not.
    const filterNarrowing = filterValues ? narrowingOf(Object.values(filterValues)) : undefined;
    const prevFilterRef = useRef(filterNarrowing);
    useEffect(() => {
        if (filterNarrowing === undefined) return;
        const previous = prevFilterRef.current;
        if (previous === filterNarrowing) return;
        prevFilterRef.current = filterNarrowing;
        Eif (!previous) return;
        if (value !== undefined && value !== null) onChange(undefined);
    }, [filterNarrowing, onChange, value]);
 
    useEffect(() => {
        let cancelled = false;
 
        // Skip async load when static options are already provided
        if (staticOptions) return;
 
        // Priority 1: named dropdown via portal orchestrator (handles batching + caching)
        Eif (dropdownKey) {
            const loader = (key: string) =>
                (
                    handler.portalDropdownList({names: [key]}, {}) as Promise<
                        Record<string, unknown>
                    >
                ).then(result => toOptions(result[key]));
 
            dropdownRegistry
                .get(dropdownKey, loader)
                .then(data => {
                    Eif (!cancelled) setOptions(data);
                })
                .catch(() => {
                    // Error already surfaced by the central dispatch wrapper in
                    // BlongProvider. Widget renders with empty options.
                });
 
            return () => {
                cancelled = true;
            };
        }
 
        // Priority 2: explicit fetch action (re-fetch when parent value changes)
        if (!fetchAction) return;
        const params: Record<string, unknown> = {};
        if (parent && parentValue !== undefined) params[parentKey(parent)] = parentValue;
        (handler[fetchAction](params, {}) as Promise<unknown>)
            .then(data => {
                if (!cancelled) setOptions(toOptions(data));
            })
            .catch(() => {});
        return () => {
            cancelled = true;
        };
        // eslint-disable-next-line @eslint-react/exhaustive-deps -- parent and staticOptions intentionally omitted
    }, [fetchAction, dropdownKey, handler, parentValue, dropdownVersion]);
 
    // Filter options by parent value (client-side cascade).
    // Supports both named-key format ({continent: 1}) and generic parent key ({parent: 1}).
    // `optionsFilter` is the explicit form — `{optionProperty: formField}` — for a list
    // whose options carry the key under another name, or that depend on more than one
    // field. An empty field leaves the list whole, so the first pick is never blocked.
    // @@D-615
    const optionsFilter = schema.widget?.optionsFilter;
    // Only the model's own option list is translated here; a fetched list is data.
    const translatedOptions = staticOptions
        ? options.map(o => ({...o, label: optionLabel(o)}))
        : options;
    const visibleOptions = optionsFilter
        ? translatedOptions.filter(o => {
              const candidate = o as unknown as Record<string, unknown>;
              return Object.entries(optionsFilter).every(([optionProperty, formField]) => {
                  const want = filterValues?.[formField];
                  if (want === undefined || want === null || want === '') return true;
                  return String(candidate[optionProperty]) === String(want);
              });
          })
        : parent && parentValue !== undefined
          ? translatedOptions.filter(o => {
                const opt = o as unknown as Record<string, unknown>;
                // The value is read at the field's path, the option matched under
                // the field's own name. @@D-875
                const key = parentKey(parent);
                return opt[key] === parentValue || opt['parent'] === parentValue;
            })
          : translatedOptions;
 
    if (readOnly) {
        const found = visibleOptions.find(o => o.value === value);
        return (
            <span className="blong-display">
                {found?.label ?? (value != null ? String(value) : '')}
            </span>
        );
    }
 
    const isParentEmpty = !!parent && (parentValue === undefined || parentValue === null);
 
    return (
        <Dropdown
            inputId={id ?? name}
            data-testid={id ?? name}
            value={value}
            options={visibleOptions}
            onChange={e => onChange(e.value)}
            onHide={onBlur}
            disabled={disabled || isParentEmpty}
            className={`blong-dropdown w-full ${error ? 'p-invalid' : ''}`}
            showClear={!schema.fieldRequired}
            filter={visibleOptions.length > 8}
            placeholder={schema.placeholder ?? 'Select…'}
        />
    );
}
 
/**
 * Connected variant — uses `useWatch` to subscribe only to the specific parent field.
 * This component is only rendered when inside a Form that has a `control` and a `parent`
 * field is configured.  It re-renders only when the parent field value changes, not on
 * every keystroke in any other field.
 */
function ConnectedDropdown({
    parentFieldName,
    control,
    filterFields,
    ...props
}: IWidgetProps & {
    parentFieldName?: string;
    control: Control<Record<string, unknown>>;
    filterFields?: string[];
}) {
    const watched = parentFieldName ? [parentFieldName, ...(filterFields ?? [])] : filterFields;
    const values = useWatch({
        control,
        name: (watched ?? []) as string[],
    }) as unknown[] | undefined;
    const parentValue = parentFieldName ? values?.[0] : undefined;
    const filterValues = filterFields
        ? Object.fromEntries(
              filterFields.map((field, index) => [
                  field,
                  values?.[(parentFieldName ? 1 : 0) + index],
              ]),
          )
        : undefined;
    return (
        <DropdownCore
            {...props}
            parentValue={parentValue}
            filterValues={filterValues}
        />
    );
}
 
/**
 * DropdownWidget — wraps PrimeReact Dropdown with cascade-filtering support.
 *
 * When a `parent` field is configured in the schema and the widget is rendered inside
 * a Form, it delegates to `ConnectedDropdown` which subscribes only to that specific
 * parent field via `useWatch`.  This means the dropdown only rerenders when the parent
 * field changes — not on every keystroke in any field.
 *
 * When used standalone (no Form context / no parent), rendering is handled directly.
 */
export function DropdownWidget(props: IWidgetProps) {
    const formCtx = useBlongForm();
    const parent = props.schema.widget?.parent;
    const filterFields = Object.values(props.schema.widget?.optionsFilter ?? {});
 
    if (formCtx?.control && (parent || filterFields.length > 0)) {
        return (
            <ConnectedDropdown
                {...props}
                parentFieldName={parent}
                filterFields={filterFields.length > 0 ? filterFields : undefined}
                control={formCtx.control}
            />
        );
    }
 
    return (
        <DropdownCore
            {...props}
            parentValue={undefined}
        />
    );
}