Last active
July 28, 2022 00:21
-
-
Save jeziellopes/8f807f72ac23dc012d5c4b9f06bd1e0d to your computer and use it in GitHub Desktop.
This is my imlementation of Typing Bold Effect when searching with ReactJS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react"; | |
import styled from "styled-components"; | |
export const Bold = styled.label` | |
cursor: pointer; | |
font-size: 12px; | |
font-weight: bold; | |
`; | |
/** | |
* Wrapper for labels with bold effect on search | |
* @param {String} label full label string | |
* @param {Array} matches all regex matches for a given search | |
* @param {JSX.Element} Wrapper component wapper for searchs | |
* @returns returns a label with bold effect | |
*/ | |
export const withBoldEffect = (label, matches) => { | |
const bold = matches.map(m => m.indices.pop()); | |
const all = getAllPositions(label, bold); | |
return all.reduce( | |
(withBold, p) => [ | |
...withBold, | |
bold.includes(p) ? ( | |
<Bold>{label.slice(...p)}</Bold> | |
) : ( | |
label.slice(...p) | |
), | |
], | |
[], | |
); | |
}; | |
/** | |
* Helper to get search matches even when not a word | |
* @param {String} string full string to search content | |
* @param {Array} bold all bold positions for a given search | |
* @returns returns array of all elements positions | |
*/ | |
export const getMatches = (string, search) => { | |
if (string && search && search.length) { | |
let match; | |
const matches = []; | |
const re = new RegExp(search, "gid"); | |
do { | |
match = re.exec(string); | |
if (match) { | |
matches.push(match); | |
} | |
} while (match); | |
return matches; | |
} | |
return false; | |
}; | |
/** | |
* Helper to found string elements positions | |
* @param {String} string full string to search content | |
* @param {Array} bold all bold positions for a given search | |
* @returns returns array of all elements positions | |
*/ | |
export const getAllPositions = (string, bold) => { | |
let temp = []; | |
let lastEnd; | |
return bold.reduce((positions, pos, i) => { | |
const [start, end] = pos; | |
temp = []; | |
if (i === 0 && i < start) { | |
temp.push([i, start]); | |
} | |
if (i === 0 || lastEnd === start) { | |
temp.push(pos); | |
} else { | |
const last = [lastEnd, start]; | |
temp = [last, pos]; | |
} | |
if (i === bold.length - 1) { | |
temp.push([end, string.length]); | |
} | |
lastEnd = end; | |
return [...positions, ...temp]; | |
}, []); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment