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

100% Statements 19/19
100% Branches 6/6
100% Functions 5/5
100% Lines 15/15

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                                            124x 124x 124x 292x     292x 292x 6x     124x     124x   124x   3x 2x 2x           124x   124x    
/**
 * What a row has picked while it is being edited.
 *
 * A row being edited keeps its draft to itself until the row is saved, and the cell
 * editors are mounted the moment the row enters edit mode. A cell whose list is
 * narrowed by a sibling would therefore keep the list it computed at that moment — for
 * a new row, the whole list, because the sibling is still empty — and the pick that
 * should narrow it would change nothing on screen. So the table remembers the picks in
 * the fields a cascade depends on, hands them to the cells through a context (a
 * consumer re-renders past PrimeReact's memoized cell), and forgets them when the row
 * stops being edited. `@@D-617`
 */
import {useCallback, useMemo, useState} from 'react';
import {parentKey} from '../cascade.js';
import {KEY, type Row} from './model.js';
 
/** A column whose list is narrowed by a sibling, or by its `parent`. */
export interface ICascadeColumn {
    fieldSchema: {widget?: {parent?: string; optionsFilter?: Record<string, string>}};
}
 
export function useRowDrafts(columns: ICascadeColumn[]) {
    const cascadeFields = useMemo(() => {
        const fields = new Set<string>();
        for (const col of columns) {
            const widget = col.fieldSchema.widget;
            // Picks are recorded under the row's own field name, which is the leaf of
            // the path a model declares. @@D-875
            if (widget?.parent) fields.add(parentKey(widget.parent));
            for (const rowField of Object.values(widget?.optionsFilter ?? {})) {
                fields.add(String(rowField));
            }
        }
        return fields;
    }, [columns]);
 
    const [rowDrafts, setRowDrafts] = useState<Record<string, Row>>({});
 
    const recordRowDraft = useCallback(
        (row: Row, field: string, value: unknown) => {
            if (!cascadeFields.has(field)) return;
            const key = String(row[KEY]);
            setRowDrafts(prev => ({...prev, [key]: {...prev[key], [field]: value}}));
        },
        [cascadeFields],
    );
 
    /** A row that is no longer edited leaves no picks behind. */
    const clearRowDrafts = useCallback(() => setRowDrafts({}), []);
 
    return {rowDrafts, recordRowDraft, clearRowDrafts};
}