Projet

Général

Profil

0001-assets-add-css-classes-related-to-assets-on-cells-41.patch

Lauréline Guérin, 24 avril 2020 14:43

Télécharger (8,78 ko)

Voir les différences:

Subject: [PATCH] assets: add css classes related to assets on cells (#41995)

 combo/apps/assets/templatetags/assets.py      |  8 +++-
 combo/data/models.py                          | 29 ++++++++++++
 combo/public/templates/combo/placeholder.html |  2 +-
 combo/public/views.py                         | 10 ++++
 tests/test_public.py                          | 46 ++++++++++++++++++-
 5 files changed, 91 insertions(+), 4 deletions(-)
combo/apps/assets/templatetags/assets.py
80 80

  
81 81
    key = None
82 82
    if 'cell' in kwargs and 'type' in kwargs:
83
        cell = kwargs['cell']
84
        cell_type = kwargs['type']
83 85
        try:
84
            if not kwargs['cell'].can_have_assets():
86
            if not cell.can_have_assets():
85 87
                return None
86
            key = kwargs['cell'].get_asset_slot_key(kwargs['type'])
88
            key = cell.get_asset_slot_key(cell_type)
87 89
        except AttributeError:
88 90
            return None
91
        if hasattr(cell, '_assets'):
92
            return cell._assets.get(key)
89 93
    elif len(args) == 1:
90 94
        key = args[0]
91 95

  
combo/data/models.py
621 621
    def css_class_names(self):
622 622
        return ' '.join([self.class_name, self.legacy_class_name, self.extra_css_class])
623 623

  
624
    @property
625
    def asset_css_classes(self):
626
        from combo.apps.assets.models import Asset
627

  
628
        if not hasattr(self, '_asset_keys'):
629
            self._asset_keys = self.get_asset_slot_keys()
630
        if not hasattr(self, '_assets'):
631
            self._assets = {a.key: a for a in Asset.objects.filter(key__in=self._asset_keys.keys())}
632

  
633
        if not self._asset_keys or not self._assets:
634
            return ''
635

  
636
        # add has-asset-<slug> for each asset found
637
        css = sorted(['has-asset-{}'.format(v) for k, v in self._asset_keys.items() if k in self._assets])
638
        # add has-any-asset if at least one asset defined
639
        if self._assets:
640
            css.append('has-any-asset')
641
        # add has-all-assets if all assets are defined
642
        if self._assets.keys() == self._asset_keys.keys():
643
            css.append('has-all-assets')
644

  
645
        return ' '.join(css)
646

  
624 647
    def can_have_assets(self):
625 648
        return self.get_slug_for_asset() and self.get_asset_slot_templates()
626 649

  
......
643 666
    def get_asset_slot_templates(self):
644 667
        return settings.COMBO_CELL_ASSET_SLOTS.get(self.get_cell_type_str()) or {}
645 668

  
669
    def get_asset_slot_keys(self):
670
        if not self.can_have_assets():
671
            return {}
672
        slot_templates = self.get_asset_slot_templates()
673
        return {self.get_asset_slot_key(key): key for key in slot_templates.keys()}
674

  
646 675
    def get_asset_slots(self):
647 676
        if not self.can_have_assets():
648 677
            return {}
combo/public/templates/combo/placeholder.html
4 4
{{ skeleton }}
5 5
{% endif %}
6 6
{% for cell in cells %}
7
<div class="cell {{ cell.css_class_names }} {% if cell.slug %}{{cell.slug}}{% endif %} {% if cell|shown_because_admin:request %}shown-because-admin{% endif %}"
7
<div class="cell {{ cell.css_class_names }} {{ cell.asset_css_classes }}{% if cell.slug %} {{cell.slug}}{% endif %}{% if cell|shown_because_admin:request %} shown-because-admin{% endif %}"
8 8
     {% if cell.slug and cell.use_slug_as_id %}id="{{ cell.slug }}"{% endif %}
9 9
     data-ajax-cell-url="{{ site_base }}{% url 'combo-public-ajax-page-cell' page_pk=cell.page_id cell_reference=cell.get_reference %}"
10 10
     data-ajax-cell-loading-message="{{ cell.loading_message }}"
combo/public/views.py
16 16

  
17 17
import json
18 18
import re
19
from itertools import chain
19 20

  
20 21
import django
21 22
from django.conf import settings
......
46 47
else:
47 48
    get_idps = lambda: []
48 49

  
50
from combo.apps.assets.models import Asset
49 51
from combo.data.models import (CellBase, PostException, Page, Redirect,
50 52
        ParentContentCell, TextCell, PageSnapshot)
51 53
from combo.profile.models import Profile
......
536 538
    cells = [x for x in cells if x.is_visible(user=request.user)]
537 539
    mark_duplicated_slugs(cells)
538 540

  
541
    # load assets
542
    for cell in cells:
543
        cell._asset_keys = cell.get_asset_slot_keys()
544
    asset_keys = list(set(chain(*[c._asset_keys.keys() for c in cells])))
545
    assets = list(Asset.objects.filter(key__in=asset_keys))
546
    for cell in cells:
547
        cell._assets = {a.key: a for a in assets if a.key in cell._asset_keys.keys()}
548

  
539 549
    ctx = {
540 550
        'check_badges': should_check_badges(),
541 551
        'page': page,
tests/test_public.py
9 9

  
10 10
from django.conf import settings
11 11
from django.contrib.auth.models import User, Group
12
from django.core.files import File
12 13
from django.urls import reverse
13 14
from django.db import connection
14 15
from django.utils.http import quote
15
from django.utils import six
16
from django.utils.six import StringIO
16 17
from django.utils.six.moves.urllib import parse as urlparse
17 18
from django.test import override_settings
18 19
from django.test.utils import CaptureQueriesContext
......
26 27
from combo.wsgi import application
27 28
from combo.data.models import (Page, CellBase, TextCell, ParentContentCell,
28 29
        FeedCell, LinkCell, LinkListCell, ConfigJsonCell, Redirect, JsonCell)
30
from combo.apps.assets.models import Asset
29 31
from combo.apps.family.models import FamilyInfosCell
30 32

  
31 33
pytestmark = pytest.mark.django_db
......
1008 1010
    assert urlparse.urlparse(app.get('/foo', status=301).location).path == '/foo/'
1009 1011
    # don't be tricked by double slashes
1010 1012
    assert urlparse.urlparse(app.get('//foo', status=301).location).path == '/foo/'
1013

  
1014

  
1015
def test_cell_asset_css_classes(settings, app, admin_user):
1016
    settings.COMBO_CELL_ASSET_SLOTS = {}
1017
    page = Page.objects.create(title='Home', slug='index', template_name='standard')
1018
    cell = TextCell.objects.create(page=page, placeholder='content', order=0, slug='foo', text='foo')
1019

  
1020
    # test direct access
1021
    assert cell.asset_css_classes == ''
1022
    # and test asset preload
1023
    resp = app.get('/', status=200)
1024
    assert 'class="cell text-cell textcell   foo"' in resp.text
1025

  
1026
    settings.COMBO_CELL_ASSET_SLOTS = {'data_textcell': {'picture': {'prefix': 'Picture'}}}
1027
    cell = TextCell.objects.get(pk=cell.pk)
1028
    assert cell.asset_css_classes == ''
1029
    resp = app.get('/', status=200)
1030
    assert 'class="cell text-cell textcell   foo"' in resp.text
1031

  
1032
    Asset.objects.create(key=cell.get_asset_slot_key('picture'), asset=File(StringIO('test'), 'test.png'))
1033
    cell = TextCell.objects.get(pk=cell.pk)
1034
    assert cell.asset_css_classes == 'has-asset-picture has-any-asset has-all-assets'
1035
    resp = app.get('/', status=200)
1036
    assert 'class="cell text-cell textcell  has-asset-picture has-any-asset has-all-assets foo"' in resp.text
1037

  
1038
    settings.COMBO_CELL_ASSET_SLOTS = {'data_textcell': {'picture': {'prefix': 'Picture'}, 'foo': {'prefix': 'Foo'}}}
1039
    cell = TextCell.objects.get(pk=cell.pk)
1040
    assert cell.asset_css_classes == 'has-asset-picture has-any-asset'
1041
    resp = app.get('/', status=200)
1042
    assert 'class="cell text-cell textcell  has-asset-picture has-any-asset foo"' in resp.text
1043

  
1044
    Asset.objects.create(key=cell.get_asset_slot_key('foo'), asset=File(StringIO('test'), 'test.png'))
1045
    cell = TextCell.objects.get(pk=cell.pk)
1046
    assert cell.asset_css_classes == 'has-asset-foo has-asset-picture has-any-asset has-all-assets'
1047
    resp = app.get('/', status=200)
1048
    assert 'class="cell text-cell textcell  has-asset-foo has-asset-picture has-any-asset has-all-assets foo"' in resp.text
1049

  
1050
    Asset.objects.all().delete()
1051
    cell = TextCell.objects.get(pk=cell.pk)
1052
    assert cell.asset_css_classes == ''
1053
    resp = app.get('/', status=200)
1054
    assert 'class="cell text-cell textcell   foo"' in resp.text
1011
-