All files / roosterjs-content-model-api/lib/publicApi/link removeLink.ts

100% Statements 15/15
100% Branches 7/7
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 461x 1x                 1x 6x   6x   6x   7x   7x       6x         6x   6x 12x 8x   8x       6x              
import { adjustSegmentSelection } from '../../modelApi/selection/adjustSegmentSelection';
import { getSelectedSegments } from 'roosterjs-content-model-dom';
import type { IEditor } from 'roosterjs-content-model-types';
 
/**
 * Remove link at selection. If no links at selection, do nothing.
 * If selection contains multiple links, all of the link styles will be removed.
 * If only part of a link is selected, the whole link style will be removed.
 * @param editor The editor instance
 */
export function removeLink(editor: IEditor) {
    editor.focus();
 
    editor.formatContentModel(
        model => {
            adjustSegmentSelection(
                model,
                target => !!target.isSelected && !!target.link,
                (target, ref) =>
                    target.isSelected || // Expand the selection to any link that is involved. So we can remove multiple links together
                    (!!target.link && target.link.format.href == ref.link!.format.href)
            );
 
            const segments = getSelectedSegments(
                model,
                false /*includingFormatHolder*/,
                true /*mutate*/
            );
            let isChanged = false;
 
            segments.forEach(segment => {
                if (segment.link) {
                    isChanged = true;
 
                    delete segment.link;
                }
            });
 
            return isChanged;
        },
        {
            apiName: 'removeLink',
        }
    );
}