-
Notifications
You must be signed in to change notification settings - Fork 120
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
feat: add readthedocs javascript search #158
Open
ReenigneArcher
wants to merge
2
commits into
jothepro:main
Choose a base branch
from
ReenigneArcher:feat-add-readthedocs-javascript-search
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+237
−3
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
/* Highlight text in search results */ | ||
span.highlighted { | ||
background-color:var(--warning-color); | ||
color: var(--page-foreground-color); | ||
padding: 2px; | ||
border-radius: 3px; | ||
} | ||
|
||
/* Remove list bullets for search results */ | ||
ul.search { | ||
list-style-type: none; | ||
padding: 0; | ||
} | ||
|
||
/* Add horizontal divider for search results */ | ||
ul.search li.search-result { | ||
border-bottom: 1px solid var(--separator-color); | ||
padding-bottom: 10px; | ||
margin-bottom: 10px; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,172 @@ | ||
class DoxygenAwesomeReadtheDocsSearch { | ||
static searchResultsText=[ | ||
"Sorry, no pages matching your query.", | ||
"Search finished, found <b>1</b> page matching the search query.", | ||
"Search finished, found <b>$num</b> pages matching the search query.", | ||
]; | ||
|
||
static get serverUrl() { | ||
const serverUrlSuffix = '_/api/v3/'; | ||
const domainName = window.location.hostname; | ||
console.log(`Domain name: ${domainName}`); | ||
|
||
if (domainName === 'localhost') { | ||
let tmpServerUrl = serverUrl; | ||
while (tmpServerUrl.endsWith('/')) { | ||
tmpServerUrl = tmpServerUrl.slice(0, -1); | ||
} | ||
console.warn('Localhost detected, you probably need to bypass CORS'); | ||
return `${tmpServerUrl}/${serverUrlSuffix}`; | ||
} | ||
return `https://${domainName}/${serverUrlSuffix}`; | ||
} | ||
|
||
static init() { | ||
window.searchFor = function(query, page, count) { | ||
const results = $('#searchresults'); | ||
|
||
// Get the title | ||
let pageTitle = $('div.title') | ||
const originalTitle = pageTitle.text().toString(); | ||
let pageTitleStates = ["Searching", "Searching .", "Searching ..", "Searching ..."]; | ||
let pageTitleIndex = 0; | ||
|
||
// Function to update the page title | ||
function updatePageTitle() { | ||
pageTitle.text(pageTitleStates[pageTitleIndex]); | ||
pageTitleIndex = (pageTitleIndex + 1) % pageTitleStates.length; | ||
} | ||
|
||
// Start the interval to update the page title | ||
let titleInterval = setInterval(updatePageTitle, 500); | ||
|
||
// The summary will be displayed at the top of the search results | ||
let resultSummary = document.createElement('p'); | ||
resultSummary.className = 'search-summary'; | ||
results.append(resultSummary); | ||
|
||
// Put all results into an unordered list | ||
let resultList = document.createElement('ul'); | ||
resultList.className = 'search'; | ||
results.append(resultList); | ||
|
||
// readthedocs metadata | ||
// TODO: how to handle defaults? ... only matters when this is outside of readthedocs | ||
let projectSlug = DoxygenAwesomeReadtheDocsSearch.getMetaValue("readthedocs-project-slug") || "doxygen-awesome-css"; | ||
let projectVersion = DoxygenAwesomeReadtheDocsSearch.getMetaValue("readthedocs-version-slug") || "latest"; | ||
|
||
// pull requests are not indexed, so use the default version | ||
if (/^\d+$/.test(projectVersion)) { | ||
console.log('Pull request detected, getting default version from ReadTheDocs API'); | ||
DoxygenAwesomeReadtheDocsSearch.getReadTheDocsDefaultVersion(projectSlug); | ||
} | ||
|
||
let url = `${DoxygenAwesomeReadtheDocsSearch.serverUrl}search/?q=project:${projectSlug}/${projectVersion}+${query}&page=${page + 1}&page_size=${count}`; | ||
console.log(url); | ||
|
||
let firstUrl = true; | ||
|
||
function fetchResults(url) { | ||
$.ajax({ | ||
url: url, | ||
dataType: 'json', | ||
success: function (data) { | ||
// Add the query to the search field | ||
// This seems only be working if applied in the ajax success function... | ||
// maybe the field is not available before this point | ||
$('#MSearchField').val(query); | ||
|
||
if (firstUrl) { | ||
if (data.count > 0) { | ||
if (data.count === 1) { | ||
resultSummary.innerHTML = DoxygenAwesomeReadtheDocsSearch.searchResultsText[1]; | ||
} else { | ||
resultSummary.innerHTML = DoxygenAwesomeReadtheDocsSearch.searchResultsText[2].replace(/\$num/, data.count); | ||
} | ||
} else { | ||
resultSummary.innerHTML = DoxygenAwesomeReadtheDocsSearch.searchResultsText[0]; | ||
} | ||
} | ||
|
||
$.each(data.results, function (i, item) { | ||
let resultItem = document.createElement('li'); | ||
resultItem.className = 'search-result'; | ||
let resultItemUrl = `${item.domain}${item.path}`; | ||
let resultItemTitle = item.title; | ||
let resultItemType = item.type; // todo... we can possibly display results differently based on type | ||
let resultItemTitleLink = document.createElement('a'); | ||
let resultItemTitleHeading = document.createElement('h3'); | ||
resultItemTitleHeading.appendChild(resultItemTitleLink); | ||
resultItemTitleLink.href = resultItemUrl; | ||
resultItemTitleLink.textContent = resultItemTitle; | ||
resultItem.append(resultItemTitleHeading); | ||
resultList.append(resultItem); | ||
|
||
let resultItemParagraph = document.createElement('p'); | ||
resultItemParagraph.className = 'context'; | ||
for (let i = 0; i < item.blocks.length; i++) { | ||
let blockContent = item.blocks[i].highlights.content.join(', '); | ||
|
||
// Find all <span> tags and ensure they are highlighted | ||
blockContent = blockContent.replace(/<span>(.*?)<\/span>/g, '<span class="highlighted">$1</span>'); | ||
resultItemParagraph.innerHTML += blockContent; | ||
|
||
let blockName = `#${item.blocks[i].title.toLowerCase().replace(' ', '-')}`; | ||
let blockUrl = resultItemUrl + blockName; | ||
let blockLink = document.createElement('a'); | ||
blockLink.href = blockUrl; | ||
blockLink.textContent = "More..."; | ||
resultItemParagraph.append(document.createTextNode(' ')); | ||
resultItemParagraph.append(blockLink); | ||
resultItemParagraph.append(document.createElement('br')); | ||
} | ||
resultItem.append(resultItemParagraph); | ||
}); | ||
|
||
// Add pagination | ||
firstUrl = false; | ||
if (data.next) { | ||
fetchResults(data.next); | ||
} else { | ||
// Clear the interval when the search is complete | ||
clearInterval(titleInterval); | ||
pageTitle.text(originalTitle); | ||
} | ||
} | ||
}); | ||
} | ||
|
||
fetchResults(url); | ||
} | ||
} | ||
|
||
// Function to extract the value of a specified Read the Docs meta property | ||
static getMetaValue(propertyName) { | ||
const metaTags = document.getElementsByTagName('meta'); | ||
|
||
for (let meta of metaTags) { | ||
if (meta.name === propertyName) { | ||
return meta.content; | ||
} | ||
} | ||
|
||
return null; | ||
} | ||
|
||
static getReadTheDocsDefaultVersion(project) { | ||
let url = `${DoxygenAwesomeReadtheDocsSearch.serverUrl}projects/${project}/`; | ||
$.ajax({ | ||
url: url, | ||
dataType: 'json', | ||
success: function(data) { | ||
console.log(data); | ||
return data.default_version; | ||
}, | ||
error: function(jqXHR, textStatus, errorThrown) { | ||
console.error('Error:', textStatus, errorThrown); | ||
console.log(`Cannot determine default version for ${project}, assuming "latest"`); | ||
return "latest"; | ||
} | ||
}) | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
was
jquery
intentionally listed as adevDependency
here? Currently thepackage.json
is only used to allow for installation of the custom CSS. Can you explain your development workflow that requires the dependency to be added here?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, otherwise the IDE complains about undefined names, such as
ajax
if I recall.