All files / lib/util linkDetector.ts

100% Statements 29/29
100% Branches 2/2
100% Functions 7/7
100% Lines 27/27

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          17x   17x 11x 11x     17x   22x   17x 10x 20x 13x       10x 10x   10x 10x   10x 9x 9x 3x   6x       10x 10x 3x     10x 10x 1x     10x           17x    
import Crowi from 'server/crowi'
import { decodeSpace } from './path'
 
export default (crowi: Crowi) => {
  // const debug = Debug('crowi:lib:url')
  const linkDetector: any = {}
 
  linkDetector.getLinkRegexp = () => {
    const appUrl = crowi.getBaseUrl()
    return new RegExp(appUrl + '(/[^\\s"?)#]*)?', 'g')
  }
 
  linkDetector.getObjectIdRegexp = () => new RegExp('/([0-9a-fA-F]{24})')
 
  linkDetector.getPathRegexps = () => [new RegExp('<(/[^>]+)>', 'g'), /\[(\/[^\]]+)\](?!\()/g]
 
  linkDetector.search = function(text) {
    var unique = function(array) {
      return array.filter(function(x, i, self) {
        return self.indexOf(x) === i
      })
    }
 
    const objectIds: any = []
    const paths: any = []
 
    const linkRegexp = linkDetector.getLinkRegexp()
    const objectIdRegexp = linkDetector.getObjectIdRegexp()
 
    while (linkRegexp.exec(text)) {
      const path = decodeSpace(decodeURIComponent(RegExp.$1))
      if (objectIdRegexp.test(path)) {
        objectIds.push(RegExp.$1)
      } else {
        paths.push(path)
      }
    }
 
    const pathRegexp = linkDetector.getPathRegexps()[0]
    while (pathRegexp.exec(text)) {
      paths.push(RegExp.$1)
    }
 
    const pathRegexp2 = linkDetector.getPathRegexps()[1]
    while (pathRegexp2.exec(text)) {
      paths.push(RegExp.$1)
    }
 
    return {
      objectIds: unique(objectIds),
      paths: unique(paths),
    }
  }
 
  return linkDetector
}