All files / roosterjs-content-model-api/lib/modelApi/link promoteLink.ts

100% Statements 11/11
88.89% Branches 8/9
100% Functions 1/1
100% Lines 11/11

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         49x 49x 49x   49x 19x           19x               19x     30x    
import { getLinkUrl } from './getLinkUrl';
import { splitTextSegment } from '../../publicApi/segment/splitTextSegment';
import type {
    AutoLinkOptions,
    ContentModelText,
    ShallowMutableContentModelParagraph,
} from 'roosterjs-content-model-types';
 
/**
 * Promote the given text segment to a hyper link when the segment text is ending with a valid link format.
 * When the whole text segment if of a link, promote the whole segment.
 * When the text segment ends with a link format, split the segment and promote the second part
 * When link is in middle of the text segment, no action.
 * This is mainly used for doing auto link when there is a link before cursor
 * @param segment The text segment to search link text from
 * @param paragraph Parent paragraph of the segment
 * @param options Options of auto link
 * @returns If a link is promoted, return this segment. Otherwise return null
 */
export function promoteLink(
    segment: ContentModelText,
    paragraph: ShallowMutableContentModelParagraph,
    autoLinkOptions: AutoLinkOptions
): ContentModelText | null {
    const link = segment.text.split(' ').pop();
    const url = link?.trim();
    let linkUrl: string | undefined = undefined;
 
    if (url && link && (linkUrl = getLinkUrl(url, autoLinkOptions))) {
        const linkSegment = splitTextSegment(
            segment,
            paragraph,
            segment.text.length - link.trimLeft().length,
            segment.text.trimRight().length
        );
        linkSegment.link = {
            format: {
                href: linkUrl,
                underline: true,
            },
            dataset: {},
        };
 
        return linkSegment;
    }
 
    return null;
}