@siftql/react-highlighter
v0.1.2
Published
Paint siftql's highlight ranges. A dumb React component over a framework-free core.
Maintainers
Readme
@siftql/react-highlighter
Paint siftql's highlight ranges. A dumb React component over a framework-free core — it takes spans, not a query, so the same component works in a paragraph and in a grid.
▶ See it painting — the three states side by side, spans that do not describe the string, and the case where one character changes whether siftql will tell you where it matched. This is a package whose output is pixels, and the demo is the only honest way to show it.
npm install @siftql/react-highlighterimport { SiftQLHighlight } from '@siftql/react-highlighter';
<SiftQLHighlight text="Goldsmith" spans={[{ start: 4, end: 9 }]} />;
// Gold<mark>smith</mark>Why this rather than a word highlighter
Word-based highlighters take a list of search terms and find them again in the text. That is a second, independent match — and it disagrees with the first one, quietly, wherever the two use different rules. Case folding is where it shows up first: /s/iu marks ſ that siftql does not match, and dropping the u to fix that makes /k/i refuse the Kelvin sign that siftql does match.
siftql already knows where the match was. highlight() reports offsets from the matcher that decided the record matched, so there is nothing to re-derive and nothing to disagree about. This package turns those offsets into DOM.
It also carries a state a word highlighter structurally cannot express: matched, with nothing to underline. DOB:>=1990-01-01 is why the row is on screen, and no substring of 1990-05-20 is the reason.
Install
react >= 18 is a peer dependency, and CI runs the suite against 18 and 19 — the range is what is tested rather than what is assumed to work. Node 18 is the floor.
@siftql/core is an optional peer: needed only for the hook, never for the component. See Related packages.
The three states
spans is the whole API, and it has three values rather than two.
| spans | means | renders |
| ----------------- | ---------------------------------------- | ------------------------ |
| undefined | this value is not why the record matched | plain text |
| null | it is, but no substring of it is | wholeValueStyle |
| HighlightSpan[] | mark these offsets | <mark> around each run |
siftql expresses the middle state by omitting ranges, which collides with the undefined a failed Map.get returns. Somewhere between engine and component one of them has to become null — the Spans type is where that is written down.
The component
<SiftQLHighlight
text={row.surname}
spans={spansFor('surname')}
markStyle={{ backgroundColor: theme.palette.warning.light }}
/>| prop | default |
| ----------------------------- | --------------------------------- |
| text | required |
| spans | undefined |
| markStyle / markClassName | browser default <mark> |
| wholeValueStyle | { textDecoration: 'underline' } |
| wholeValueClassName | — |
| className / style | on the wrapper, in every state |
wholeValueStyle replaces the default rather than merging with it; pass {} to opt out.
A wrapper <span> is always emitted, in all three states, so the DOM shape does not change as a query does.
It takes spans, not a query
Deliberately. A component that ran the engine itself would be pleasant in a list of paragraphs and wrong in a grid, where it would re-match every cell on every scroll frame. Compute spans once where you already know what matched, and pass them down.
The hook
For the easy shape — a list of items, each rendering a few fields:
import { useSiftQLHighlight } from '@siftql/react-highlighter/siftql';
const Post = ({ query, post }) => {
const spansFor = useSiftQLHighlight(query, post);
return (
<article>
<h2>
<SiftQLHighlight text={post.title} spans={spansFor('title')} />
</h2>
<p>
<SiftQLHighlight text={post.body} spans={spansFor('body')} />
</p>
</article>
);
};spansFor is variadic because a field is a path: spansFor('name', 'first') addresses what siftql reports as segments: ['name', 'first'].
Three things worth knowing:
itemandoptionsare compared by identity, asuseMemodeps. An object literal built during render defeats the memo.- A query that fails to parse yields no highlights rather than throwing. A search box is mid-keystroke most of the time, and taking the screen down over decoration is the wrong trade. Whatever parses the query for filtering is what should report the error.
- Pass a
SiftQLAst, not a string, in anything real — parse once, filter and highlight with the same tree.
Not for grids
highlight() walks the AST once per call, so a hook per cell re-matches the same row for every column. Index the rows once and pass spans down:
const spans = useMemo(() => {
const byRow = new Map();
for (const row of matched) {
const byField = new Map();
for (const hit of highlight(ast, row))
byField.set(hit.segments[0], hit.ranges ?? null);
byRow.set(row.id, byField);
}
return byRow;
}, [ast, matched]);That index is application-specific — it keys on whatever identifies your rows — which is why it lives in your app rather than in this package.
Without React
toSegments is the whole library; the component is a <mark> and some props.
import { toSegments } from '@siftql/react-highlighter';
toSegments('Goldsmith', [{ start: 4, end: 9 }]);
// [{ text: 'Gold', marked: false }, { text: 'smith', marked: true }]It imports nothing. Spans may arrive unsorted, overlapping, touching, reversed, empty, negative, or past the end of the text; each is clamped or dropped, never thrown on — the offsets usually come from an engine and the text usually comes from a row, and nothing guarantees the two were computed from the same string. The returned runs always concatenate back to the input exactly.
Related packages
@siftql/core — the engine that produces the offsets this package paints. A Lucene-style query language with a hand-written parser, a serializer, an in-memory filter engine, real chronological date comparison, and zero runtime dependencies.
npm install @siftql/coreimport { highlight, parse } from '@siftql/core';
const ast = parse('surname:*smith* OR birthDate:>=1990-01-01');
highlight(ast, row);
// [{ path: 'surname', segments: ['surname'], ranges: [{ start: 4, end: 9 }] }]Only clauses that actually contributed are reported — the losing branch of an OR and everything under a satisfied NOT contribute nothing — which is why the spans reaching this package describe why the record is on screen, rather than every place a search term happens to appear.
It is an optional peer dependency here. toSegments and SiftQLHighlight take offsets and render them, so they install and work without it; only useSiftQLHighlight, behind the /siftql entry point, needs an engine. Spans from anywhere else work just as well.
What this package deliberately is not
There is no <SiftQLTable>, no <SiftQLDataGrid>, and no @siftql/mui. A component that renders inline content already works in a paragraph, a table cell and a list item — there is nothing table-shaped left to build. Adapters would mean owning an API for every grid library forever, and each one still needs its own row lookup, which is application-specific anyway.
UI-library integration is one prop: markStyle.
License
MIT
