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

98.25% Statements 112/114
94.29% Branches 66/70
90.48% Functions 19/21
97.96% Lines 96/98

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 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 3201x 1x 1x 1x 1x 1x 1x 1x 1x                                                                           1x                               1x 41x                             42x         1x                   1x 41x               1x                   1x 41x 41x   21x 21x   17x 17x   3x 3x         41x         4x                         5x 5x           5x 3x   2x             1x           1x           1x       21x 21x 21x 21x           20x   17x         17x     17x   57x 57x 12x           12x 10x 3x   10x           17x 10x 10x     17x         17x         17x 17x 17x 14x   2x 1x   2x   4x 4x       4x 4x 4x 4x 4x 4x 3x               3x   4x 2x   4x               4x   6x 6x         1x 6x 5x       1x 3x 3x 1x             1x   1x 10x     1x 10x             1x 3x 3x 3x 3x    
import { ChangeSource } from 'roosterjs-content-model-dom';
import { checkAndInsertHorizontalLine } from './horizontalLine/checkAndInsertHorizontalLine';
import { createLink } from './link/createLink';
import { formatTextSegmentBeforeSelectionMarker, promoteLink } from 'roosterjs-content-model-api';
import { keyboardListTrigger } from './list/keyboardListTrigger';
import { transformFraction } from './numbers/transformFraction';
import { transformHyphen } from './hyphen/transformHyphen';
import { transformOrdinals } from './numbers/transformOrdinals';
import { unlink } from './link/unlink';
import type { AutoFormatOptions } from './interface/AutoFormatOptions';
import type {
    ContentChangedEvent,
    ContentModelText,
    EditorInputEvent,
    EditorPlugin,
    FormatContentModelContext,
    FormatContentModelOptions,
    IEditor,
    KeyDownEvent,
    PluginEvent,
    ReadonlyContentModelDocument,
    ShallowMutableContentModelParagraph,
} from 'roosterjs-content-model-types';
 
/**
 * @internal
 */
type AutoFormatFeature = 'list' | 'link' | 'hyphen' | 'fraction' | 'ordinal';
 
/**
 * @internal
 */
interface Feature {
    autoFormat: AutoFormatFeature;
    enabled: boolean;
    transformFunction: (
        model: ReadonlyContentModelDocument,
        previousSegment: ContentModelText,
        paragraph: ShallowMutableContentModelParagraph,
        context: FormatContentModelContext
    ) => boolean | HTMLElement;
}
 
/**
 * @internal
 */
const DefaultOptions: Partial<AutoFormatOptions> = {
    autoBullet: false,
    autoNumbering: false,
    autoUnlink: false,
    autoLink: false,
    autoHyphen: false,
    autoFraction: false,
    autoOrdinals: false,
    removeListMargins: false,
    autoHorizontalLine: false,
};
 
/**
 * Auto Format plugin handles auto formatting, such as transforming * characters into a bullet list.
 * It can be customized with options to enable or disable auto list features.
 */
export class AutoFormatPlugin implements EditorPlugin {
    private editor: IEditor | null = null;
    /**
     * @param options An optional parameter that takes in an object of type AutoFormatOptions, which includes the following properties:
     *  - autoBullet: A boolean that enables or disables automatic bullet list formatting. Defaults to false.
     *  - autoNumbering: A boolean that enables or disables automatic numbering formatting. Defaults to false.
     *  - removeListMargins: A boolean to remove list margins when it is automatically triggered. Defaults to false.
     *  - autoHyphen: A boolean that enables or disables automatic hyphen transformation. Defaults to false.
     *  - autoFraction: A boolean that enables or disables automatic fraction transformation. Defaults to false.
     *  - autoOrdinals: A boolean that enables or disables automatic ordinal number transformation. Defaults to false.
     *  - autoLink: A boolean that enables or disables automatic hyperlink url address creation when pasting or typing content. Defaults to false.
     *  - autoUnlink: A boolean that enables or disables automatic hyperlink removal when pressing backspace. Defaults to false.
     *  - autoTel: A boolean that enables or disables automatic hyperlink telephone numbers transformation. Defaults to false.
     *  - autoMailto: A boolean that enables or disables automatic hyperlink email address transformation. Defaults to false.
     *  - autoHorizontalLine: A boolean that enables or disables automatic horizontal line creation. Defaults to false.
     */
    constructor(private options: AutoFormatOptions = DefaultOptions) {}
 
    /**
     * Get name of this plugin
     */
    getName() {
        return 'AutoFormat';
    }
 
    /**
     * The first method that editor will call to a plugin when editor is initializing.
     * It will pass in the editor instance, plugin should take this chance to save the
     * editor reference so that it can call to any editor method or format API later.
     * @param editor The editor object
     */
    initialize(editor: IEditor) {
        this.editor = editor;
    }
 
    /**
     * The last method that editor will call to a plugin before it is disposed.
     * Plugin can take this chance to clear the reference to editor. After this method is
     * called, plugin should not call to any editor method since it will result in error.
     */
    dispose() {
        this.editor = null;
    }
 
    /**
     * Core method for a plugin. Once an event happens in editor, editor will call this
     * method of each plugin to handle the event as long as the event is not handled
     * exclusively by another plugin.
     * @param event The event to handle:
     */
    onPluginEvent(event: PluginEvent) {
        Eif (this.editor) {
            switch (event.eventType) {
                case 'input':
                    this.handleEditorInputEvent(this.editor, event);
                    break;
                case 'keyDown':
                    this.handleKeyDownEvent(this.editor, event);
                    break;
                case 'contentChanged':
                    this.handleContentChangedEvent(this.editor, event);
                    break;
            }
        }
    }
 
