Skip to content

Commit

Permalink
Add css loader utility
Browse files Browse the repository at this point in the history
  • Loading branch information
edan-bainglass committed Aug 24, 2024
1 parent cab09b4 commit fd643e7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
38 changes: 38 additions & 0 deletions aiidalab_widgets_base/utils/loaders.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
from importlib.resources import Package, files

from IPython.display import Javascript, display


def load_css_stylesheet(package: Package, filename: str = ""):
"""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);
""")
)
8 changes: 8 additions & 0 deletions tests/test_loaders.py
Original file line number Diff line number Diff line change
@@ -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)

0 comments on commit fd643e7

Please sign in to comment.