function cacheGetNeighborEntityElement()

in packages/roosterjs-editor-plugins/lib/plugins/ContentEdit/features/entityFeatures.ts [136:192]


function cacheGetNeighborEntityElement(
    event: PluginKeyboardEvent,
    editor: IEditor,
    isNext: boolean,
    collapseOnly: boolean,
    operation?: EntityOperation
): HTMLElement {
    const element = cacheGetEventData(
        event,
        'NEIGHBOR_ENTITY_ELEMENT_' + isNext + '_' + collapseOnly,
        () => {
            const range = editor.getSelectionRange();

            if (collapseOnly && !range.collapsed) {
                return null;
            }

            range.commonAncestorContainer.normalize();
            const pos = Position.getEnd(range).normalize();
            const isAtBeginOrEnd = pos.offset == 0 || pos.isAtEnd;
            let entityNode: HTMLElement = null;

            if (isAtBeginOrEnd) {
                const traverser = editor.getBodyTraverser(pos.node);
                const sibling = isNext
                    ? pos.offset == 0
                        ? traverser.currentInlineElement
                        : traverser.getNextInlineElement()
                    : pos.isAtEnd
                    ? traverser.currentInlineElement
                    : traverser.getPreviousInlineElement();
                let node = sibling && sibling.getContainerNode();

                if (!collapseOnly) {
                    const block = editor.getBlockElementAtNode(pos.node);
                    if (!block || !block.contains(node)) {
                        node = null;
                    }
                }

                entityNode = node && editor.getElementAtCursor(getEntitySelector(), node);
            }

            return entityNode;
        }
    );

    if (element && operation !== undefined) {
        editor.triggerPluginEvent(PluginEventType.EntityOperation, {
            operation,
            rawEvent: event.rawEvent,
            entity: getEntityFromElement(element),
        });
    }

    return element;
}