forked from jaraco/cssutils
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathselectorlist.py
More file actions
243 lines (206 loc) · 8.17 KB
/
selectorlist.py
File metadata and controls
243 lines (206 loc) · 8.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
"""SelectorList is a list of CSS Selector objects.
TODO
- remove duplicate Selectors. -> CSSOM canonicalize
- ??? CSS2 gives a special meaning to the comma (,) in selectors.
However, since it is not known if the comma may acquire other
meanings in future versions of CSS, the whole statement should be
ignored if there is an error anywhere in the selector, even though
the rest of the selector may look reasonable in CSS2.
Illegal example(s):
For example, since the "&" is not a valid token in a CSS2 selector,
a CSS2 user agent must ignore the whole second line, and not set
the color of H3 to red:
"""
__all__ = ['SelectorList']
import cssutils
from .selector import Selector
class SelectorList(cssutils.util.Base, cssutils.util.ListSeq):
"""A list of :class:`~cssutils.css.Selector` objects
of a :class:`~cssutils.css.CSSStyleRule`."""
def __init__(self, selectorText=None, parentRule=None, readonly=False):
"""
:Parameters:
selectorText
parsable list of Selectors
parentRule
the parent CSSRule if available
"""
super().__init__()
self._parentRule = parentRule
if selectorText:
self.selectorText = selectorText
self._readonly = readonly
def __repr__(self):
if self._namespaces:
st = (self.selectorText, self._namespaces)
else:
st = self.selectorText
return f"cssutils.css.{self.__class__.__name__}(selectorText={st!r})"
def __str__(self):
return "<cssutils.css.%s object selectorText=%r _namespaces=%r at " "0x%x>" % (
self.__class__.__name__,
self.selectorText,
self._namespaces,
id(self),
)
def __setitem__(self, index, newSelector):
"""Overwrite ListSeq.__setitem__
Any duplicate Selectors are **not** removed.
"""
newSelector = self.__prepareset(newSelector)
if newSelector:
self.seq[index] = newSelector
def __prepareset(self, newSelector, namespaces=None):
"Used by appendSelector and __setitem__"
if not namespaces:
namespaces = {}
self._checkReadonly()
if not isinstance(newSelector, Selector):
newSelector = Selector((newSelector, namespaces), parent=self)
if newSelector.wellformed:
newSelector._parent = self # maybe set twice but must be!
return newSelector
def __getNamespaces(self):
"""Use children namespaces if not attached to a sheet, else the sheet's
ones.
"""
try:
return self.parentRule.parentStyleSheet.namespaces
except AttributeError:
namespaces = {}
for selector in self.seq:
namespaces.update(selector._namespaces)
return namespaces
def _getUsedUris(self):
"Used by CSSStyleSheet to check if @namespace rules are needed"
uris = set()
for s in self:
uris.update(s._getUsedUris())
return uris
_namespaces = property(
__getNamespaces,
doc="""If this SelectorList is
attached to a CSSStyleSheet the namespaces of that sheet are mirrored
here. While the SelectorList (or parentRule(s) are
not attached the namespaces of all children Selectors are used.""",
)
def append(self, newSelector):
"Same as :meth:`appendSelector`."
self.appendSelector(newSelector)
def appendSelector(self, newSelector):
"""
Append `newSelector` to this list (a string will be converted to a
:class:`~cssutils.css.Selector`).
:param newSelector:
comma-separated list of selectors (as a single string) or a tuple of
`(newSelector, dict-of-namespaces)`
:returns: New :class:`~cssutils.css.Selector` or ``None`` if
`newSelector` is not wellformed.
:exceptions:
- :exc:`~xml.dom.NamespaceErr`:
Raised if the specified selector uses an unknown namespace
prefix.
- :exc:`~xml.dom.SyntaxErr`:
Raised if the specified CSS string value has a syntax error
and is unparsable.
- :exc:`~xml.dom.NoModificationAllowedErr`:
Raised if this rule is readonly.
"""
self._checkReadonly()
# might be (selectorText, namespaces)
newSelector, namespaces = self._splitNamespacesOff(newSelector)
try:
# use parent's only if available
namespaces = self.parentRule.parentStyleSheet.namespaces
except AttributeError:
# use already present namespaces plus new given ones
_namespaces = self._namespaces
_namespaces.update(namespaces)
namespaces = _namespaces
newSelector = self.__prepareset(newSelector, namespaces)
if newSelector:
seq = self.seq[:]
del self.seq[:]
for s in seq:
if s.selectorText != newSelector.selectorText:
self.seq.append(s)
self.seq.append(newSelector)
return newSelector
def _getSelectorText(self):
"Return serialized format."
return cssutils.ser.do_css_SelectorList(self)
def _setSelectorText(self, selectorText):
"""
:param selectorText:
comma-separated list of selectors or a tuple of
(selectorText, dict-of-namespaces)
:exceptions:
- :exc:`~xml.dom.NamespaceErr`:
Raised if the specified selector uses an unknown namespace
prefix.
- :exc:`~xml.dom.SyntaxErr`:
Raised if the specified CSS string value has a syntax error
and is unparsable.
- :exc:`~xml.dom.NoModificationAllowedErr`:
Raised if this rule is readonly.
"""
self._checkReadonly()
# might be (selectorText, namespaces)
selectorText, namespaces = self._splitNamespacesOff(selectorText)
try:
# use parent's only if available
namespaces = self.parentRule.parentStyleSheet.namespaces
except AttributeError:
pass
wellformed = True
tokenizer = self._tokenize2(selectorText)
newseq = []
expected = True
while True:
# find all upto and including next ",", EOF or nothing
selectortokens = self._tokensupto2(tokenizer, listseponly=True)
if selectortokens:
if self._tokenvalue(selectortokens[-1]) == ',':
expected = selectortokens.pop()
else:
expected = None
selector = Selector((selectortokens, namespaces), parent=self)
if selector.wellformed:
newseq.append(selector)
else:
wellformed = False
self._log.error(
'SelectorList: Invalid Selector: %s'
% self._valuestr(selectortokens)
)
else:
break
# post condition
if ',' == expected:
wellformed = False
self._log.error(
'SelectorList: Cannot end with ",": %r' % self._valuestr(selectorText)
)
elif expected:
wellformed = False
self._log.error(
'SelectorList: Unknown Syntax: %r' % self._valuestr(selectorText)
)
if wellformed:
self.seq = newseq
selectorText = property(
_getSelectorText,
_setSelectorText,
doc="(cssutils) The textual representation of the " "selector for a rule set.",
)
length = property(
lambda self: len(self),
doc="The number of :class:`~cssutils.css.Selector` " "objects in the list.",
)
parentRule = property(
lambda self: self._parentRule,
doc="(DOM) The CSS rule that contains this "
"SelectorList or ``None`` if this SelectorList "
"is not attached to a CSSRule.",
)
wellformed = property(lambda self: bool(len(self.seq)))