From c961bc4ec60e49a5ac62c793a8e8990ad30e066c Mon Sep 17 00:00:00 2001 From: Edan Bainglass Date: Thu, 11 Jul 2024 09:54:13 +0000 Subject: [PATCH] Add css loader utility --- aiidalab_widgets_base/utils/loaders.py | 38 ++++++++++++++++++++++++++ tests/test_loaders.py | 8 ++++++ 2 files changed, 46 insertions(+) create mode 100644 aiidalab_widgets_base/utils/loaders.py create mode 100644 tests/test_loaders.py diff --git a/aiidalab_widgets_base/utils/loaders.py b/aiidalab_widgets_base/utils/loaders.py new file mode 100644 index 000000000..4d00fc908 --- /dev/null +++ b/aiidalab_widgets_base/utils/loaders.py @@ -0,0 +1,38 @@ +from importlib.resources import Package, files + +from IPython.display import Javascript, display + + +def load_css_stylesheet(package: Package, filename=""): + """Load a CSS stylesheet from a package and inject it into the DOM. + + Parameters + ---------- + `package` : `Package` + The package where the CSS file is located. + `filename` : `str`, optional + The name of the CSS file to load. + If not provided, all CSS files in the package will be loaded. + """ + root = files(package) + + filenames = [] + if filename: + filenames.append(filename) + else: + filenames.extend( + path.name + for path in root.iterdir() + if path.is_file() and path.name.endswith(".css") + ) + + for filename in filenames: + stylesheet = (root / filename).read_text() + display( + Javascript(f""" + var style = document.createElement('style'); + style.type = 'text/css'; + style.innerHTML = `{stylesheet}`; + document.head.appendChild(style); + """) + ) diff --git a/tests/test_loaders.py b/tests/test_loaders.py new file mode 100644 index 000000000..21caa9186 --- /dev/null +++ b/tests/test_loaders.py @@ -0,0 +1,8 @@ +from aiidalab_widgets_base.utils.loaders import load_css_stylesheet + + +def test_load_css_stylesheet(): + """Test `load_css_stylesheet` function.""" + package = "aiidalab_widgets_base.static.styles" + load_css_stylesheet(package=package, filename="global.css") + load_css_stylesheet(package=package)