    private features: Feature[] = [
        {
            autoFormat: 'list',
            enabled: !!(this.options.autoBullet || this.options.autoNumbering),
            transformFunction: (model, _previousSegment, paragraph, context) =>
                keyboardListTrigger(
                    model,
                    paragraph,
                    context,
                    this.options.autoBullet,
                    this.options.autoNumbering,
                    this.options.removeListMargins
                ),
        },
        {
            autoFormat: 'link',
            enabled: !!(this.options.autoLink || this.options.autoTel || this.options.autoMailto),
            transformFunction: (_model, previousSegment, paragraph, context) => {
                const { autoLink, autoTel, autoMailto } = this.options;
                const linkSegment = promoteLink(previousSegment, paragraph, {
                    autoLink,
                    autoTel,
                    autoMailto,
                });
 
                if (linkSegment) {
                    return createAnchor(linkSegment.link?.format.href || '', linkSegment.text);
                }
                return false;
            },
        },
        {
            autoFormat: 'hyphen',
            enabled: !!this.options.autoHyphen,
            transformFunction: (_model, previousSegment, paragraph, context) =>
                transformHyphen(previousSegment, paragraph, context),
        },
        {
            autoFormat: 'fraction',
            enabled: !!this.options.autoFraction,
            transformFunction: (_model, previousSegment, paragraph, context) =>
                transformFraction(previousSegment, paragraph, context),
        },
        {
            autoFormat: 'ordinal',
            enabled: !!this.options.autoOrdinals,
            transformFunction: (_model, previousSegment, paragraph, context) =>
                transformOrdinals(previousSegment, paragraph, context),
        },
    ];
 
    private handleEditorInputEvent(editor: IEditor, event: EditorInputEvent) {
        const rawEvent = event.rawEvent;
        const selection = editor.getDOMSelection();
        if (
            rawEvent.inputType === 'insertText' &&
            selection &&
            selection.type === 'range' &&
            selection.range.collapsed
        ) {
            switch (rawEvent.data) {
                case ' ':
                    const formatOptions: FormatContentModelOptions = {
                        changeSource: '',
                        apiName: '',
                        getChangeData: undefined,
                    };
                    formatTextSegmentBeforeSelectionMarker(
                        editor,
                        (model, previousSegment, paragraph, _markerFormat, context) => {
                            let formatApplied: AutoFormatFeature | undefined = undefined;
 
                            for (const feature of this.features) {
                                if (feature.enabled) {
                                    const result = feature.transformFunction(
                                        model,
                                        previousSegment,
                                        paragraph,
                                        context
                                    );
                                    if (result) {
                                        if (typeof result !== 'boolean') {
                                            formatOptions.getChangeData = () => result;
                                        }
                                        formatApplied = feature.autoFormat;
                                        break;
                                    }
                                }
                            }
 
                            if (formatApplied) {
                                formatOptions.changeSource = getChangeSource(formatApplied);
                                formatOptions.apiName = getApiName(formatApplied);
                            }
 
                            return !!formatApplied;
                        },
                        formatOptions
                    );
 
                    break;
            }
        }
    }
 
    private handleKeyDownEvent(editor: IEditor, event: KeyDownEvent) {
        const rawEvent = event.rawEvent;
        if (!rawEvent.defaultPrevented && !event.handledByEditFeature) {
            switch (rawEvent.key) {
                case 'Backspace':
                    if (this.options.autoUnlink) {
                        unlink(editor, rawEvent);
                    }
                    break;
                case 'Tab':
                    Eif (!rawEvent.shiftKey) {
                        formatTextSegmentBeforeSelectionMarker(
                            editor,
                            (model, _previousSegment, paragraph, _markerFormat, context) => {
                                const {
                                    autoBullet,
                                    autoNumbering,
                                    removeListMargins,
                                } = this.options;
                                let shouldList = false;
                                if (autoBullet || autoNumbering) {
                                    shouldList = keyboardListTrigger(
                                        model,
                                        paragraph,
                                        context,
                                        autoBullet,
                                        autoNumbering,
                                        removeListMargins
                                    );
                                    context.canUndoByBackspace = shouldList;
                                }
                                if (shouldList) {
                                    event.rawEvent.preventDefault();
                                }
                                return shouldList;
                            },
                            {
                                changeSource: ChangeSource.AutoFormat,
                                apiName: 'autoToggleList',
                            }
                        );
                    }
                    break;
                case 'Enter':
                    this.handleEnterKey(editor, event);
                    break;
            }
        }
    }
 
    private handleEnterKey(editor: IEditor, event: KeyDownEvent) {
        if (this.options.autoHorizontalLine) {
            checkAndInsertHorizontalLine(editor, event);
        }
    }
 
    private handleContentChangedEvent(editor: IEditor, event: ContentChangedEvent) {
        const { autoLink, autoTel, autoMailto } = this.options;
        if (event.source == 'Paste' && (autoLink || autoTel || autoMailto)) {
            createLink(editor, {
                autoLink,
                autoTel,
                autoMailto,
            });
        }
    }
}
 
const getApiName = (autoFormat: AutoFormatFeature) => {
    return autoFormat == 'list' ? 'autoToggleList' : autoFormat == 'hyphen' ? 'autoHyphen' : '';
};
 
const getChangeSource = (autoFormat: AutoFormatFeature) => {
    return autoFormat == 'list' || autoFormat == 'hyphen'
        ? ChangeSource.AutoFormat
        : autoFormat == 'link'
        ? ChangeSource.AutoLink
        : '';
};
 
const createAnchor = (url: string, text: string) => {
    const anchor = document.createElement('a');
    anchor.href = url;
    anchor.textContent = text;
    return anchor;
};