All files / roosterjs-content-model-markdown/lib/markdownToModel/appliers applyTextFormatting.ts

100% Statements 65/65
100% Branches 39/39
100% Functions 8/8
100% Lines 65/65

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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 1931x                                         1x 258x     258x 9x     249x 249x   249x 249x   249x 2820x   2820x   272x   193x 135x               135x       193x     193x     79x 79x       2548x 2548x         249x 212x           249x       196x     53x         258x 258x 258x 258x     258x       2820x   2820x 36x     2784x 122x     2662x 114x     2548x                 272x   272x   272x   96x       176x         153x       193x   93x 93x   72x 72x   28x 28x               272x   122x   114x   36x                   347x   347x 57x     347x 41x     347x 18x     347x    
import { createText } from 'roosterjs-content-model-dom';
import type {
    ContentModelLink,
    ContentModelSegmentFormat,
    ContentModelText,
} from 'roosterjs-content-model-types';
 
interface FormattingState {
    bold: boolean;
    italic: boolean;
    strikethrough: boolean;
}
 
interface FormatMarker {
    type: 'bold' | 'italic' | 'strikethrough';
    length: number;
}
 
/**
 * @internal
 */
export function applyTextFormatting(textSegment: ContentModelText) {
    const text = textSegment.text;
 
    // Quick check: if the text contains only formatting markers, return original
    if (isOnlyFormattingMarkers(text)) {
        return [textSegment];
    }
 
    const textSegments: ContentModelText[] = [];
    const currentState: FormattingState = { bold: false, italic: false, strikethrough: false };
 
    let currentText = '';
    let i = 0;
 
    while (i < text.length) {
        const marker = parseMarkerAt(text, i);
 
        if (marker) {
            // Check if this marker should be treated as formatting or as literal text
            if (shouldToggleFormatting(text, i, marker, currentState)) {
                // If we have accumulated text, create a segment for it
                if (currentText.length > 0) {
                    textSegments.push(
                        createFormattedSegment(
                            currentText,
                            textSegment.format,
                            currentState,
                            textSegment.link
                        )
                    );
                    currentText = '';
                }
 
                // Toggle the formatting state
                toggleFormatting(currentState, marker.type);
 
                // Skip the marker characters
                i += marker.length;
            } else {
                // Treat as regular text if marker is not valid in this context
                currentText += text[i];
                i++;
            }
        } else {
            // Regular character, add to current text
            currentText += text[i];
            i++;
        }
    }
 
    // Add any remaining text as a final segment
    if (currentText.length > 0) {
        textSegments.push(
            createFormattedSegment(currentText, textSegment.format, currentState, textSegment.link)
        );
    }
 
    // If no meaningful formatting was applied, return the original segment
    if (
        textSegments.length === 0 ||
        (textSegments.length === 1 && textSegments[0].text === textSegment.text)
    ) {
        return [textSegment];
    }
 
    return textSegments;
}
 
function isOnlyFormattingMarkers(text: string): boolean {
    // Remove all potential formatting markers and see if anything remains
    let remaining = text;
    remaining = remaining.replace(/\*\*/g, ''); // Remove **
    remaining = remaining.replace(/~~/g, ''); // Remove ~~
    remaining = remaining.replace(/\*/g, ''); // Remove *
 
    // If nothing remains after removing all markers, it was only markers
    return remaining.length === 0;
}
 
function parseMarkerAt(text: string, index: number): FormatMarker | null {
    const remaining = text.substring(index);
 
    if (remaining.startsWith('~~')) {
        return { type: 'strikethrough', length: 2 };
    }
 
    if (remaining.startsWith('**')) {
        return { type: 'bold', length: 2 };
    }
 
    if (remaining.startsWith('*')) {
        return { type: 'italic', length: 1 };
    }
 
    return null;
}
 
function shouldToggleFormatting(
    text: string,
    index: number,
    marker: FormatMarker,
    currentState: FormattingState
): boolean {
    const nextChar = index + marker.length < text.length ? text.charAt(index + marker.length) : '';
 
    const isCurrentlyActive = getCurrentFormatState(currentState, marker.type);
 
    if (isCurrentlyActive) {
        // We're currently in this format, so any marker can close it
        return true;
    } else {
        // We're not in this format, so this marker would open it
        // Opening markers must be followed by non-whitespace
        return nextChar.length > 0 && !isWhitespace(nextChar);
    }
}
 
function isWhitespace(char: string): boolean {
    return /\s/.test(char);
}
 
function toggleFormatting(state: FormattingState, type: 'bold' | 'italic' | 'strikethrough'): void {
    switch (type) {
        case 'bold':
            state.bold = !state.bold;
            break;
        case 'italic':
            state.italic = !state.italic;
            break;
        case 'strikethrough':
            state.strikethrough = !state.strikethrough;
            break;
    }
}
 
function getCurrentFormatState(
    state: FormattingState,
    type: 'bold' | 'italic' | 'strikethrough'
): boolean {
    switch (type) {
        case 'bold':
            return state.bold;
        case 'italic':
            return state.italic;
        case 'strikethrough':
            return state.strikethrough;
    }
}
 
function createFormattedSegment(
    text: string,
    baseFormat: ContentModelSegmentFormat,
    state: FormattingState,
    link?: ContentModelLink
): ContentModelText {
    const format: ContentModelSegmentFormat = { ...baseFormat };
 
    if (state.bold) {
        format.fontWeight = 'bold';
    }
 
    if (state.italic) {
        format.italic = true;
    }
 
    if (state.strikethrough) {
        format.strikethrough = true;
    }
 
    return createText(text, format, link);
}