All files / owid-grapher/clientUtils search.tsx

35.23% Statements 68/193
100% Branches 10/10
42.86% Functions 3/7
35.23% Lines 68/193

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 2441x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                         1x 1x                       1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                           1x                                                                                                                                                   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 16x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 161x 161x 5x 5x 161x                                                                                                      
import { flatten } from "./Util"
import chunk from "chunk-text"
import { fromString } from "html-to-text"
import { drop, escapeRegExp, sortBy } from "lodash"
import React from "react"
 
export interface SearchWord {
    regex: RegExp
    word: string
}
 
function buildRegexFromSearchWord(str: string): RegExp {
    const escapedString = escapeRegExp(str)
    const moreTolerantMatchReplacements =
        // Match digit or superscript/subscript variant
        [
            { searchTerm: "0", regexTerm: "(0|\u2070|\u2080)" },
            {
                searchTerm: "1",
                regexTerm: "(1|\u00B9|\u2081)", // superscript for 1, 2 and 3 are odd codepoints
            },
            { searchTerm: "2", regexTerm: "(2|\u00B2|\u2082)" },
            { searchTerm: "3", regexTerm: "(3|\u00B3|\u2083)" },
            { searchTerm: "4", regexTerm: "(4|\u2074|\u2084)" },
            { searchTerm: "5", regexTerm: "(5|\u2075|\u2085)" },
            { searchTerm: "6", regexTerm: "(6|\u2076|\u2086)" },
            { searchTerm: "7", regexTerm: "(7|\u2077|\u2087)" },
            { searchTerm: "8", regexTerm: "(8|\u2078|\u2088)" },
            { searchTerm: "9", regexTerm: "(9|\u2079|\u2089)" },
        ]
    let moreTolerantMatch = escapedString
    for (const replacement of moreTolerantMatchReplacements) {
        moreTolerantMatch = moreTolerantMatch.replace(
            replacement.searchTerm,
            replacement.regexTerm
        )
    }
    return new RegExp(moreTolerantMatch, "iu")
}
export const buildSearchWordsFromSearchString = (
    searchInput: string | undefined
): SearchWord[] => {
    if (!searchInput) return []
    const wordRegexes = searchInput
        .split(" ")
        .filter((item) => item)
        .map((item) => ({
            regex: buildRegexFromSearchWord(item),
            word: item,
        }))
    return wordRegexes
}
 
/** Given a list of SearchWords constructed with buildSearchWordsFromSearchString
    and a search field string extractor function, this function returns a filter function
    that tells you if all search terms occur in any of the fields extracted by the extractor fn (in any order).
 
    E.g. if you have a type Person with firstName and lastName and you want it to search in both fields,
    you would call it like this:
 
    @example
    const searchWords = buildSearchWordsFromSearchString("peter mary")
    const filterFn = filterFunctionForSearchWords(searchWords, (person: Person) => [person.firstName, person.lastName])
    const filteredPeople = people.filter(filterFn)
*/
export function filterFunctionForSearchWords<TargetObject>(
    searchWords: SearchWord[],
    targetPropertyExtractorFn: (t: TargetObject) => (string | undefined)[]
): (target: TargetObject) => boolean {
    return (target: TargetObject): boolean =>
        searchWords.every((searchWord) =>
            targetPropertyExtractorFn(target).some(
                (searchString) =>
                    searchString !== undefined &&
                    searchWord.regex.test(searchString)
            )
        )
}
 
export function highlightFunctionForSearchWords(
    searchWords: SearchWord[]
): (text: string) => JSX.Element | string {
    return (text: string): JSX.Element | string => {
        if (searchWords.length > 0) {
            const firstMatches = searchWords
                .map((regex) => ({
                    matchStart: text.search(regex.regex),
                    matchLength: regex.word.length,
                }))
                .filter(({ matchStart }) => matchStart >= 0)
            const fragments: JSX.Element[] = []
            let lastIndex = 0
            if (firstMatches.length > 0) {
                // sort descending by end position and then length
                const sortedFirstMatches = sortBy(firstMatches, [
                    ({ matchStart, matchLength }) =>
                        -(matchStart + matchLength),
                    ({ matchStart, matchLength }) => -matchLength,
                ])
                // merge overlapping match ranges
                const mergedMatches = [sortedFirstMatches[0]]
                let lastMatch = mergedMatches[0]
                for (const match of drop(sortedFirstMatches, 1)) {
                    if (
                        lastMatch.matchStart <=
                        match.matchStart + match.matchLength
                    ) {
                        lastMatch.matchLength =
                            Math.max(
                                lastMatch.matchStart + lastMatch.matchLength,
                                match.matchStart + match.matchLength
                            ) - match.matchStart
                        lastMatch.matchStart = match.matchStart
                    } else {
                        mergedMatches.push(match)
                        lastMatch = match
                    }
                }
                // sort ascending
                const sortedMergedMatches = sortBy(
                    mergedMatches,
                    (match) => match.matchStart
                )

                // cut and add fragments
                for (const { matchStart, matchLength } of sortedMergedMatches) {
                    fragments.push(
                        <span key={`${lastIndex}-start`}>
                            {text.substring(lastIndex, matchStart)}
                        </span>
                    )
                    fragments.push(
                        <span
                            key={`${lastIndex}-content`}
                            style={{ color: "#aa3333" }}
                        >
                            {text.substring(
                                matchStart,
                                matchStart + matchLength
                            )}
                        </span>
                    )
                    lastIndex = matchStart + matchLength
                }
            }
            fragments.push(
                <span key={lastIndex}>{text.substring(lastIndex)}</span>
            )
            return <span>{fragments}</span>
        } else return text
    }
}
 
export const htmlToPlaintext = (html: string): string =>
    fromString(html, {
        tables: true,
        ignoreHref: true,
        wordwrap: false,
        uppercaseHeadings: false,
        ignoreImage: true,
    })
 
export const chunkWords = (text: string, maxChunkLength: number): string[] =>
    chunk(text, maxChunkLength)
 
export const chunkSentences = (
    text: string,
    maxChunkLength: number
): string[] => {
    // See https://stackoverflow.com/a/25736082/1983739
    // Not perfect, just works in most cases
    const sentenceRegex = /(?<!\w\.\w.)(?<![A-Z][a-z]\.)(?<=\.|\?|\n)\s/g
    const sentences = flatten(
        text
            .split(sentenceRegex)
            .map((s) =>
                s.length > maxChunkLength ? chunkWords(s, maxChunkLength) : s
            )
    )
        .map((s) => s.trim())
        .filter((s) => s)
        .reverse() as string[]
 
    const chunks = []
    let chunk = sentences.pop()
    if (!chunk) return []
 
    while (true) {
        const sentence = sentences.pop()
        if (!sentence) {
            chunks.push(chunk)
            break
        } else {
            const nextChunk: string = chunk + " " + sentence
            if (nextChunk.length > maxChunkLength) {
                chunks.push(chunk)
                chunk = sentence
            } else chunk = nextChunk
        }
    }
 
    return chunks
}
 
// Chunks a given bit of text into an array of fragments less than or equal to maxChunkLength in size
// These chunks will honor sentence boundaries where possible
export const chunkParagraphs = (
    text: string,
    maxChunkLength: number
): string[] => {
    const paragraphs = flatten(
        text
            .split("\n\n")
            .map((p) =>
                p.length > maxChunkLength
                    ? chunkSentences(p, maxChunkLength)
                    : p
            )
    )
        .map((p) => p.trim())
        .filter((p) => p)
        .reverse() as string[]
 
    const chunks = []
    let chunk = paragraphs.pop()
    if (!chunk) return []
 
    while (true) {
        const p = paragraphs.pop()
        if (!p) {
            chunks.push(chunk)
            break
        } else {
            const nextChunk: string = chunk + "\n\n" + p
            if (nextChunk.length > maxChunkLength) {
                chunks.push(chunk)
                chunk = p
            } else chunk = nextChunk
        }
    }
 
    return chunks
}