All files / roosterjs-content-model-plugins/lib/paste/PowerPoint processPastedContentFromPowerPoint.ts

98.28% Statements 57/58
88.89% Branches 48/54
100% Functions 6/6
98.21% Lines 55/56

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 193 194 195 196 1971x 1x 1x 1x 1x                       1x 1x 1x 1x   1x 270x 270x 270x               1x       42x   14x     1x   1x     14x   14x 187x   187x 45x   142x 142x   90x 90x 90x 90x 90x 90x 90x     90x                     90x                       90x 90x 46x       90x 90x     52x                                                         90x 90x 90x 90x 90x   90x   90x 90x   90x                           1x                   1x                           52x       52x           44x     8x            
import { addParser } from '../utils/addParser';
import { processAsListItem, setupListFormat } from '../utils/customListUtils';
import { removeNegativeTextIndentParser } from '../parsers/removeNegativeTextIndentParser';
import { setProcessor } from '../utils/setProcessor';
import {
    BulletListType,
    getOrderedListNumberStr,
    moveChildNodes,
    NumberingListType,
} from 'roosterjs-content-model-dom';
import type {
    BeforePasteEvent,
    ContentModelListItemLevelFormat,
    DOMCreator,
} from 'roosterjs-content-model-types';
 
const BulletSelector = '* > span > span[style*=mso-special-format]';
const MsOfficeSpecialFormat = 'mso-special-format';
const CssStyleKey = 'style';
const MsoSpecialFormatRegex = /mso-special-format:\s*([^;]*)/;
 
const clearListItemStyles = (format: ContentModelListItemLevelFormat): void => {
    delete format.textAlign;
    delete format.marginLeft;
    delete format.paddingLeft;
};
/**
 * @internal
 * Convert pasted content from PowerPoint
 * @param event The BeforePaste event
 */
 
export function processPastedContentFromPowerPoint(
    event: BeforePasteEvent,
    domCreator: DOMCreator
) {
    const { fragment, clipboardData, domToModelOption } = event;
 
    if (clipboardData.html && !clipboardData.text && clipboardData.image) {
        // It is possible that PowerPoint copied both image and HTML but not plain text.
        // We always prefer HTML if any.
        const doc = domCreator.htmlToDOM(clipboardData.html);
 
        moveChildNodes(fragment, doc?.body);
    }
 
    addParser(domToModelOption, 'block', removeNegativeTextIndentParser);
 
    setProcessor(domToModelOption, 'element', (group, element, context) => {
        const style = element.getAttribute(CssStyleKey) || '';
        // If the element is the bullet element, just ignore it, otherwise we will see an extra bullet in the list
        if (style.includes(MsOfficeSpecialFormat) && context.listFormat.levels.length > 0) {
            return;
        }
        const bulletElement = element.querySelector(BulletSelector) as HTMLElement;
        if (bulletElement) {
            const {
                depth,
                unorderedBulletType,
                orderedBulletType,
                startNumberOverrideOrBullet,
                isOrderedList,
                isNewList,
            } = extractPowerPointListInfo(element, bulletElement);
 
            // Setup the listformat with the metadata extracted from the bullet element
            setupListFormat(
                isOrderedList ? 'OL' : 'UL',
                element,
                context,
                depth,
                context.listFormat,
                group,
                [clearListItemStyles]
            );
 
            // Set the metadata for the list item, which will be used to set the correct bullet style type
            const listMetadata = {
                unorderedStyleType:
                    !isOrderedList && unorderedBulletType
                        ? BulletListType[unorderedBulletType]
                        : undefined,
                orderedStyleType:
                    isOrderedList && orderedBulletType
                        ? NumberingListType[orderedBulletType]
                        : undefined,
            };
 
            // Process the Div element as a list item.
            processAsListItem(context, element, group, listMetadata, bulletElement, listItem => {
                if (isNewList) {
                    listItem.levels[
                        listItem.levels.length - 1
                    ].format.startNumberOverride = parseInt(startNumberOverrideOrBullet);
                }
                clearListItemStyles(listItem.levels[listItem.levels.length - 1].format);
                clearListItemStyles(listItem.format);
            });
        } else {
            context.defaultElementProcessors.element?.(group, element, context);
        }
    });
}
 
/**
 * Extract list information from PowerPoint pasted content
 *
 * The lists from PowerPoint are represent as:
 *
 * - The class 0# represents the depth of the list, if the list is in the first level, the class attribute wont be present.
 * - The mso-special-format style represents the type of bullet and the start of the list.
 *      The first part of the mso-special-format is the type of bullet, and the second part is the start of the list.
 *  - All the items that are in the same list have the same mso-special-format style. Which we are leveraging to identify when a list is new or part of the existing list thread.
 *
 * @example
 *  `   <div class="O1" style="...">
            <span style="font-size: 5pt"
                ><span style="mso-special-format: 'numbullet6\,1'; font-family: +mj-lt"
                    >i.</span
                ></span
            ><span style="...;">123</span>
        </div> `
 *
 * @param element The element to extract list information from
 * @param bulletElement The bullet element to extract list information from
 * @returns The extracted list information
 */
function extractPowerPointListInfo(element: HTMLElement, bulletElement: HTMLElement) {
    const className = element.className.substring(1) || '0';
    const depth = parseInt(className) + 1;
    const style = bulletElement.getAttribute(CssStyleKey) || '';
    const msoSpecialFormat = style.match(MsoSpecialFormatRegex);
    const [bulletTypeHtml, startNumberOverrideOrBullet] =
        msoSpecialFormat?.[1].replace('"', '').split('\\,') || [];
    const isOrderedList = OrderedListStyleMap.has(bulletTypeHtml);
 
    const unorderedBulletType = UnorderedBullets.get(bulletElement.innerText);
    const orderedBulletType = OrderedListStyleMap.get(bulletTypeHtml);
 
    return {
        depth,
        unorderedBulletType,
        orderedBulletType,
        startNumberOverrideOrBullet,
        isOrderedList,
        isNewList:
            isOrderedList &&
            !!orderedBulletType &&
            bulletElement.innerText ===
                getPptListStart(orderedBulletType, startNumberOverrideOrBullet),
    };
}
 
const UnorderedBullets: Map<string, keyof typeof BulletListType> = new Map([
    ['•', 'Disc'],
    ['o', 'Circle'],
    ['§', 'Square'],
    ['q', 'BoxShadow'],
    ['v', 'Xrhombus'],
    ['Ø', 'ShortArrow'],
    ['ü', 'CheckMark'],
]);
 
const OrderedListStyleMap: Map<string, keyof typeof NumberingListType> = new Map([
    ['numbullet1', 'UpperAlpha'],
    ['numbullet2', 'DecimalParenthesis'],
    ['numbullet3', 'Decimal'],
    ['numbullet7', 'UpperRoman'],
    ['numbullet9', 'LowerAlphaParenthesis'],
    ['numbullet0', 'LowerAlpha'],
    ['numbullet6', 'LowerRoman'],
]);
 
function getPptListStart(
    orderedBulletType: keyof typeof NumberingListType,
    startNumberOverride: string
) {
    const bullet = getOrderedListNumberStr(
        NumberingListType[orderedBulletType],
        parseInt(startNumberOverride)
    );
    switch (orderedBulletType) {
        case 'Decimal':
        case 'UpperAlpha':
        case 'LowerAlpha':
        case 'UpperRoman':
        case 'LowerRoman':
            return bullet + '.';
        case 'DecimalParenthesis':
        case 'LowerAlphaParenthesis':
            return bullet + ')';
 
        default:
            return undefined;
    }
}