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
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-17 01:37 +0200
1from typing import Optional
3import gws
5from . import parser, icon
8# parsing depends on whenever the context is `trusted` (=config) or not (=request)
10def from_dict(d: dict, opts: parser.Options = None) -> 'Object':
11 """Creates a css style object from a dictionary.
13 Args:
14 d: A dictionary.
15 opts: Dictionary options.
17 Returns:
18 A css style object.
20 """
21 vals = {}
22 opts = opts or parser.Options(trusted=False, strict=True)
24 s = d.get('text')
25 if s:
26 vals.update(parser.parse_text(s, opts))
28 s = d.get('values')
29 if s:
30 vals.update(parser.parse_dict(gws.u.to_dict(s), opts))
32 return Object(
33 d.get('cssSelector', ''),
34 d.get('text', ''),
35 gws.StyleValues(vals),
36 )
39def from_config(cfg: gws.Config, opts: parser.Options = None) -> 'Object':
40 """Creates a css style object from a configuration.
42 Args:
43 cfg: A configuration.
44 opts: Configuration options.
46 Returns:
47 A css style object.
49 """
50 return from_dict(
51 gws.u.to_dict(cfg),
52 opts or parser.Options(trusted=True, strict=True))
55def from_props(props: gws.Props, opts: parser.Options = None) -> 'Object':
56 """Creates a css style object from properties.
58 Args:
59 props: Properties.
60 opts: Property Options.
62 Returns:
63 A css style object.
65 """
66 return from_dict(
67 gws.u.to_dict(props),
68 opts or parser.Options(trusted=False, strict=False))
71##
74class Config(gws.Config):
75 """Feature style"""
77 cssSelector: Optional[str]
78 """CSS selector"""
79 text: Optional[str]
80 """raw style content"""
81 values: Optional[dict]
82 """style values"""
85class Props(gws.Props):
87 cssSelector: Optional[str]
88 """CSS selector"""
89 values: Optional[dict]
90 """Style values"""
93class Object(gws.Style):
94 def __init__(self, selector, text, values):
95 self.cssSelector = selector
96 self.text = text
97 self.values = values
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 = ''
107 return Props(
108 cssSelector=self.cssSelector or '',
109 values=gws.u.merge(self.values, icon=ico),
110 )