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

100% Statements 22/22
95.45% Branches 21/22
100% Functions 5/5
100% Lines 21/21

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 491x 1x 1x             1x 8x 8x   8x   8x   14x 12x   8x         8x   8x 1x   1x 1x 1x       13x 8x   8x             8x    
import { adjustSegmentSelection } from '../../modelApi/selection/adjustSegmentSelection';
import { adjustWordSelection } from '../../modelApi/selection/adjustWordSelection';
import { getSelectedSegments, setSelection } from 'roosterjs-content-model-dom';
import type { IEditor } from 'roosterjs-content-model-types';
 
/**
 * Adjust selection to make sure select a hyperlink if any, or a word if original selection is collapsed
 * @return A combination of existing link display text and url if any. If there is no existing link, return selected text and null
 */
export function adjustLinkSelection(editor: IEditor): [string, string | null] {
    let text = '';
    let url: string | null = null;
 
    editor.formatContentModel(
        model => {
            let changed = adjustSegmentSelection(
                model,
                target => !!target.isSelected && !!target.link,
                (target, ref) => !!target.link && target.link.format.href == ref.link!.format.href
            );
            let segments = getSelectedSegments(
                model,
                false /*includingFormatHolder*/,
                true /*mutate*/
            );
            const firstSegment = segments[0];
 
            if (segments.length == 1 && firstSegment.segmentType == 'SelectionMarker') {
                segments = adjustWordSelection(model, firstSegment);
 
                Eif (segments.length > 1) {
                    changed = true;
                    setSelection(model, segments[0], segments[segments.length - 1]);
                }
            }
 
            text = segments.map(x => (x.segmentType == 'Text' ? x.text : '')).join('');
            url = segments[0]?.link?.format.href || null;
 
            return changed;
        },
        {
            apiName: 'adjustLinkSelection',
        }
    );
 
    return [text, url];
}