Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve CSS query with getter and setter, keep order of css entries #101

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 33 additions & 36 deletions pyquery/pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import types
import sys

from collections import OrderedDict
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since Python 3.7: Dictionary order for all dicts is guaranteed to be insertion order.


PY3k = sys.version_info >= (3,)

Expand Down Expand Up @@ -883,44 +884,40 @@ def toggle_class(self, value):
tag.set('class', ' '.join(classes))
return self

def css(self, *args, **kwargs):
"""css attributes manipulation
"""

attr = value = no_default
length = len(args)
if length == 1:
attr = args[0]
elif length == 2:
attr, value = args
elif kwargs:
attr = kwargs
def css(self, propertyName, value=no_default):
"""css attributes manipulation"""
def clean_css(styles):
return OrderedDict((key.strip().replace('_', '-'), value.strip())
for key, value in styles.items())

if isinstance(propertyName, basestring):
getter = value is no_default
attrs = {propertyName: not getter and value or ''}
elif isinstance(propertyName, dict):
attrs = propertyName
getter = False
elif isinstance(propertyName, list):
attrs = OrderedDict((key, '') for key in propertyName)
getter = True
else:
raise ValueError('Invalid arguments %s %s' % (args, kwargs))
raise ValueError('Invalid arguments %s' % str(propertyName))
attrs = clean_css(attrs)

if isinstance(attr, dict):
for tag in self:
stripped_keys = [key.strip().replace('_', '-')
for key in attr.keys()]
current = [el.strip()
for el in (tag.get('style') or '').split(';')
if el.strip()
and not el.split(':')[0].strip() in stripped_keys]
for key, value in attr.items():
key = key.replace('_', '-')
current.append('%s: %s' % (key, value))
tag.set('style', '; '.join(current))
elif isinstance(value, basestring):
attr = attr.replace('_', '-')
for tag in self:
current = [
el.strip()
for el in (tag.get('style') or '').split(';')
if (el.strip() and
not el.split(':')[0].strip() == attr.strip())]
current.append('%s: %s' % (attr, value))
tag.set('style', '; '.join(current))
return self
for tag in self:
style = (tag.get('style') or '').split(';')
styles = OrderedDict(e.split(':', 1) for e in style if ':' in e)
styles = clean_css(styles)

if getter:
# The getter always returns for the first element in jquery
ret = [ styles.get(key, no_default) for key in attrs.keys() ]
return isinstance(propertyName, list) and ret or ''.join(ret[:1])

styles.update(attrs)
styles = [ ': '.join(e) for e in styles.items() if all(e) ]
tag.set('style', '; '.join(styles) + ';')
# Return's self on write (but not on read)
return self

css = FlexibleElement(pget=css, pset=css)

Expand Down
10 changes: 10 additions & 0 deletions tests/test_css.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<html>
<body>
<p class="hello" id="hello">Hello world !</p>

<p id="test">
hello <a href="http://python.org">python</a> !
</p>
<div id="css" style="color: red; border: 2px solid black;">CSS Too!</div>
</body>
</html>
37 changes: 37 additions & 0 deletions tests/test_pyquery.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def not_py3k(func):
dirname = os.path.dirname(os.path.abspath(__file__))
docs = os.path.join(os.path.dirname(dirname), 'docs')
path_to_html_file = os.path.join(dirname, 'test.html')
path_to_css_file = os.path.join(dirname, 'test_css.html')
path_to_invalid_file = os.path.join(dirname, 'invalid.xml')


Expand Down Expand Up @@ -265,6 +266,42 @@ def test_closest(self):
assert self.klass('.node3', self.html).closest('form') == []


class TestCss(TestCase):
def setUp(self):
self.doc = pq(filename=path_to_css_file)
self.tags = self.doc('#css')

def test_read_css(self):
self.assertEqual(self.tags.css('color'), 'red')

def test_read_list(self):
self.assertEqual(self.tags.css(['color']), ['red'])
self.assertEqual(self.tags.css(['color', 'border']),
['red', '2px solid black'])

def test_write_css_new(self):
self.tags.css('font-size', '4px')
self.assertEqual(self.tags[0].get('style'),
'color: red; border: 2px solid black; font-size: 4px;')

def test_remove_css(self):
self.tags.css('color', None)
self.assertEqual(self.tags[0].get('style'),
'border: 2px solid black;')

def test_write_css_old(self):
# Note, our jquery modifies the css in place rather than reordering.
self.tags.css('color', 'blue')
self.assertEqual(self.tags.css('color'), 'blue')
self.assertEqual(self.tags[0].get('style'),
'color: blue; border: 2px solid black;')

def test_write_dict(self):
self.tags.css({'color': 'green', 'font-size': '16px'})
self.assertEqual(self.tags[0].get('style'),
'color: green; border: 2px solid black; font-size: 16px;')


class TestOpener(TestCase):

def test_open_filename(self):
Expand Down