All files / roosterjs-content-model-plugins/lib/edit/tabUtils handleTabOnTableCell.ts

100% Statements 22/22
73.91% Branches 17/23
100% Functions 1/1
100% Lines 22/22

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 631x 1x                                 1x         3x   3x   3x 3x 3x   3x 1x 1x     1x           1x       1x 1x 1x   1x 1x 1x     1x 1x       2x    
import { clearSelectedCells, insertTableRow } from 'roosterjs-content-model-api';
import {
    createSelectionMarker,
    getFirstSelectedTable,
    mutateBlock,
    normalizeTable,
    setParagraphNotImplicit,
    setSelection,
} from 'roosterjs-content-model-dom';
import type {
    ReadonlyContentModelDocument,
    ReadonlyContentModelTableCell,
} from 'roosterjs-content-model-types';
 
/**
 * When the cursor is on the last cell of a table, add new row and focus first new cell.
 * @internal
 */
export function handleTabOnTableCell(
    model: ReadonlyContentModelDocument,
    cell: ReadonlyContentModelTableCell,
    rawEvent: KeyboardEvent
) {
    const readonlyTableModel = getFirstSelectedTable(model)[0];
 
    Eif (readonlyTableModel) {
        // Check if cursor is on last cell of the table
        const lastRow = readonlyTableModel.rows[readonlyTableModel.rows.length - 1];
        const lastColumn = lastRow ? lastRow.cells.length - 1 : -1;
        const lastCell = lastRow?.cells[lastColumn];
 
        if (!rawEvent.shiftKey && lastCell && lastCell === cell) {
            const tableModel = mutateBlock(readonlyTableModel);
            insertTableRow(tableModel, 'insertBelow');
 
            // Clear Table selection
            clearSelectedCells(tableModel, {
                firstRow: tableModel.rows.length - 1,
                firstColumn: 0,
                lastRow: tableModel.rows.length - 1,
                lastColumn: lastColumn,
            });
            normalizeTable(tableModel, model.format);
 
            // Add selection marker to the first cell of the new row
            const markerParagraph =
                tableModel.rows[tableModel.rows.length - 1]?.cells[0]?.blocks[0];
            Eif (markerParagraph.blockType == 'Paragraph') {
                const marker = createSelectionMarker(model.format);
 
                mutateBlock(markerParagraph).segments.unshift(marker);
                setParagraphNotImplicit(markerParagraph);
                setSelection(tableModel.rows[tableModel.rows.length - 1].cells[0], marker);
            }
 
            rawEvent.preventDefault();
            return true;
        }
    }
 
    return false;
}