Skip to content

Commit

Permalink
Keep default Search.init behavior if addons injected (#131)
Browse files Browse the repository at this point in the history
* Keep default `Search.init` behavior if addons injected

The extension removes the call to `Search.init` because it needs to perform some
injection before calling this method. The old implementation of the
`readthedocs-doc-embed.js` calls this method manually after modifying some
stuff.

However, with the introduction of addons, we don't want to manipulate the
defaults and the Sphinx default search should work out-of-the-box.

To keep the default behavior when addons is enabled, we check for addons
javascript and if it's present we call `_ready(Search.init);` as the default
Sphinx code does.

See readthedocs/addons#213 for more information.

* Update test case

* Lint

* Update integration test

* Wait for the DOM to be ready before checking for the `script`
  • Loading branch information
humitos authored Dec 13, 2023
1 parent 614109c commit 66e1167
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
16 changes: 15 additions & 1 deletion readthedocs_ext/readthedocs.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,21 @@ def remove_search_init(app, exception):
)

if os.path.exists(searchtools_file):
replacement_text = '/* Search initialization removed for Read the Docs */'
replacement_text = r"""
/* Search initialization manipulated by Read the Docs */
/* See https://github.com/readthedocs/addons/issues/213 for more information */
function triggerSearch() {
const addonsInjected = document.querySelector(
'script[src="/_/static/javascript/readthedocs-addons.js"]'
);
if (addonsInjected) {
Search.init();
}
}
_ready(triggerSearch);
"""
replacement_regex = re.compile(
r'''
^(\$\(document\).ready\(function\s*\(\)\s*{(?:\n|\r\n?)
Expand Down
8 changes: 6 additions & 2 deletions tests/test_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,12 @@ def test_included_data(self):
def test_searchtools_is_patched(self):
with build_output('pyexample', '_build/html/_static/searchtools.js',
builder='html') as data:
self.assertNotIn('Search.init();', data)
self.assertIn('Search initialization removed for Read the Docs', data)
search_content = "if (addonsInjected)"
self.assertIn(search_content, data)
search_content = "Search.init();"
self.assertIn(search_content, data)
search_content = "_ready(triggerSearch);"
self.assertIn(search_content, data)

def test_generate_json_artifacts(self):
self._run_test(
Expand Down

0 comments on commit 66e1167

Please sign in to comment.