go.chromium.org/luci@v0.0.0-20240309015107-7cdc2e660f33/milo/ui/src/common/components/linkified_text/linkified_text.tsx (about)

     1  // Copyright 2024 The LUCI Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //      http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  import { Fragment } from 'react';
    16  
    17  // The patterns that will be linkified.
    18  //
    19  // WARNING: Be strict with what is accepted here.  If you are too liberal you
    20  // will enable XSS attacks.
    21  const patterns = [
    22    'go/[a-zA-Z0-9-_]+',
    23    'b/[0-9]+',
    24    'crrev.com/[ci]/[0-9]+',
    25    'https?://[a-z0-9.-]+/?[a-zA-Z0-9/.-_+]*',
    26  ];
    27  
    28  const combinedPatterns = '(?:' + patterns.join(')|(?:') + ')';
    29  
    30  interface LinkifiedTextProps {
    31    text: string | undefined;
    32  }
    33  
    34  /**
    35   * Linkified Text displays text with substrings that look links turned into
    36   * actual HTML links.
    37   *
    38   * There are no guarantees provided that all types of links will be handled,
    39   * we just try to handle the most common ones for our UIs.  In particular
    40   * the patterns are fairly strict to avoid XSS vulnerabilities.
    41   */
    42  export const LinkifiedText = ({ text }: LinkifiedTextProps) => {
    43    if (!text) {
    44      return null;
    45    }
    46    const fragments = fragmentsFromText(text);
    47    return (
    48      <Fragment>
    49        {fragments.map((f, i) => (
    50          <Fragment key={i}>
    51            {f.text ? <span>{f.text}</span> : null}
    52            {f.link ? (
    53              <a href={f.link} target="_blank" rel="noreferrer">
    54                {f.linkText}
    55              </a>
    56            ) : null}
    57          </Fragment>
    58        ))}
    59      </Fragment>
    60    );
    61  };
    62  
    63  interface TextFragment {
    64    text: string;
    65    linkText?: string;
    66    link?: string;
    67  }
    68  
    69  const fragmentsFromText = (text: string): TextFragment[] => {
    70    const re = new RegExp(combinedPatterns, 'g');
    71    let lastIndex = 0;
    72    let result: RegExpExecArray | null = null;
    73    const fragments: TextFragment[] = [];
    74  
    75    while ((result = re.exec(text))) {
    76      fragments.push({
    77        text: text.substring(lastIndex, result.index),
    78        linkText: result[0],
    79        link: result[0].match(/https?:\/\//) ? result[0] : 'http://' + result[0],
    80      });
    81      lastIndex = result.index + result[0].length;
    82    }
    83    fragments.push({
    84      text: text.substring(lastIndex, text.length),
    85    });
    86    return fragments;
    87  };