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

Add Document Search #534

Merged
merged 7 commits into from
Jan 26, 2021
Merged
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 microsite/docs/docs/intro.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ This plugin is based on and utilizes other awesome sbt plugins to make it possib

The plugin provides basic free styles, css, and image resources by default. Everything is based on the [Bootstrap](https://getbootstrap.com/) framework. If you want to personalize the color palette, styles, and images for your project, you can easily do so by viewing the steps in the [documentation]({% link docs/getting-started.md %}).

Document search is provided by the [Lunr.js](https://lunrjs.com/) project for client-side search functionality.

In order to create microsites, this plugin directly uses the following plugins and libraries:

* [sbt-mdoc](https://github.com/scalameta/mdoc)
Expand Down
2 changes: 2 additions & 0 deletions microsite/docs/docs/settings.md
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,8 @@ Each file (the map key) can be related to a specific configuration through the `
micrositePluginsDirectory := (resourceDirectory in Compile).value / "site" / "plugins"
```

- `micrositeSearchEnabled`: Whether or not the search bar functionality is enabled for your microsite. Enabled by default. To disable, set to `false`.

- `micrositeTheme`: You can choose two different themes to generate your microsite. By default it will display the `light` theme but you have the option of choosing the classic `pattern` theme.

```scala
Expand Down
62 changes: 62 additions & 0 deletions src/main/resources/_sass/light-style/_doc-search.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
div[id$='search-dropdown'] {
position: relative;

.dropdown {
display: block;
outline: 0;
width: 100%;
}

label {
padding-right: 0.3em;

i {
padding-right: 0.2em;
}
}

/* Documentation Dropdown Content (Hidden by Default) */
.dropdown-content {
position: absolute;
min-width: 100px;
overflow: hidden auto;
box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
z-index: 1;
background: $white-color;
margin: 0;
padding: 0;
opacity: 0.5;
transform: rotate3d(1, 0, 0, 90deg);
transition: transform ease 250ms, opacity ease 100ms;
transform-origin: top;

.dropdown-item {
width: 100%;

.dropdown-item-link {
padding: 12px 9px;
text-decoration: none;
display: block;
border-radius: 0;
color: #333;

&:hover span {
border-bottom: 2px solid;
}

&:focus span {
border-bottom: 2px solid;
}

}
}
}

/* Show the documentation dropdown menu (use JS to add this class
to the .dropdown-content container when the user clicks on
the dropdown button) */
.show {
transform: rotate3d(1, 0, 0, 0);
opacity: 1;
}
}
4 changes: 2 additions & 2 deletions src/main/resources/_sass/light-style/_light-docs.scss
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@
height: $top-bar-size;
}

a {
a:not(.dropdown-item-link) {
color: $brand-primary;
padding: 0 $base-point-grid * 2;
display: block;
Expand All @@ -209,7 +209,7 @@
list-style: none;
display: inline-block;

span {
span:not(.dropdown-item-link-text) {
display: inline-flex;
flex-direction: row-reverse;
font-size: 14px;
Expand Down
1 change: 1 addition & 0 deletions src/main/resources/css/light-style.scss
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
@import "light-style/button";
@import "light-style/masthead";
@import "light-style/main";
@import "light-style/doc-search";
@import "light-style/doc-versions";
@import "light-style/footer";
@import "light-style/light-docs";
Expand Down
192 changes: 192 additions & 0 deletions src/main/resources/js/search.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
---
---
// When the user clicks on the search box, we want to toggle the search dropdown
function displayToggleSearch(e) {
e.preventDefault();
e.stopPropagation();

closeDropdownSearch(e);

if (idx === null) {
console.log("Building search index...");
prepareIdxAndDocMap();
console.log("Search index built.");
}
const dropdown = document.querySelector("#search-dropdown-content");
if (dropdown) {
if (!dropdown.classList.contains("show")) {
dropdown.classList.add("show");
}
document.addEventListener("click", closeDropdownSearch);
document.addEventListener("keydown", searchOnKeyDown);
document.addEventListener("keyup", searchOnKeyUp);
}
}

//We want to prepare the index only after clicking the search bar
var idx = null
const docMap = new Map()

function prepareIdxAndDocMap() {
const docs = [{% if site.search_enabled %} {% for page in site.pages %} {% if page.title %}
{
"title": "{{ page.title }}",
"url": "{{ site.baseurl }}{{ page.url }}",
"content": {{ page.content | markdownify | strip_html | normalize_whitespace | strip | jsonify }}
} {% unless forloop.last %}, {% endunless %} {% endif %} {% endfor %} {% endif %}
];

idx = lunr(function () {
this.ref("title");
this.field("content");

docs.forEach(function (doc) {
this.add(doc);
}, this);
});

docs.forEach(function (doc) {
docMap.set(doc.title, doc.url);
});
}

// The onkeypress handler for search functionality
function searchOnKeyDown(e) {
const keyCode = e.keyCode;
const parent = e.target.parentElement;
const isSearchBar = e.target.id === "search-bar";
const isSearchResult = parent ? parent.id.startsWith("result-") : false;
const isSearchBarOrResult = isSearchBar || isSearchResult;

if (keyCode === 40 && isSearchBarOrResult) {
// On 'down', try to navigate down the search results
e.preventDefault();
e.stopPropagation();
selectDown(e);
} else if (keyCode === 38 && isSearchBarOrResult) {
// On 'up', try to navigate up the search results
e.preventDefault();
e.stopPropagation();
selectUp(e);
} else if (keyCode === 27 && isSearchBarOrResult) {
// On 'ESC', close the search dropdown
e.preventDefault();
e.stopPropagation();
closeDropdownSearch(e);
}
}

// Search is only done on key-up so that the search terms are properly propagated
function searchOnKeyUp(e) {
// Filter out up, down, esc keys
const keyCode = e.keyCode;
const cannotBe = [40, 38, 27];
const isSearchBar = e.target.id === "search-bar";
const keyIsNotWrong = !cannotBe.includes(keyCode);
if (isSearchBar && keyIsNotWrong) {
// Try to run a search
runSearch(e);
}
}

// Move the cursor up the search list
function selectUp(e) {
if (e.target.parentElement.id.startsWith("result-")) {
const index = parseInt(e.target.parentElement.id.substring(7));
if (!isNaN(index) && (index > 0)) {
const nextIndexStr = "result-" + (index - 1);
const querySel = "li[id$='" + nextIndexStr + "'";
const nextResult = document.querySelector(querySel);
if (nextResult) {
nextResult.firstChild.focus();
}
}
}
}

// Move the cursor down the search list
function selectDown(e) {
if (e.target.id === "search-bar") {
const firstResult = document.querySelector("li[id$='result-0']");
if (firstResult) {
firstResult.firstChild.focus();
}
} else if (e.target.parentElement.id.startsWith("result-")) {
const index = parseInt(e.target.parentElement.id.substring(7));
if (!isNaN(index)) {
const nextIndexStr = "result-" + (index + 1);
const querySel = "li[id$='" + nextIndexStr + "'";
const nextResult = document.querySelector(querySel);
if (nextResult) {
nextResult.firstChild.focus();
}
}
}
}

// Search for whatever the user has typed so far
function runSearch(e) {
if (e.target.value === "") {
// On empty string, remove all search results
// Otherwise this may show all results as everything is a "match"
applySearchResults([]);
} else {
const tokens = e.target.value.split(" ");
const moddedTokens = tokens.map(function (token) {
// "*" + token + "*"
return token;
})
const searchTerm = moddedTokens.join(" ");
const searchResults = idx.search(searchTerm);
const mapResults = searchResults.map(function (result) {
const resultUrl = docMap.get(result.ref);
return { name: result.ref, url: resultUrl };
})

applySearchResults(mapResults);
}

}

// After a search, modify the search dropdown to contain the search results
function applySearchResults(results) {
const dropdown = document.querySelector("div[id$='search-dropdown'] > .dropdown-content.show");
if (dropdown) {
//Remove each child
while (dropdown.firstChild) {
dropdown.removeChild(dropdown.firstChild);
}

//Add each result as an element in the list
results.forEach(function (result, i) {
const elem = document.createElement("li");
elem.setAttribute("class", "dropdown-item");
elem.setAttribute("id", "result-" + i);

const elemLink = document.createElement("a");
elemLink.setAttribute("title", result.name);
elemLink.setAttribute("href", result.url);
elemLink.setAttribute("class", "dropdown-item-link");

const elemLinkText = document.createElement("span");
elemLinkText.setAttribute("class", "dropdown-item-link-text");
elemLinkText.innerHTML = result.name;

elemLink.appendChild(elemLinkText);
elem.appendChild(elemLink);
dropdown.appendChild(elem);
});
}
}

// Close the dropdown if the user clicks (only) outside of it
function closeDropdownSearch(e) {
// Check if where we're clicking is the search dropdown
if (e.target.id !== "search-bar") {
const dropdown = document.querySelector("div[id$='search-dropdown'] > .dropdown-content.show");
if (dropdown) {
dropdown.classList.remove("show");
document.documentElement.removeEventListener("click", closeDropdownSearch);
}
}
}
14 changes: 7 additions & 7 deletions src/main/resources/js/version-selector.js
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
/* When the user clicks on the navigation Documentation button,
* toggle between hiding and showing the dropdown content.
*/
function displayToggle(e) {
function displayToggleVersion(e) {
e.preventDefault();
e.stopPropagation();
// Calling close func. in case we're clicking another dropdown with one opened
closeDropdown(e);
closeDropdownVersion(e);
const parent = e.target.closest("div[id$='version-dropdown']");
if (parent) {
const dropdown = parent.querySelector(".dropdown-content");
const dropdown = parent.querySelector("#version-dropdown-content");
if (dropdown) {
dropdown.classList.toggle("show");
if (dropdown.classList.contains("show")) {
document.documentElement.addEventListener("click", closeDropdown);
document.documentElement.addEventListener("click", closeDropdownVersion);
}
else {
document.documentElement.removeEventListener("click", closeDropdown);
document.documentElement.removeEventListener("click", closeDropdownVersion);
}
}
}
}

// Close the dropdown if the user clicks (only) outside of it
function closeDropdown(e) {
function closeDropdownVersion(e) {
const dropdown = document.querySelector("div[id$='version-dropdown'] > .dropdown-content.show");
if (dropdown) {
const currentTarget = e.currentTarget || {};
Expand All @@ -31,6 +31,6 @@ function closeDropdown(e) {
if (currentTargetParent !== dropdownParent) {
dropdown.classList.remove("show");
}
document.documentElement.removeEventListener("click", closeDropdown);
document.documentElement.removeEventListener("click", closeDropdownVersion);
}
}
20 changes: 20 additions & 0 deletions src/main/resources/lunr/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@

Copyright (C) 2013 by Oliver Nightingale

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
Loading