Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add highlight option #188

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions example/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ root.render(
autoFocus
leftIcon={<>🎨</>}
iconBoxSize="48px"
includeMatches={true}
highlightStyle={{ fontWeight: "bolder", backgroundColor: "yellow" }}
/>
</React.StrictMode>
);
98 changes: 96 additions & 2 deletions src/dropdown/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { FC } from "react";
import { CSSProperties, FC } from "react";
import { StyledDropdown } from "./styles";

// the prototype of fuse.js's search result's match
// only work when includeMatches == true
interface Match {
indices: number[][];
key: string;
value: string;
}

interface IProps {
onClick: any;
matchedRecords: [
Expand All @@ -9,17 +17,99 @@ interface IProps {
key: string;
value: string;
};
matches?: Match[];
}
];
dropdownHoverColor: string;
dropdownBorderColor: string;
highlightStyle?: CSSProperties;
}

interface ItemProps {
/*
* the content
*/
value: string;
/*
* the matched places, to be highlighted
*/
matches?: Match[];
/*
* the highlighted span's style
* if matches is undefined or empty, this won't work
*/
highlightStyle?: CSSProperties;
}

const DropDownItem: FC<ItemProps> = ({ value, matches, highlightStyle }) => {
if (matches === undefined) {
return <div>value</div>;
} else {
const parts: JSX.Element[] = [];
let lastIndex = 0;

let rawIndexes = matches.map((item) => item.indices).flat();
let indexes = mergeIntervals(rawIndexes);
indexes.forEach((arr, index) => {
let start = arr[0];
let end = arr[1];
// Add non-highlighted text before the current highlighted text
if (start > lastIndex) {
parts.push(
<span key={`text-before-${index}`}>
{value.substring(lastIndex, start)}
</span>
);
}
// Add highlighted text
parts.push(
<span key={`highlight-${index}`} style={highlightStyle}>
{value.substring(start, end + 1)}
</span>
);
lastIndex = end + 1;
});

// Add any remaining non-highlighted text after the last highlighted section
if (lastIndex < value.length) {
parts.push(<span key="text-after">{value.substring(lastIndex)}</span>);
}

return <div>{parts}</div>;
}
};

// merge intervals of spans
const mergeIntervals = (intervals: number[][]): number[][] => {
if (!intervals.length) return [];

// Sort intervals by their start values
intervals.sort((a, b) => a[0] - b[0]);

const merged: number[][] = [intervals[0]];

for (let i = 1; i < intervals.length; i++) {
const prev = merged[merged.length - 1];
const current = intervals[i];

if (current[0] <= prev[1] + 1) {
// Check if current interval overlaps or is consecutive
// Merge intervals by updating the end value of the previous interval
prev[1] = Math.max(prev[1], current[1]);
} else {
merged.push(current);
}
}

return merged;
};

const Dropdown: FC<IProps> = ({
onClick,
matchedRecords = [],
dropdownBorderColor,
dropdownHoverColor,
highlightStyle,
}) => {
return (
<StyledDropdown
Expand All @@ -41,7 +131,11 @@ const Dropdown: FC<IProps> = ({
className="react-search-box-dropdown-list-item"
onClick={() => onClick(record)}
>
{record.item.value}
<DropDownItem
value={record.item.value}
matches={record.matches}
highlightStyle={highlightStyle}
/>
</li>
);
})}
Expand Down
16 changes: 16 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import Fuse from "fuse.js";
import React, {
CSSProperties,
ChangeEvent,
FC,
KeyboardEvent,
Expand Down Expand Up @@ -102,6 +103,17 @@ interface IProps {
* The type of the input.
*/
type?: string;

/*
* If return the matched ranges
*/
includeMatches?: boolean;

/*
* the highlighted span's style
* only works if the includeMatches is true
*/
highlightStyle?: CSSProperties;
}

const ReactSearchBox: FC<IProps> = ({
Expand All @@ -124,6 +136,8 @@ const ReactSearchBox: FC<IProps> = ({
leftIcon,
iconBoxSize = "24px",
type = "text",
includeMatches = false,
highlightStyle,
}) => {
const [matchedRecords, setMatchedRecords] = useState<any>([]);
const [value, setValue] = useState<string>("");
Expand All @@ -137,6 +151,7 @@ const ReactSearchBox: FC<IProps> = ({
* for more details.
*/
const defaultFuseConfigs = {
includeMatches: includeMatches,
/**
* At what point does the match algorithm give up. A threshold of 0.0
* requires a perfect match (of both letters and location), a threshold
Expand Down Expand Up @@ -302,6 +317,7 @@ const ReactSearchBox: FC<IProps> = ({
onClick={handleDropdownItemClick}
dropdownHoverColor={dropdownHoverColor}
dropdownBorderColor={dropdownBorderColor}
highlightStyle={highlightStyle}
/>
);
};
Expand Down