Skip to content

Commit

Permalink
feat highlightResult option added
Browse files Browse the repository at this point in the history
  • Loading branch information
praveenn77 committed Sep 16, 2023
1 parent 255eb43 commit 426e313
Show file tree
Hide file tree
Showing 8 changed files with 3,208 additions and 3,241 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,8 @@ Supports all the language listed here https://github.com/MihaiValentin/lunr-lang
| `excludeRoutes` | `Array` | `[]` | Exclude certain routes from the search |
| `includeRoutes` | `Array` | `[]` | Include only specific routes for search |
| `stopWords` | `Array` | `[]` | Add stop words(words that are exclude from search result) to the search index |
| `excludeTags` | `Array` | `[]` | Exclude certain tags from the search |
| `excludeTags` | `Array` | `[]` | Exclude certain tags from the search
| `highlightResult` | `Boolean` | `false` | Enable it to highlight the searched word in the result page. Used `mark.js` for highlighting. <br /> You can customize the highlight color using css <br /> ``` mark { background-color: red !important; color: green !important }``` |
| `disableVersioning` | `Boolean` | `false` | Docs versions are displayed by default. If you want to hide it, set this plugin option to `true` |

## Indexing non-direct children headings of `.markdown`
Expand Down
6,311 changes: 3,100 additions & 3,211 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "docusaurus-lunr-search",
"version": "2.4.3",
"version": "3.0.0",
"description": "Offline search component for Docusaurus V2",
"main": "src/index.js",
"publishConfig": {
Expand Down Expand Up @@ -48,6 +48,7 @@
"hogan.js": "^3.0.2",
"lunr": "^2.3.8",
"lunr-languages": "^1.4.0",
"mark.js": "^8.11.1",
"minimatch": "^3.0.4",
"object-assign": "^4.1.1",
"rehype-parse": "^7.0.1",
Expand Down
2 changes: 1 addition & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ module.exports = function (context, options) {
console.timeEnd('docusaurus-lunr-search:: Indexing time')
console.log(`docusaurus-lunr-search:: indexed ${indexedDocuments} documents out of ${files.length}`)

const searchDocFileContents = JSON.stringify(searchDocuments)
const searchDocFileContents = JSON.stringify({ searchDocs: searchDocuments, options })
console.log('docusaurus-lunr-search:: writing search-doc.json')
// This file is written for backwards-compatibility with components swizzled from v2.1.12 or earlier.
fs.writeFileSync(
Expand Down
53 changes: 53 additions & 0 deletions src/theme/SearchBar/HighlightSearchResults.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
//copied from https://github.com/cmfcmf/docusaurus-search-local
import Mark from "mark.js";
import { useEffect, useState } from "react";
import { useLocation } from "@docusaurus/router";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import { useHistory } from "@docusaurus/router";

export function HighlightSearchResults() {
const location = useLocation();
const history = useHistory();
const {
siteConfig: { baseUrl },
} = useDocusaurusContext();

const [highlightData, setHighlightData] = useState({ wordToHighlight: '', isTitleSuggestion: false , titleText: '' });

useEffect(() => {
if (
!location.state?.highlightState ||
location.state.highlightState.wordToHighlight.length === 0
) {
return;
}
setHighlightData(location.state.highlightState);

const { highlightState, ...state } = location.state;
history.replace({
...location,
state,
});
}, [location.state?.highlightState, history, location]);

useEffect(() => {
if (highlightData.wordToHighlight.length === 0) {
return;
}

// Make sure to also adjust parse.js if you change the top element here.
const root = document.getElementsByTagName("article")[0] ?? document.getElementsByTagName("main")[0] ;
if (!root) {
return;
}

const mark = new Mark(root);
const options = {
ignoreJoiners: true,
};
mark.mark(highlightData.wordToHighlight , options);
return () => mark.unmark(options);
}, [highlightData, baseUrl]);

return null;
}
4 changes: 4 additions & 0 deletions src/theme/SearchBar/algolia.css
Original file line number Diff line number Diff line change
Expand Up @@ -554,3 +554,7 @@ html[data-theme='dark'] .algolia-docsearch-suggestion--title {
html[data-theme='dark'] .ds-cursor .algolia-docsearch-suggestion--wrapper {
background: var(--ifm-background-surface-color) !important;
}

mark{
background-color: lightblue;
}
66 changes: 39 additions & 27 deletions src/theme/SearchBar/index.js → src/theme/SearchBar/index.jsx
Original file line number Diff line number Diff line change
@@ -1,16 +1,10 @@
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import React, { useRef, useCallback, useState } from "react";
import clsx from "clsx";
import { useHistory } from "@docusaurus/router";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import { usePluginData } from '@docusaurus/useGlobalData';
import useIsBrowser from "@docusaurus/useIsBrowser";
import { HighlightSearchResults } from "./HighlightSearchResults";
const Search = props => {
const initialized = useRef(false);
const searchBarRef = useRef(null);
Expand All @@ -19,26 +13,42 @@ const Search = props => {
const { siteConfig = {} } = useDocusaurusContext();
const isBrowser = useIsBrowser();
const { baseUrl } = siteConfig;
const initAlgolia = (searchDocs, searchIndex, DocSearch) => {
new DocSearch({
searchDocs,
searchIndex,
baseUrl,
inputSelector: "#search_input_react",
// Override algolia's default selection event, allowing us to do client-side
// navigation and avoiding a full page refresh.
handleSelected: (_input, _event, suggestion) => {
const url = suggestion.url || "/";
// Use an anchor tag to parse the absolute url into a relative url
// Alternatively, we can use new URL(suggestion.url) but its not supported in IE
const a = document.createElement("a");
a.href = url;
// Algolia use closest parent element id #__docusaurus when a h1 page title does not have an id
// So, we can safely remove it. See https://github.com/facebook/docusaurus/issues/1828 for more details.
const initAlgolia = (searchDocs, searchIndex, DocSearch, options) => {
new DocSearch({
searchDocs,
searchIndex,
baseUrl,
inputSelector: "#search_input_react",
// Override algolia's default selection event, allowing us to do client-side
// navigation and avoiding a full page refresh.
handleSelected: (_input, _event, suggestion) => {
const url = suggestion.url || "/";
// Use an anchor tag to parse the absolute url into a relative url
// Alternatively, we can use new URL(suggestion.url) but its not supported in IE
const a = document.createElement("a");
a.href = url;

history.push(url);
// Get the highlight word from the suggestion.
let wordToHighlight = '';
if (options.highlightResult) {
try {
const matchedLine = suggestion.text || suggestion.subcategory || suggestion.title;
const matchedWordResult = matchedLine.match(new RegExp('<span.+span>\\w*', 'g'));
if (matchedWordResult && matchedWordResult.length > 0) {
const tempDoc = document.createElement('div');
tempDoc.innerHTML = matchedWordResult[0];
wordToHighlight = tempDoc.textContent;
}
} catch (e) {
console.log(e);
}
}
});

history.push(url, {
highlightState: { wordToHighlight },
});
}
});
};

const pluginData = usePluginData('docusaurus-lunr-search');
Expand All @@ -59,11 +69,12 @@ const Search = props => {
getLunrIndex(),
import("./DocSearch"),
import("./algolia.css")
]).then(([searchDocs, searchIndex, { default: DocSearch }]) => {
]).then(([searchDocFile, searchIndex, { default: DocSearch }]) => {
const { searchDocs, options } = searchDocFile;
if (searchDocs.length === 0) {
return;
}
initAlgolia(searchDocs, searchIndex, DocSearch);
initAlgolia(searchDocs, searchIndex, DocSearch, options);
setIndexReady(true);
});
initialized.current = true;
Expand Down Expand Up @@ -114,6 +125,7 @@ const Search = props => {
ref={searchBarRef}
disabled={!indexReady}
/>
<HighlightSearchResults />
</div>
);
};
Expand Down
7 changes: 7 additions & 0 deletions src/theme/SearchBar/lunar-search.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
/*
Aloglia DocSearch Adapter for Lunr.js
====================================
Written by: Praveen N
github: praveenn77
*/

import lunr from "@generated/lunr.client";
lunr.tokenizer.separator = /[\s\-/]+/;

Expand Down

0 comments on commit 426e313

Please sign in to comment.