From 66e11678d4d0b517aa49c3345e4f15b56ea221ce Mon Sep 17 00:00:00 2001 From: Manuel Kaufmann Date: Wed, 13 Dec 2023 09:34:04 +0100 Subject: [PATCH] Keep default `Search.init` behavior if addons injected (#131) * 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 https://github.com/readthedocs/addons/issues/213 for more information. * Update test case * Lint * Update integration test * Wait for the DOM to be ready before checking for the `script` --- readthedocs_ext/readthedocs.py | 16 +++++++++++++++- tests/test_integration.py | 8 ++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/readthedocs_ext/readthedocs.py b/readthedocs_ext/readthedocs.py index 9d4b7b8..0a06c62 100644 --- a/readthedocs_ext/readthedocs.py +++ b/readthedocs_ext/readthedocs.py @@ -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?) diff --git a/tests/test_integration.py b/tests/test_integration.py index 9070e2f..0e012d1 100644 --- a/tests/test_integration.py +++ b/tests/test_integration.py @@ -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(