All files / roosterjs-content-model-dom/lib/modelApi/editing getClosestAncestorBlockGroupIndex.ts

100% Statements 10/10
100% Branches 9/9
100% Functions 1/1
100% Lines 9/9

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                            1x     859x     842x 869x   869x       233x 636x         37x       572x    
import type {
    ContentModelBlockGroup,
    ContentModelBlockGroupType,
    ReadonlyContentModelBlockGroup,
    TypeOfBlockGroup,
} from 'roosterjs-content-model-types';
 
/**
 * Get index of closest ancestor block group of the expected block group type. If not found, return -1
 * @param path The block group path, from the closest one to root
 * @param blockGroupTypes The expected block group types
 * @param stopTypes @optional Block group types that will cause stop searching
 * @param isValidTarget @optional An additional callback to validate whether a matching block group is a valid target
 */
export function getClosestAncestorBlockGroupIndex<T extends ContentModelBlockGroup>(
    path: ReadonlyContentModelBlockGroup[],
    blockGroupTypes: TypeOfBlockGroup<T>[],
    stopTypes: ContentModelBlockGroupType[] = [],
    isValidTarget?: (block: ReadonlyContentModelBlockGroup) => boolean
): number {
    for (let i = 0; i < path.length; i++) {
        const group = path[i];
 
        if (
            (blockGroupTypes as string[]).indexOf(group.blockGroupType) >= 0 &&
            (!isValidTarget || isValidTarget(group))
        ) {
            return i;
        } else if (stopTypes.indexOf(group.blockGroupType) >= 0) {
            // Do not go across boundary specified by stopTypes.
            // For example, in most case we will set table as the boundary,
            // in order to allow modify list item under a table when the table itself is in another list item
            // Although this is not very likely to happen in most case, but we still need to handle it
            return -1;
        }
    }
 
    return -1;
}