Coverage for install/scipp/visualization/resources.py: 53%

36 statements  

« prev     ^ index     » next       coverage.py v7.4.0, created at 2024-04-28 01:28 +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 

5 

6import importlib.resources 

7from functools import lru_cache, partial 

8 

9 

10def _read_text(filename): 

11 return ( 

12 importlib.resources.files('scipp.visualization.templates') 

13 .joinpath(filename) 

14 .read_text() 

15 ) 

16 

17 

18def _preprocess_style(raw_css: str) -> str: 

19 import re 

20 

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 

28 

29 

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')) 

37 

38 

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>' 

44 

45 

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') 

53 

54 

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 from .formatting_html import load_style 

64 from .resources import _preprocess_style, _read_text 

65 

66 style_sheet = ( 

67 '<style id="datagroup-style-sheet">' 

68 + _preprocess_style(_read_text('datagroup.css')) 

69 + '</style>' 

70 ) 

71 

72 return load_style() + style_sheet 

73 

74 

75@lru_cache(maxsize=4) 

76def _load_template(name: str) -> str: 

77 """HTML template in scipp.visualization.templates""" 

78 html_tpl = _read_text(name + '.html') 

79 import re 

80 

81 # line breaks are not needed 

82 html_tpl = html_tpl.replace('\n', '') 

83 # remove comments 

84 html_tpl = re.sub(r'<!--(.|\s|\n)*?-->', '', html_tpl) 

85 # remove space around special characters 

86 html_tpl = re.sub(r'\s*([><])\s*', r'\1', html_tpl) 

87 return html_tpl 

88 

89 

90load_atomic_row_tpl = partial(_load_template, name="dg_atomic_row") 

91load_collapsible_row_tpl = partial(_load_template, name="dg_collapsible_row") 

92load_dg_detail_list_tpl = partial(_load_template, name="dg_detail_list") 

93load_dg_repr_tpl = partial(_load_template, name="dg_repr")