All files / roosterjs-content-model-plugins/lib/hyperlink HyperlinkPlugin.ts

94.12% Statements 64/68
84.38% Branches 81/96
84.62% Functions 11/13
95.31% Lines 61/64

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 1671x                   1x               1x 9x 9x 9x 9x   9x 9x                 9x 16x 9x 9x           1x               1x 9x 9x 9x 9x                 1x 8x         8x 8x 8x             15x     15x 3x   3x   3x 3x 3x   3x 3x         2x       12x 4x   4x   4x               1x   8x 6x 6x         3x   3x 3x   3x 3x       2x 1x       9x 3x   2x         2x       1x 12x       12x   12x 11x       1x 5x   1x  
import { matchLink } from 'roosterjs-content-model-api';
import type { HyperlinkToolTip } from './HyperlinkToolTip';
import type {
    DOMHelper,
    EditorPlugin,
    IEditor,
    PluginEvent,
    LinkData,
} from 'roosterjs-content-model-types';
 
const defaultToolTipCallback: HyperlinkToolTip = (url: string) => url;
 
/**
 * Hyperlink plugin does the following jobs for a hyperlink in editor:
 * 1. When hover on a link, show a tool tip
 * 2. When Ctrl+Click on a link, open a new window with the link
 * 3. When type directly on a link whose text matches its link url, update the link url with the link text
 */
export class HyperlinkPlugin implements EditorPlugin {
    private editor: IEditor | null = null;
    private domHelper: DOMHelper | null = null;
    private isMac: boolean = false;
    private disposer: (() => void) | null = null;
 
    private currentNode: Node | null = null;
    private currentLink: HTMLAnchorElement | null = null;
 
    /**
     * Create a new instance of HyperLink class
     * @param tooltip Tooltip to show when mouse hover over a link
     * Default value is to return the href itself. If null, there will be no tooltip text.
     * @param target (Optional) Target window name for hyperlink. If null, will use "_blank"
     * @param onLinkClick (Optional) Open link callback (return false to use default behavior)
     */
    constructor(
        private tooltip: HyperlinkToolTip = defaultToolTipCallback,
        private target?: string,
        private onLinkClick?: (anchor: HTMLAnchorElement, mouseEvent: MouseEvent) => boolean | void
    ) {}
 
    /**
     * Get a friendly name of this plugin
     */
    getName() {
        return 'Hyperlink';
    }
 
    /**
     * Initialize this plugin
     * @param editor The editor instance
     */
    public initialize(editor: IEditor): void {
        this.editor = editor;
        this.domHelper = editor.getDOMHelper();
        this.isMac = !!editor.getEnvironment().isMac;
        this.disposer = editor.attachDomEvent({
            mouseover: { beforeDispatch: this.onMouse },
            mouseout: { beforeDispatch: this.onMouse },
        });
    }
 
    /**
     * Dispose this plugin
     */
    public dispose(): void {
        Iif (this.disposer) {
            this.disposer();
            this.disposer = null;
        }
 
        this.currentNode = null;
        this.currentLink = null;
        this.editor = null;
    }
 
    /**
     * Handle events triggered from editor
     * @param event PluginEvent object
     */
    public onPluginEvent(event: PluginEvent): void {
        let matchedLink: LinkData | null;
 
        if (event.eventType == 'keyDown') {
            const selection = this.editor?.getDOMSelection();
            const node =
                selection?.type == 'range' ? selection.range.commonAncestorContainer : null;
 
            Eif (node && node != this.currentNode) {
                this.currentNode = node;
                this.currentLink = null;
 
                this.runWithHyperlink(node, (href, a) => {
                    if (
                        node.textContent &&
                        (matchedLink = matchLink(node.textContent)) &&
                        matchedLink.normalizedUrl == href
                    ) {
                        this.currentLink = a;
                    }
                });
            }
        } else if (event.eventType == 'keyUp') {
            const selection = this.editor?.getDOMSelection();
            const node =
                selection?.type == 'range' ? selection.range.commonAncestorContainer : null;
 
            if (
                node &&
                node == this.currentNode &&
                this.currentLink &&
                this.currentLink.contains(node) &&
                node.textContent &&
                (matchedLink = matchLink(node.textContent))
            ) {
                this.currentLink.setAttribute('href', matchedLink.normalizedUrl);
            }
        } else if (event.eventType == 'mouseUp' && event.isClicking) {
            this.runWithHyperlink(event.rawEvent.target as Node, (href, anchor) => {
                if (
                    !this.onLinkClick?.(anchor, event.rawEvent) &&
                    this.isCtrlOrMetaPressed(event.rawEvent) &&
                    event.rawEvent.button === 0
                ) {
                    event.rawEvent.preventDefault();
 
                    const target = this.target || '_blank';
                    const window = this.editor?.getDocument().defaultView;
 
                    try {
                        window?.open(href, target);
                    } catch {}
                }
            });
        } else if (event.eventType == 'contentChanged') {
            this.domHelper?.setDomAttribute('title', null /*value*/);
        }
    }
 
    protected onMouse = (e: Event) => {
        this.runWithHyperlink(e.target as Node, (href, a) => {
            const tooltip =
                e.type == 'mouseover'
                    ? typeof this.tooltip == 'function'
                        ? this.tooltip(href, a)
                        : this.tooltip
                    : null;
            this.domHelper?.setDomAttribute('title', tooltip);
        });
    };
 
    private runWithHyperlink(node: Node, callback: (href: string, a: HTMLAnchorElement) => void) {
        const a = this.domHelper?.findClosestElementAncestor(
            node,
            'a[href]'
        ) as HTMLAnchorElement | null;
        const href = a?.getAttribute('href');
 
        if (href && a) {
            callback(href, a);
        }
    }
 
    private isCtrlOrMetaPressed(event: KeyboardEvent | MouseEvent): boolean {
        return this.isMac ? event.metaKey : event.ctrlKey;
    }
}