Skip to content

Instantly share code, notes, and snippets.

@sghall
Created April 3, 2020 21:12
Show Gist options
  • Save sghall/70722d430b4c39fb207da0e902dbed0e to your computer and use it in GitHub Desktop.
Save sghall/70722d430b4c39fb207da0e902dbed0e to your computer and use it in GitHub Desktop.
Marked Message
// Test Component:
interface MarkedMessageProps {
message: string;
matches: { offset: number; length: number }[];
}
const MarkedMessage: React.FC<MarkedMessageProps> = ({ message, matches }) => {
const parts: React.ReactNode[] = [];
let runningOffset = 0;
let remainder = message;
for (let i = 0; i < matches.length; i++) {
const { offset, length } = matches[i];
const index = offset - runningOffset;
const prefix = remainder.slice(0, index);
const match = remainder.slice(index, index + length);
parts.push(prefix);
parts.push(<mark>{match}</mark>);
runningOffset += prefix.length + match.length;
remainder = remainder.slice(prefix.length + match.length);
}
parts.push(remainder);
return <>{parts}</>;
};
// Example Data:
const example = {
string:
'{"engine":"POSTGRES","instanceID":"raven-production","instanceResourceID":"db-XNHXGZ7AUUXKHPP5DR3JC3ME2Q","timestamp":"2020-03-18T14:54:18Z","version":1,"uptime":"313 days, 23:08:08","numVCPUs":2}',
matches: [
{
offset: 41,
length: 10,
},
{
offset: 119,
length: 4,
},
],
};
// Usage:
<MarkedMessage message={example.string} matches={example.matches} />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment