metonym / format-fuse.js

Utility to format matching fuse.js results for easier text highlighting
MIT License
3 stars 1 forks source link
fusejs text-highlighting

format-fuse.js

NPM

Utility to format matching fuse.js results for easier text highlighting.

Install

yarn add format-fuse.js

Usage

The utility expects fuse.js search results as an array and outputs matching text based on matching indices.

import format from "format-fuse.js";

const results = format([
  {
    item: {
      title: "Monster 1959",
      author: { firstName: "David", lastName: "Maine" },
    },
    matches: [
      {
        indices: [[1, 2]],
        value: "Monster 1959",
        key: "title",
        arrayIndex: 0,
      },
    ],
  },
]);

console.log(results);
/**
 * [
    {
      author: { firstName: 'David', lastName: 'Maine' },
      title: [
        { matches: false, text: 'M' },
        { matches: true, text: 'on' },
        { matches: false, text: 'ster 1959' }
      ]
    }
  ]
 */

Matching and unmatching text become easier to iterate through.

Example

import * as React from "react";

export function Highlighter(results) {
  return (
    <div>
      {results.map(({ title }) => {
        if (Array.isArray(title)) {
          return title.map(({ matches, text }) => {
            return matches ? <mark>{text}</mark> : text;
          });
        }

        return title;
      })}
    </div>
  );
}

Changelog

License

MIT