function cacheGetLinkData()

in packages/roosterjs-editor-plugins/lib/plugins/ContentEdit/features/autoLinkFeatures.ts [52:96]


function cacheGetLinkData(event: PluginEvent, editor: IEditor): LinkData {
    return event.eventType == PluginEventType.KeyDown ||
        (event.eventType == PluginEventType.ContentChanged && event.source == ChangeSource.Paste)
        ? cacheGetEventData(event, 'LINK_DATA', () => {
              // First try to match link from the whole paste string from the plain text in clipboard.
              // This helps when we paste a link next to some existing character, and the text we got
              // from clipboard will only contain what we pasted, any existing characters will not
              // be included.
              let clipboardData =
                  event.eventType == PluginEventType.ContentChanged &&
                  event.source == ChangeSource.Paste &&
                  (event.data as ClipboardData);
              let link = matchLink((clipboardData.text || '').trim());
              let searcher = editor.getContentSearcherOfCursor(event);

              // In case the matched link is already inside a <A> tag, we do a range search.
              // getRangeFromText will return null if the given text is already in a LinkInlineElement
              if (link && searcher.getRangeFromText(link.originalUrl, false /*exactMatch*/)) {
                  return link;
              }

              let word = searcher && searcher.getWordBefore();
              if (word && word.length > MINIMUM_LENGTH) {
                  // Check for trailing punctuation
                  let trailingPunctuations = word.match(TRAILING_PUNCTUATION_REGEX);
                  let trailingPunctuation = (trailingPunctuations || [])[0] || '';
                  let candidate = word.substring(0, word.length - trailingPunctuation.length);

                  // Do special handling for ')', '}', ']'
                  ['()', '{}', '[]'].forEach(str => {
                      if (
                          candidate[candidate.length - 1] == str[1] &&
                          candidate.indexOf(str[0]) < 0
                      ) {
                          candidate = candidate.substr(0, candidate.length - 1);
                      }
                  });

                  // Match and replace in editor
                  return matchLink(candidate);
              }
              return null;
          })
        : null;
}