Minify custom css before rendering

This commit is contained in:
Gabriel Augendre 2021-01-03 21:46:41 +01:00
parent 2621796a6f
commit 4b224f0a1f
No known key found for this signature in database
GPG key ID: 1E693F4CE4AEE7B4
4 changed files with 55 additions and 3 deletions

View file

@ -1,7 +1,7 @@
import random import random
import re import re
import uuid import uuid
from functools import cached_property from functools import cached_property, reduce
import html2text import html2text
import markdown import markdown
@ -153,3 +153,15 @@ class Article(AdminUrlMixin, models.Model):
return list( return list(
filter(None, map(lambda k: k.strip().lower(), self.keywords.split(","))) filter(None, map(lambda k: k.strip().lower(), self.keywords.split(",")))
) )
@cached_property
def get_minified_custom_css(self):
def reducer(res, next_char):
if len(res) == 0:
return next_char
if res[-1] == next_char == " ":
return res
return res + next_char
css = self.custom_css.replace("\n", " ")
return reduce(reducer, css, "")

View file

@ -2,7 +2,7 @@
{% block append_header %} {% block append_header %}
<style> <style>
{{ article.custom_css }} {{ article.get_minified_custom_css }}
</style> </style>
{% endblock %} {% endblock %}

View file

@ -2,7 +2,7 @@
{% block append_header %} {% block append_header %}
<style> <style>
{{ article.custom_css }} {{ article.get_minified_custom_css }}
</style> </style>
<style> <style>
.pagination { .pagination {

View file

@ -39,3 +39,43 @@ def test_save_article_doesnt_change_existing_slug(published_article: Article):
published_article.title = "This is a brand new title" published_article.title = "This is a brand new title"
published_article.save() published_article.save()
assert published_article.slug == original_slug assert published_article.slug == original_slug
@pytest.mark.django_db
def test_empty_custom_css_minified(published_article):
published_article.custom_css = ""
assert published_article.get_minified_custom_css == ""
@pytest.mark.django_db
def test_simple_custom_css_minified(published_article):
published_article.custom_css = ".cls {\n background-color: red;\n}"
assert (
published_article.get_minified_custom_css == ".cls { background-color: red; }"
)
@pytest.mark.django_db
def test_larger_custom_css_minified(published_article):
published_article.custom_css = """\
.profile {
display: flex;
justify-content: space-evenly;
flex-wrap: wrap;
}
.profile img {
max-width: 200px;
min-width: 100px;
max-height: 200px;
min-height: 100px;
border-radius: 10%;
padding: 1rem;
flex-shrink: 1;
flex-grow: 0;
padding: 0;
}"""
assert (
published_article.get_minified_custom_css
== """.profile { display: flex; justify-content: space-evenly; flex-wrap: wrap; } .profile img { max-width: 200px; min-width: 100px; max-height: 200px; min-height: 100px; border-radius: 10%; padding: 1rem; flex-shrink: 1; flex-grow: 0; padding: 0; }"""
)