Coverage for gws-app/gws/lib/style/core.py: 52%

40 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-17 01:37 +0200

1from typing import Optional 

2 

3import gws 

4 

5from . import parser, icon 

6 

7 

8# parsing depends on whenever the context is `trusted` (=config) or not (=request) 

9 

10def from_dict(d: dict, opts: parser.Options = None) -> 'Object': 

11 """Creates a css style object from a dictionary. 

12 

13 Args: 

14 d: A dictionary. 

15 opts: Dictionary options. 

16 

17 Returns: 

18 A css style object. 

19 

20 """ 

21 vals = {} 

22 opts = opts or parser.Options(trusted=False, strict=True) 

23 

24 s = d.get('text') 

25 if s: 

26 vals.update(parser.parse_text(s, opts)) 

27 

28 s = d.get('values') 

29 if s: 

30 vals.update(parser.parse_dict(gws.u.to_dict(s), opts)) 

31 

32 return Object( 

33 d.get('cssSelector', ''), 

34 d.get('text', ''), 

35 gws.StyleValues(vals), 

36 ) 

37 

38 

39def from_config(cfg: gws.Config, opts: parser.Options = None) -> 'Object': 

40 """Creates a css style object from a configuration. 

41 

42 Args: 

43 cfg: A configuration. 

44 opts: Configuration options. 

45 

46 Returns: 

47 A css style object. 

48 

49 """ 

50 return from_dict( 

51 gws.u.to_dict(cfg), 

52 opts or parser.Options(trusted=True, strict=True)) 

53 

54 

55def from_props(props: gws.Props, opts: parser.Options = None) -> 'Object': 

56 """Creates a css style object from properties. 

57 

58 Args: 

59 props: Properties. 

60 opts: Property Options. 

61 

62 Returns: 

63 A css style object. 

64 

65 """ 

66 return from_dict( 

67 gws.u.to_dict(props), 

68 opts or parser.Options(trusted=False, strict=False)) 

69 

70 

71## 

72 

73 

74class Config(gws.Config): 

75 """Feature style""" 

76 

77 cssSelector: Optional[str] 

78 """CSS selector""" 

79 text: Optional[str] 

80 """raw style content""" 

81 values: Optional[dict] 

82 """style values""" 

83 

84 

85class Props(gws.Props): 

86 

87 cssSelector: Optional[str] 

88 """CSS selector""" 

89 values: Optional[dict] 

90 """Style values""" 

91 

92 

93class Object(gws.Style): 

94 def __init__(self, selector, text, values): 

95 self.cssSelector = selector 

96 self.text = text 

97 self.values = values 

98 

99 def props(self, user): 

100 ico = self.values.icon 

101 if ico and isinstance(ico, icon.ParsedIcon): 

102 ico = icon.to_data_url(ico) 

103 else: 

104 # NB if icon is not parsed, don't give it back 

105 ico = '' 

106 

107 return Props( 

108 cssSelector=self.cssSelector or '', 

109 values=gws.u.merge(self.values, icon=ico), 

110 )