All files / roosterjs-content-model-plugins/lib/autoFormat/hyphen transformHyphen.ts

100% Statements 21/21
93.75% Branches 15/16
100% Functions 1/1
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 461x                   1x         16x 16x 16x 2x 2x 2x 2x 2x   14x 14x 14x 9x 9x             9x 9x 5x 5x 5x       9x    
import { splitTextSegment } from 'roosterjs-content-model-api';
import type {
    ContentModelText,
    FormatContentModelContext,
    ShallowMutableContentModelParagraph,
} from 'roosterjs-content-model-types';
 
/**
 * @internal
 */
export function transformHyphen(
    previousSegment: ContentModelText,
    paragraph: ShallowMutableContentModelParagraph,
    context: FormatContentModelContext
): boolean {
    const segments = previousSegment.text.split(' ');
    const dashes = segments[segments.length - 2];
    if (dashes === '--') {
        const textIndex = previousSegment.text.lastIndexOf('--');
        const textSegment = splitTextSegment(previousSegment, paragraph, textIndex, textIndex + 2);
        textSegment.text = textSegment.text.replace('--', '—');
        context.canUndoByBackspace = true;
        return true;
    } else {
        const text = segments.pop();
        const hasDashes = text && text?.indexOf('--') > -1;
        if (hasDashes && text.trim() !== '--') {
            const textIndex = previousSegment.text.indexOf(text);
            const textSegment = splitTextSegment(
                previousSegment,
                paragraph,
                textIndex,
                textIndex + text.length - 1
            );
 
            const textLength = textSegment.text.length;
            if (textSegment.text[0] !== '-' && textSegment.text[textLength - 1] !== '-') {
                textSegment.text = textSegment.text.replace('--', '—');
                context.canUndoByBackspace = true;
                return true;
            }
        }
    }
    return false;
}