Coverage for install/scipp/visualization/resources.py: 50%
34 statements
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-17 01:51 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2024-11-17 01:51 +0000
1# SPDX-License-Identifier: BSD-3-Clause
2# Copyright (c) 2023 Scipp contributors (https://github.com/scipp)
3# @file
4# @author Jan-Lukas Wynen
6import importlib.resources
7from functools import lru_cache, partial
10def _read_text(filename: str) -> str:
11 return (
12 importlib.resources.files('scipp.visualization.templates')
13 .joinpath(filename)
14 .read_text(encoding='utf-8')
15 )
18def _preprocess_style(raw_css: str) -> str:
19 import re
21 # line breaks are not needed
22 css = raw_css.replace('\n', '')
23 # remove comments
24 css = re.sub(r'/\*(\*(?!/)|[^*])*\*/', '', css)
25 # remove space around special characters
26 css = re.sub(r'\s*([;{}:,])\s*', r'\1', css)
27 return css
30@lru_cache(maxsize=1)
31def load_style_sheet() -> str:
32 """
33 Load the bundled CSS style and return it as a string.
34 The string is cached upon first call.
35 """
36 return _preprocess_style(_read_text('style.css'))
39def load_style() -> str:
40 """
41 Load the bundled CSS style and return it within <style> tags.
42 """
43 return '<style id="scipp-style-sheet">' + load_style_sheet() + '</style>'
46@lru_cache(maxsize=1)
47def load_icons() -> str:
48 """
49 Load the bundled icons and return them as an HTML string.
50 The string is cached upon first call.
51 """
52 return _read_text('icons-svg-inline.html')
55@lru_cache(maxsize=1)
56def load_dg_style() -> str:
57 """
58 Load the bundled CSS style and return it within <style> tags.
59 The string is cached upon first call.
60 Datagroup stylesheet is dependent on ``style.css``.
61 Therefore it loads both ``style.css`` and ``datagroup.css``.
62 """
63 style_sheet = (
64 '<style id="datagroup-style-sheet">'
65 + _preprocess_style(_read_text('datagroup.css'))
66 + '</style>'
67 )
69 return load_style() + style_sheet
72@lru_cache(maxsize=4)
73def _load_template(name: str) -> str:
74 """HTML template in scipp.visualization.templates"""
75 html_tpl = _read_text(name + '.html')
76 import re
78 # line breaks are not needed
79 html_tpl = html_tpl.replace('\n', '')
80 # remove comments
81 html_tpl = re.sub(r'<!--(.|\s|\n)*?-->', '', html_tpl)
82 # remove space around special characters
83 html_tpl = re.sub(r'\s*([><])\s*', r'\1', html_tpl)
84 return html_tpl
87load_atomic_row_tpl = partial(_load_template, name="dg_atomic_row")
88load_collapsible_row_tpl = partial(_load_template, name="dg_collapsible_row")
89load_dg_detail_list_tpl = partial(_load_template, name="dg_detail_list")
90load_dg_repr_tpl = partial(_load_template, name="dg_repr")