before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
soup = self.get_soup(rendered)
invalid_icons = soup.select("ol li:not(:last-child) svg use[href='#icon-site']")
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
class DarkLightModeTest(Admin... | We should have at least three tests.
1. Check a case where there is no theme set on the profile, it should show as our default of l'ight dark'. This one is needed.
2. Test to be updated, Profile has light, should show as 'light dark', you are only testing that one part of the string exists, which will pass even i... | soup = self.get_soup(rendered)
invalid_icons = soup.select("ol li:not(:last-child) svg use[href='#icon-site']")
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
class ThemeColorSchemeTest(Ad... | @@ -1068,3 +1068,54 @@ def test_icon_name(self):
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
+
+
+class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
+ fixtures = ["test.js... | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.5 | bug | 716 | 51 | 51 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | lb- | ashish-nagmoti |
soup = self.get_soup(rendered)
invalid_icons = soup.select("ol li:not(:last-child) svg use[href='#icon-site']")
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
class DarkLightModeTest(Admi... | I recommend we remove the breadcrumbs template tag usage, it's unrelated to this unit test.
```suggestion
``` |
soup = self.get_soup(rendered)
invalid_icons = soup.select("ol li:not(:last-child) svg use[href='#icon-site']")
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
class ThemeColorSchemeTest(A... | @@ -1068,3 +1068,54 @@ def test_icon_name(self):
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
+
+
+class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
+ fixtures = ["test.js... | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.786 | suggestion | 114 | 51 | 51 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | lb- | ashish-nagmoti |
self.profile.save()
template = """
{% load wagtailadmin_tags %}
<body class="{% admin_theme_color_scheme %}">
{% page_breadcrumbs page 'wagtailadmin_explore' %}
</body>
"""
page = Page.objects.get(id=1)
rendered = Template(temp... | ```suggestion
```
As above, no need to include the breadcrumbs template tag. | rendered = Template(template).render(Context({"request": self.request}))
soup = self.get_soup(rendered)
meta_tag = soup.find("meta", {"name": "color-scheme"})
self.assertIsNotNone(meta_tag)
self.assertEqual(meta_tag["content"], "dark light")
def test_dark_mode(self):
... | @@ -1068,3 +1068,54 @@ def test_icon_name(self):
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
+
+
+class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
+ fixtures = ["test.js... | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.571 | suggestion | 81 | 38 | 37 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | lb- | ashish-nagmoti |
Context({"page": page, "request": self.request})
)
self.assertBreadcrumbsItemsRendered(items, rendered)
soup = self.get_soup(rendered)
invalid_icons = soup.select("ol li:not(:last-child) svg use[href='#icon-site']")
self.assertEqual(len(invalid_icons), 0)
ico... | It doesn't make sense to use the value for the `class` attribute. Please refer to what the code is supposed to do, i.e. determining the value for the `<meta name="color-scheme"` tag, so the test should be written accordingly. | Context({"page": page, "request": self.request})
)
self.assertBreadcrumbsItemsRendered(items, rendered)
soup = self.get_soup(rendered)
invalid_icons = soup.select("ol li:not(:last-child) svg use[href='#icon-site']")
self.assertEqual(len(invalid_icons), 0)
ico... | @@ -1068,3 +1068,70 @@ def test_icon_name(self):
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
+
+
+class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
+ fixtures = ["test.js... | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.643 | suggestion | 225 | 51 | 51 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | laymonage | ashish-nagmoti |
user.wagtail_userprofile.theme
if hasattr(user, "wagtail_userprofile")
else "system"
)
contrast_name = (
user.wagtail_userprofile.contrast
if hasattr(user, "wagtail_userprofile")
else "system"
)
density_name = (
user.wagtail_userprofile.density
... | It's not correct to store the UserProfile object in a `theme_name` variable, because it's not the theme name.
```suggestion
profile = getattr(user, "wagtail_userprofile", None)
theme_name = profile.theme if profile else "system"
``` | user.wagtail_userprofile.theme
if hasattr(user, "wagtail_userprofile")
else "system"
)
contrast_name = (
user.wagtail_userprofile.contrast
if hasattr(user, "wagtail_userprofile")
else "system"
)
density_name = (
user.wagtail_userprofile.density
... | @@ -708,6 +708,21 @@ def admin_theme_classname(context):
return f"w-theme-{theme_name} w-density-{density_name} w-contrast-{contrast_name}"
+@register.simple_tag(takes_context=True)
+def admin_theme_color_scheme(context):
+ """
+ Retrieves the color-scheme of the active theme for current user.
+ """
+... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.857 | suggestion | 246 | 51 | 51 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | laymonage | ashish-nagmoti |
rendered = Template(template).render(
Context({"page": page, "request": self.request})
)
soup = self.get_soup(rendered)
meta_tag = soup.find("meta", {"name": "color-scheme"})
self.assertIsNotNone(meta_tag)
self.assertIn("dark", meta_tag["content"])
def t... | ```suggestion
self.assertEqual(meta_tag["content"], "light")
``` | import json
import os
import unittest
from datetime import datetime, timedelta
from datetime import timezone as dt_timezone
from unittest import mock
from django.conf import settings
from django.template import Context, Template, TemplateSyntaxError
from django.test import SimpleTestCase, TestCase
from django.test.uti... | @@ -1068,3 +1068,66 @@ def test_icon_name(self):
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
+
+
+class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
+ fixtures = ["test.js... | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.571 | suggestion | 74 | 27 | 1,121 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | laymonage | ashish-nagmoti |
Context({"page": page, "request": self.request})
)
soup = self.get_soup(rendered)
meta_tag = soup.find("meta", {"name": "color-scheme"})
self.assertIsNotNone(meta_tag)
self.assertIn("dark", meta_tag["content"])
self.assertIn("light", meta_tag["content"])
... | ```suggestion
self.assertEqual(meta_tag["content"], "dark")
``` | self.assertEqual(meta_tag["content"], "dark light")
def test_dark_mode(self):
self.profile.theme = "dark"
self.profile.save()
template = """
{% load wagtailadmin_tags %}
<meta name="color-scheme" content="{% admin_theme_color_scheme %}">
"""
... | @@ -1068,3 +1068,66 @@ def test_icon_name(self):
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
+
+
+class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
+ fixtures = ["test.js... | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.571 | suggestion | 73 | 45 | 32 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | laymonage | ashish-nagmoti |
class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
fixtures = ["test.json"]
def setUp(self):
self.request = get_dummy_request()
self.user = self.login()
self.request.user = self.user
self.profile, created = UserProfile.objects.get_or_create(user=self.... | ```suggestion
self.assertEqual(meta_tag["content"], "dark light")
``` |
class ThemeColorSchemeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
def setUp(self):
self.request = get_dummy_request()
self.user = self.login()
self.request.user = self.user
self.profile = UserProfile.get_for_user(self.user)
def test_default_mode(self):
tem... | @@ -1068,3 +1068,66 @@ def test_icon_name(self):
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
+
+
+class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
+ fixtures = ["test.js... | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.571 | suggestion | 79 | 51 | 50 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | laymonage | ashish-nagmoti |
self.assertIn("my-class", div["class"])
def test_icon_name(self):
template = """
{% load wagtailadmin_tags %}
{% page_breadcrumbs page 'wagtailadmin_explore' icon_name='site' %}
"""
page = Page.objects.get(id=3)
items = [
{"label": "Root",... | ```suggestion
class ThemeColorSchemeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
``` | self.assertIn("my-class", div["class"])
def test_icon_name(self):
template = """
{% load wagtailadmin_tags %}
{% page_breadcrumbs page 'wagtailadmin_explore' icon_name='site' %}
"""
page = Page.objects.get(id=3)
items = [
{"label": "Root",... | @@ -1068,3 +1068,66 @@ def test_icon_name(self):
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
+
+
+class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase): | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.571 | suggestion | 99 | 51 | 51 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | laymonage | ashish-nagmoti |
with self.assertNumQueries(13):
html = panel.render_html(parent_context)
soup = self.get_soup(html)
self.assertEqual(len(soup.select('svg use[href="#icon-lock"]')), 2)
expected_titles = [
"Some obj 2",
"Some obj 1",
"Saint Patrick (single... | ```suggestion
profile = UserProfile.get_for_user(self.superuser)
``` |
with self.assertNumQueries(13):
html = panel.render_html(parent_context)
soup = self.get_soup(html)
self.assertEqual(len(soup.select('svg use[href="#icon-lock"]')), 2)
expected_titles = [
"Some obj 2",
"Some obj 1",
"Saint Patrick (single... | @@ -402,3 +403,35 @@ def test_panel_query_count(self):
]
titles = [e.get_text(strip=True) for e in soup.select(".title-wrapper a")]
self.assertEqual(titles, expected_titles)
+
+
+class CommonAdminBaseTemplate(WagtailTestUtils, TestCase):
+ def setUp(self):
+ self.superuser = self.cr... | wagtail/admin/tests/test_dashboard.py | 26 | Python | 0.643 | suggestion | 78 | 49 | 41 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | laymonage | ashish-nagmoti |
]
titles = [e.get_text(strip=True) for e in soup.select(".title-wrapper a")]
self.assertEqual(titles, expected_titles)
class CommonAdminBaseTemplate(WagtailTestUtils, TestCase):
def setUp(self):
self.superuser = self.create_superuser(username="admin", password="password")
s... | It's self-explanatory
```suggestion
``` | ]
titles = [e.get_text(strip=True) for e in soup.select(".title-wrapper a")]
self.assertEqual(titles, expected_titles)
class CommonAdminBaseTemplate(WagtailTestUtils, TestCase):
def setUp(self):
self.user = self.login()
def test_common_admin_base_template(self):
respon... | @@ -402,3 +403,35 @@ def test_panel_query_count(self):
]
titles = [e.get_text(strip=True) for e in soup.select(".title-wrapper a")]
self.assertEqual(titles, expected_titles)
+
+
+class CommonAdminBaseTemplate(WagtailTestUtils, TestCase):
+ def setUp(self):
+ self.superuser = self.cr... | wagtail/admin/tests/test_dashboard.py | 26 | Python | 0.429 | suggestion | 43 | 36 | 28 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | laymonage | ashish-nagmoti |
soup = self.get_soup(rendered)
invalid_icons = soup.select("ol li:not(:last-child) svg use[href='#icon-site']")
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
class DarkLightModeTest(Admin... | We don't need the page
```suggestion
rendered = Template(template).render(
Context({"request": self.request})
)
``` | soup = self.get_soup(rendered)
invalid_icons = soup.select("ol li:not(:last-child) svg use[href='#icon-site']")
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
class ThemeColorSchemeTest(Ad... | @@ -1068,3 +1068,66 @@ def test_icon_name(self):
self.assertEqual(len(invalid_icons), 0)
icon = soup.select_one("ol li:last-child svg use[href='#icon-site']")
self.assertIsNotNone(icon)
+
+
+class DarkLightModeTest(AdminTemplateTestUtils, WagtailTestUtils, TestCase):
+ fixtures = ["test.js... | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.714 | suggestion | 150 | 51 | 51 | false | Solved : Add color-scheme meta tag to Wagtail admin and relevent tests | 12,958 | wagtail/wagtail | 16,097 | Python | laymonage | ashish-nagmoti |
Page.objects.get(pk=1)
def test_homepage_create(self):
root_page = Page.objects.get(pk=1)
self.homepage = HomePage(title='Home')
root_page.add_child(instance=self.homepage)
class HomeTests(TestCase):
"""
Class for testing homepage logic
"""
def setUp(self):
... | Line break needed at the end of the file, minor formatting but it just means the CI will not complain.
Best to run your code formatter for new PRs.
See https://docs.wagtail.org/en/stable/contributing/python_guidelines.html#pep8 | root_page = Page.objects.get(pk=1)
self.assertIsNotNone(root_page)
def test_homepage_create(self):
root_page = Page.objects.get(pk=1)
homepage = HomePage(title="Home")
root_page.add_child(instance=homepage)
self.assertTrue(HomePage.objects.filter(title="Home").exists... | @@ -0,0 +1,39 @@
+# home/tests.py
+
+from django.test import TestCase
+from wagtail.models import Page
+from home.models import HomePage
+
+
+class HomeSetUpTests(TestCase):
+ """
+ Tests steps needed by follow up tests
+ """
+
+ def test_root_create(self):
+ Page.objects.get(pk=1)
+
+ def test_ho... | wagtail/project_template/home/tests.py | 26 | Python | 0.429 | nitpick | 231 | 26 | 31 | false | #12953 Added Default Tests for Root and Homepage Pages in Wagtail Starter Projects | 12,967 | wagtail/wagtail | 16,097 | Python | lb- | megatrron |
# home/tests.py
from django.test import TestCase
from wagtail.models import Page
from home.models import HomePage
class HomeSetUpTests(TestCase):
"""
Tests steps needed by follow up tests
"""
def test_root_create(self):
Page.objects.get(pk=1)
def test_homepage_create(self):
root... | ```suggestion
```
Do we need this comment? it does not look like we do this in any other template files. | from django.urls import reverse
from home.models import HomePage
from wagtail.models import Page
from wagtail.test.utils import WagtailPageTestCase
class HomeSetUpTests(WagtailPageTestCase):
"""
Tests for basic page structure setup and HomePage creation.
"""
def test_root_create(self):
root_... | @@ -0,0 +1,39 @@
+# home/tests.py | wagtail/project_template/home/tests.py | 1 | Python | 0.714 | suggestion | 108 | 26 | 26 | false | #12953 Added Default Tests for Root and Homepage Pages in Wagtail Starter Projects | 12,967 | wagtail/wagtail | 16,097 | Python | lb- | megatrron |
# home/tests.py
from django.test import TestCase
from wagtail.models import Page
from home.models import HomePage
class HomeSetUpTests(TestCase):
"""
Tests steps needed by follow up tests
"""
def test_root_create(self):
Page.objects.get(pk=1)
def test_homepage_create(self):
root... | I think we should try to use our documented testing approach in https://docs.wagtail.org/en/stable/advanced_topics/testing.html
```suggestion
from wagtail.test.utils import WagtailPageTestCase
```
Also, have a review of that page for some other tips/practice we recommend in our docs. | from django.urls import reverse
from home.models import HomePage
from wagtail.models import Page
from wagtail.test.utils import WagtailPageTestCase
class HomeSetUpTests(WagtailPageTestCase):
"""
Tests for basic page structure setup and HomePage creation.
"""
def test_root_create(self):
root_... | @@ -0,0 +1,39 @@
+# home/tests.py
+
+from django.test import TestCase | wagtail/project_template/home/tests.py | 3 | Python | 0.857 | suggestion | 294 | 28 | 28 | false | #12953 Added Default Tests for Root and Homepage Pages in Wagtail Starter Projects | 12,967 | wagtail/wagtail | 16,097 | Python | lb- | megatrron |
# home/tests.py
from django.test import TestCase
from wagtail.models import Page
from home.models import HomePage
class HomeSetUpTests(TestCase):
"""
Tests steps needed by follow up tests
"""
def test_root_create(self):
Page.objects.get(pk=1)
def test_homepage_create(self):
root... | What is this actually testing?
Do we need some assertions here?
Same for the test above. | from django.urls import reverse
from home.models import HomePage
from wagtail.models import Page
from wagtail.test.utils import WagtailPageTestCase
class HomeSetUpTests(WagtailPageTestCase):
"""
Tests for basic page structure setup and HomePage creation.
"""
def test_root_create(self):
root_... | @@ -0,0 +1,39 @@
+# home/tests.py
+
+from django.test import TestCase
+from wagtail.models import Page
+from home.models import HomePage
+
+
+class HomeSetUpTests(TestCase):
+ """
+ Tests steps needed by follow up tests
+ """
+
+ def test_root_create(self):
+ Page.objects.get(pk=1)
+
+ def test_ho... | wagtail/project_template/home/tests.py | 19 | Python | 0.214 | question | 94 | 39 | 44 | false | #12953 Added Default Tests for Root and Homepage Pages in Wagtail Starter Projects | 12,967 | wagtail/wagtail | 16,097 | Python | lb- | megatrron |
def test_root_create(self):
root_page = Page.objects.get(pk=1)
self.assertIsNotNone(root_page)
def test_homepage_create(self):
root_page = Page.objects.get(pk=1)
homepage = HomePage(title="Home")
root_page.add_child(instance=homepage)
self.assertTrue(HomePage.o... | Note, AI suggestion, but maybe we should do something else here to actually have a basic starting set of tests.
```suggestion
def test_homepage_status_code(self):
response = self.client.get(reverse('home'))
self.assertEqual(response.status_code, 200)
def test_homepage_template_used(self... | """
Tests for basic page structure setup and HomePage creation.
"""
def test_root_create(self):
root_page = Page.objects.get(pk=1)
self.assertIsNotNone(root_page)
def test_homepage_create(self):
root_page = Page.objects.get(pk=1)
homepage = HomePage(title="Home")
... | @@ -0,0 +1,40 @@
+from wagtail.test.utils import WagtailPageTestCase
+from wagtail.models import Page
+from home.models import HomePage
+
+class HomeSetUpTests(WagtailPageTestCase):
+ """
+ Tests steps needed by follow up tests
+ """
+
+ def test_root_create(self):
+ root_page = Page.objects.get(pk=1... | wagtail/project_template/home/tests.py | 26 | Python | 0.857 | suggestion | 522 | 32 | 36 | false | #12953 Added Default Tests for Root and Homepage Pages in Wagtail Starter Projects | 12,967 | wagtail/wagtail | 16,097 | Python | lb- | megatrron |
root_page = Page.objects.get(pk=1)
homepage = HomePage(title="Home")
root_page.add_child(instance=homepage)
self.assertTrue(HomePage.objects.filter(title="Home").exists())
class HomeTests(WagtailPageTestCase):
"""
Class for testing homepage logic
"""
def setUp(self):
... | I think we should choose to start with a set of tests that pass. It's possible it could cause confusion if the tutorial starting point does not pass.
I would recommend we actually remove this 'placeholder' test and just add a few more starting tests. | self.assertIsNotNone(root_page)
def test_homepage_create(self):
root_page = Page.objects.get(pk=1)
homepage = HomePage(title="Home")
root_page.add_child(instance=homepage)
self.assertTrue(HomePage.objects.filter(title="Home").exists())
class HomeTests(WagtailPageTestCase):... | @@ -0,0 +1,40 @@
+from wagtail.test.utils import WagtailPageTestCase
+from wagtail.models import Page
+from home.models import HomePage
+
+class HomeSetUpTests(WagtailPageTestCase):
+ """
+ Tests steps needed by follow up tests
+ """
+
+ def test_root_create(self):
+ root_page = Page.objects.get(pk=1... | wagtail/project_template/home/tests.py | 26 | Python | 0.5 | refactor | 253 | 26 | 30 | false | #12953 Added Default Tests for Root and Homepage Pages in Wagtail Starter Projects | 12,967 | wagtail/wagtail | 16,097 | Python | lb- | megatrron |
}
),
sidebar_data,
)
def test_keyboard_shortcuts_dialog(self):
response = self.client.get(reverse("wagtailadmin_home"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(
response, "wagtailadmin/shared/keyboard_s... | I understand what you are doing here, but we have an existing approach to mocking when comments are enabled or not.
Instead of mocking the function, let's mock the root setting. Django has a great way to do this
```
from django.test import override_settings
# ...
@override_settings(WAGTAILADMIN_COMMENTS_ENAB... | """
self.client.defaults["HTTP_USER_AGENT"] = (
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"
)
response = self.client.get(reverse("wagtailadmin_home"))
key_labels = get_keyboard... | @@ -54,6 +55,34 @@ def test_keyboard_shortcuts_dialog(self):
)
self.assertIn("Keyboard shortcut", shortcuts_dialog.find("thead").prettify())
+ @patch("wagtail.admin.templatetags.wagtailadmin_tags.get_comments_enabled") | wagtail/admin/tests/test_keyboard_shortcuts.py | 26 | Python | 0.857 | refactor | 829 | 51 | 51 | false | Updated keyboard shortcut for comments | 12,968 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
self.client = Client(
headers={
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36"
}
)
self.login()
def test_mac_useragent_and_behavior(self):
response = self.c... | Similar here, split these to two tests and use the settings override approach instead. | )
def test_keyboard_shortcuts_dialog(self):
response = self.client.get(reverse("wagtailadmin_home"))
self.assertEqual(response.status_code, 200)
self.assertTemplateUsed(
response, "wagtailadmin/shared/keyboard_shortcuts_dialog.html"
)
soup = self.get_so... | @@ -82,3 +111,31 @@ def test_mac_useragent_and_behavior(self):
for shortcut in all_shortcuts:
# All shortcuts should have the ⌘ symbol
self.assertIn("⌘", shortcut.prettify())
+
+ @patch("wagtail.admin.templatetags.wagtailadmin_tags.get_comments_enabled") | wagtail/admin/tests/test_keyboard_shortcuts.py | 26 | Python | 0.286 | suggestion | 86 | 51 | 51 | false | Updated keyboard shortcut for comments | 12,968 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
"""
Given a URL and a dictionary of query parameters,
returns a new URL with those query parameters added or updated.
If the value of a query parameter is None, that parameter will be removed from the URL.
"""
scheme, netloc, path, query, fragment = urlsplit(url)
querydict = parse_qs(query... | Let's add a unit test for this stand alone utility.
I know it's being tested indirectly via the template tag tests but pulling this out means we need to support a basic suite of tests on its own.
Maybe add this just at the **start** of the file `wagtail/admin/tests/test_keyboard_shortcuts.py`. This way, we can ensu... |
try:
return user.get_username()
except AttributeError:
# we were passed None or something else that isn't a valid user object; return
# empty string to replicate the behaviour of {{ user.get_full_name|default:user.get_username }}
return ""
def set_query_params(url: str, params... | @@ -70,3 +72,29 @@ def set_query_params(url: str, params: dict):
querydict = {key: value for key, value in querydict.items() if value is not None}
query = urlencode(querydict, doseq=True)
return urlunsplit((scheme, netloc, path, query, fragment))
+
+
+def get_keyboard_key_labels_from_request(request): | wagtail/admin/utils.py | 26 | Python | 1 | bug | 2,073 | 40 | 51 | false | Updated keyboard shortcut for comments | 12,968 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
def get_keyboard_key_labels_from_request(request):
"""
Returns an instance of SimpleNamespace based on the user's keyboard layout
based on the User-Agent header in the request.
These are intentionally not translated, as they are key labels that are assumed
to be consistent across all languages.
... | Can we please also add a 'mod' (modifier) name here, this is commonly used by libraries such as mousetrap (JS) to refer to the CMD or Ctrl differences.
Then, can we replace the usage in the template tag with `.MOD`.
We can still have two variations in the output, but that way the overall differences in the templa... | If the value of a query parameter is None, that parameter will be removed from the URL.
"""
scheme, netloc, path, query, fragment = urlsplit(url)
querydict = parse_qs(query)
querydict.update(params)
querydict = {key: value for key, value in querydict.items() if value is not None}
query = ur... | @@ -70,3 +72,29 @@ def set_query_params(url: str, params: dict):
querydict = {key: value for key, value in querydict.items() if value is not None}
query = urlencode(querydict, doseq=True)
return urlunsplit((scheme, netloc, path, query, fragment))
+
+
+def get_keyboard_key_labels_from_request(request):
+ ... | wagtail/admin/utils.py | 26 | Python | 0.857 | suggestion | 565 | 26 | 37 | false | Updated keyboard shortcut for comments | 12,968 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
comments_enabled = get_comments_enabled()
return {
"shortcuts": {
("actions-common", _("Common actions")): [
(_("Copy"), f"{KEYS.MOD} + c"),
(_("Cut"), f"{KEYS.MOD} + x"),
(_("Paste"), f"{KEYS.MOD} + v"),
(
... | ```suggestion
_("Add or show comments"),
```
Sorry I did not pick up on this early, the wording should reflect the action.
Note: There is still a bug, unrelated to your PR here https://github.com/wagtail/wagtail/issues/11021
You may be up for looking at that bug next and the older PR (see... | KEYS = get_keyboard_key_labels_from_request(context["request"])
return {
"shortcuts": {
("actions-common", _("Common actions")): [
(_("Copy"), f"{KEYS.MOD} + c"),
(_("Cut"), f"{KEYS.MOD} + x"),
(_("Paste"), f"{KEYS.MOD} + v"),
... | @@ -1382,41 +1383,51 @@ def keyboard_shortcuts_dialog(context):
user_agent = context["request"].headers.get("User-Agent", "")
is_mac = re.search(r"Mac|iPod|iPhone|iPad", user_agent)
- modifier = "⌘" if is_mac else "Ctrl"
+ KEYS = get_keyboard_key_labels_from_request(context["request"])
+
+ comments... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 1 | bug | 357 | 51 | 51 | false | Updated keyboard shortcut for comments | 12,968 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
comments_enabled = get_comments_enabled()
return {
"shortcuts": {
("actions-common", _("Common actions")): [
(_("Copy"), f"{KEYS.MOD} + c"),
(_("Cut"), f"{KEYS.MOD} + x"),
(_("Paste"), f"{KEYS.MOD} + v"),
(
... | ```suggestion
f"{KEYS.CTRL} + {KEYS.ALT} + m",
```
Sorry, this probably got lost in the refactor, it should be ctrl + alt (or ctrl + opt on mac).
https://github.com/wagtail/wagtail/blob/5c30b4211a36cab32727e3a155f70464295e446a/client/src/entrypoints/admin/comments.js#L16-L18 |
return {
"shortcuts": {
("actions-common", _("Common actions")): [
(_("Copy"), f"{KEYS.MOD} + c"),
(_("Cut"), f"{KEYS.MOD} + x"),
(_("Paste"), f"{KEYS.MOD} + v"),
(
_("Paste and match style")
... | @@ -1382,41 +1383,51 @@ def keyboard_shortcuts_dialog(context):
user_agent = context["request"].headers.get("User-Agent", "")
is_mac = re.search(r"Mac|iPod|iPhone|iPad", user_agent)
- modifier = "⌘" if is_mac else "Ctrl"
+ KEYS = get_keyboard_key_labels_from_request(context["request"])
+
+ comments... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.857 | refactor | 303 | 51 | 51 | false | Updated keyboard shortcut for comments | 12,968 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from wagtail.models import Collection
from wagtail.models.media import CollectionViewRestriction
class TestCollectionTreeOperations(TestCase):
def setUp(self):
self.root_collection = Collection... | OK, we should be putting these tests in the view tests. see `wagtail/admin/tests/test_collections_views.py`.
When you look at other Wagtail view tests, we have a lot of helper classes to avoid the boilerplate of creating admin users etc.
I have just moved the tests over and here's what it could look like.
```... | from django.test import TestCase
from wagtail.models import Collection
class TestCollectionTreeOperations(TestCase):
def setUp(self):
self.root_collection = Collection.get_first_root_node()
self.holiday_photos_collection = self.root_collection.add_child(
name="Holiday photos"
... | @@ -1,6 +1,9 @@
+from django.contrib.auth import get_user_model
from django.test import TestCase
+from django.urls import reverse
from wagtail.models import Collection
+from wagtail.models.media import CollectionViewRestriction
| wagtail/tests/test_collection_model.py | 5 | Python | 1 | refactor | 2,892 | 30 | 30 | false | fix privacy collection status label being incorrect | 12,974 | wagtail/wagtail | 16,097 | Python | lb- | smark-1 |
).get_latest_revision_as_object()
def get_form(self, query_dict):
form_class = self.object.get_edit_handler().get_form_class()
parent_page = self.object.get_parent().specific
if not query_dict:
# Query dict is empty, return null form
return form_class(
... | I thought it'd be nice to allow these to be blank so that the preview can be displayed immediately when creating a page (if no other validation errors prevent it).
I used uuid just to ensure uniqueness. We can also use something else such as the `session_key`, but it's less robust because if for some reason there's ... | def get_object(self):
return get_object_or_404(
Page, id=self.kwargs["page_id"]
).get_latest_revision_as_object()
def get_form(self, query_dict):
form_class = self.object.get_edit_handler().get_form_class()
parent_page = self.object.get_parent().specific
if ... | @@ -43,6 +46,16 @@ def get_form(self, query_dict):
for_user=self.request.user,
)
+ query_dict = query_dict.copy()
+
+ if not query_dict.get("title"):
+ query_dict["title"] = gettext("Placeholder title")
+
+ # Generate a random slug if one is not provided, ... | wagtail/admin/views/pages/preview.py | 26 | Python | 0.786 | bug | 556 | 51 | 51 | false | Defer validation of required text fields in previews | 12,982 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
def defer_required_fields(self):
if self.deferred_required_fields:
# defer_required_fields has already been called
return
for field_name in self._meta.defer_required_on_fields:
try:
if self.fields[field_name].required:
self.fie... | Do we need to check for `and name not in self.deferred_formset_min_nums` as well, in case `defer_required_fields` has been called?
Without it, if `defer_required_on_fields` is empty, and the form has formsets with `min_num`, calling `defer_required_fields` multiple times might result in `deferred_formset_min_nums[na... | ):
def __init__(self, *args, **kwargs):
# keep hold of the `for_user` kwarg as well as passing it on to PermissionedForm
self.for_user = kwargs.get("for_user")
self.deferred_required_fields = []
self.deferred_formset_min_nums = {}
super().__init__(*args, **kwargs)
def de... | @@ -142,14 +143,20 @@ def defer_required_fields(self):
except KeyError:
pass
- for formset in self.formsets.values():
+ for name, formset in self.formsets.items():
for form in formset:
form.defer_required_fields()
+ if formset.min_nu... | wagtail/admin/forms/models.py | 26 | Python | 0.643 | question | 365 | 51 | 51 | false | Defer validation on inline panels when saving drafts | 12,984 | wagtail/wagtail | 16,097 | Python | laymonage | gasman |
#!/usr/bin/env python
from wagtail import __version__
from wagtail.utils.setup import assets, check_bdist_egg, sdist
try:
from setuptools import find_packages, setup
except ImportError:
from distutils.core import setup
# Hack to prevent "TypeError: 'NoneType' object is not callable" error
# in multiprocessi... | Looking at this again, since Python 3 this should simply be
```suggestion
super().run()
````
I've made the change locally and did e2e testing again, and it still works well. Will push the change as I merge | import subprocess
from setuptools import setup
from setuptools.command.sdist import sdist as base_sdist
class sdist(base_sdist):
def compile_assets(self):
try:
subprocess.check_call(["npm", "run", "build"])
except (OSError, subprocess.CalledProcessError) as e:
print("Error... | @@ -1,135 +1,23 @@
-#!/usr/bin/env python
+import subprocess
-from wagtail import __version__
-from wagtail.utils.setup import assets, check_bdist_egg, sdist
+from setuptools import setup
+from setuptools.command.sdist import sdist as base_sdist
-try:
- from setuptools import find_packages, setup
-except ImportE... | setup.py | 17 | Python | 0.857 | suggestion | 221 | 42 | 24 | false | Migrate setup.cfg and setup.py to pyproject.toml | 12,993 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
response.
"""
return None
def dispatch(self, *args, **kwargs):
hooks_result = self.run_before_hook()
if hooks_result is not None:
return hooks_result
return super().dispatch(*args, **kwargs)
def form_valid(self, form):
response = super().for... | This is probably too much, so feel free to remove | response.
"""
return None
def dispatch(self, *args, **kwargs):
hooks_result = self.run_before_hook()
if hooks_result is not None:
return hooks_result
return super().dispatch(*args, **kwargs)
def form_valid(self, form):
response = super().for... | @@ -107,8 +108,10 @@ def form_valid(self, form):
class LocaleMixin:
@cached_property
def i18n_enabled(self) -> bool:
- return getattr(settings, "WAGTAIL_I18N_ENABLED", False) and issubclass(
- self.model, TranslatableMixin
+ return (
+ (model := getattr(self, "model", None... | wagtail/admin/views/generic/mixins.py | 26 | Python | 0.143 | suggestion | 49 | 51 | 51 | false | Improve locale filter in all choosers | 13,043 | wagtail/wagtail | 16,097 | Python | zerolab | zerolab |
if self.construct_queryset_hook_name:
# allow hooks to modify the queryset
for hook in hooks.get_hooks(self.construct_queryset_hook_name):
objects = hook(objects, self.request)
if self.filter_form.is_valid():
objects = self.filter_form.filter(objects... | Not sure if we've ever had ordering working in choosers before (it needs the link to be AJAX-ified). If not, then we need to disable it
```suggestion
return [self.title_column, LocaleColumn(sort_key=None)]
``` | if filters:
objects = objects.filter(**filters)
if self.construct_queryset_hook_name:
# allow hooks to modify the queryset
for hook in hooks.get_hooks(self.construct_queryset_hook_name):
objects = hook(objects, self.request)
if self.filter_fo... | @@ -208,7 +213,9 @@ def is_multiple_choice(self):
return self.request.GET.get("multiple")
@property
- def columns(self):
+ def columns(self) -> list[Column]:
+ if self.i18n_enabled:
+ return [self.title_column, LocaleColumn()] | wagtail/admin/views/generic/chooser.py | 26 | Python | 0.786 | suggestion | 226 | 51 | 51 | false | Improve locale filter in all choosers | 13,043 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
"""
Provides common functionality for views that present a (possibly searchable / filterable) list
of objects to choose from
"""
per_page = 10
ordering = None
chosen_url_name = None
chosen_multiple_url_name = None
results_url_name = None
icon = "snippet"
page_title = _("Choo... | The original code had the `issubclass` check inside an `if self.model_class`. There's a possibility that the `model_class` is `None` so we have to check that too | """
Provides common functionality for views that present a (possibly searchable / filterable) list
of objects to choose from
"""
per_page = 10
ordering = None
chosen_url_name = None
chosen_multiple_url_name = None
results_url_name = None
icon = "snippet"
page_title = _("Choo... | @@ -134,6 +134,12 @@ class BaseChooseView(
url_filter_parameters = []
paginator_class = WagtailPaginator
+ @cached_property
+ def i18n_enabled(self) -> bool:
+ return getattr(settings, "WAGTAIL_I18N_ENABLED", False) and issubclass(
+ self.model_class, TranslatableMixin
+ ) | wagtail/admin/views/generic/chooser.py | 26 | Python | 0.5 | suggestion | 161 | 51 | 51 | false | Improve locale filter in all choosers | 13,043 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
{
"modalUrl": "/admin/animated_advert_chooser/",
"linkedFields": {"url": "#id_cool_url"},
},
)
@override_settings(WAGTAIL_I18N_ENABLED=True)
def test_filter_by_locale(self):
fr_locale = Locale.objects.create(language_code="fr")
Tr... | I don't think it's common for us to inspect the view's internals like this. For better or worse, we usually parse the HTML instead | {
"modalUrl": "/admin/animated_advert_chooser/",
"linkedFields": {"url": "#id_cool_url"},
},
)
@override_settings(WAGTAIL_I18N_ENABLED=True)
def test_filter_by_locale(self):
fr_locale = Locale.objects.create(language_code="fr")
Tr... | @@ -54,3 +59,27 @@ def test_adapt_widget_with_linked_fields(self):
"linkedFields": {"url": "#id_cool_url"},
},
)
+
+ @override_settings(WAGTAIL_I18N_ENABLED=True)
+ def test_filter_by_locale(self):
+ fr_locale = Locale.objects.create(language_code="fr")
+
+ Tra... | wagtail/admin/tests/viewsets/test_chooser_viewset.py | 26 | Python | 0.429 | suggestion | 130 | 30 | 35 | false | Improve locale filter in all choosers | 13,043 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
choices=AdminContrastThemes.choices,
default=AdminContrastThemes.SYSTEM,
max_length=40,
)
class AdminDensityThemes(models.TextChoices):
DEFAULT = "default", _("Default")
SNUG = "snug", _("Snug")
density = models.CharField(
# Translators: "Density" is the ter... | suggestion:
```suggestion
if (language := get_language()) in get_available_admin_languages():
return language
``` | choices=AdminContrastThemes.choices,
default=AdminContrastThemes.SYSTEM,
max_length=40,
)
class AdminDensityThemes(models.TextChoices):
DEFAULT = "default", _("Default")
SNUG = "snug", _("Snug")
density = models.CharField(
# Translators: "Density" is the ter... | @@ -112,7 +114,11 @@ def get_for_user(cls, user):
return cls.objects.get_or_create(user=user)[0]
def get_preferred_language(self):
- return self.preferred_language or get_language()
+ if self.preferred_language:
+ return self.preferred_language
+ if get_language() in get_... | wagtail/users/models.py | 26 | Python | 0.714 | suggestion | 139 | 38 | 38 | false | Fix default preferred language should be an admin permitted language | 13,047 | wagtail/wagtail | 16,097 | Python | zerolab | SebCorbin |
construct_wagtail_userbar,
),
):
response = self.page.serve(self.request)
response.render()
self.assertTrue(kwargs.get("called"))
@override_settings(
WAGTAIL_I18N_ENABLED=True,
WAGTAIL_CONTENT_LANGUAGES=[("en", "English"), ("f... | thought: it would be good to test the other 2 test cases:
1. the user's preferred language
2. the active laguage is in the available admin languages | hooks.register_temporarily(
"construct_wagtail_userbar",
construct_wagtail_userbar,
),
):
response = self.page.serve(self.request)
response.render()
self.assertTrue(kwargs.get("called"))
@override_settings(
... | @@ -495,6 +496,23 @@ def construct_wagtail_userbar(request, items):
self.assertTrue(kwargs.get("called"))
+ @override_settings(
+ WAGTAIL_I18N_ENABLED=True,
+ WAGTAIL_CONTENT_LANGUAGES=[("en", "English"), ("fr", "French")],
+ WAGTAILADMIN_PERMITTED_LANGUAGES=[("en", "English")],... | wagtail/admin/tests/test_userbar.py | 26 | Python | 0.429 | suggestion | 150 | 51 | 51 | false | Fix default preferred language should be an admin permitted language | 13,047 | wagtail/wagtail | 16,097 | Python | zerolab | SebCorbin |
french = Locale.objects.create(language_code="fr")
self.homepage.copy_for_translation(french)
french_page = self.page.copy_for_translation(french)
with translation.override("fr"):
response = french_page.serve(self.request)
response.render()
self.assertCo... | note (non-blocking): I like this and I wish you could make it more explicit. Other than `self.assertNotEqual(expected_text, "Go to Wagtail admin")` I can't think of a nice way to do this. | french = Locale.objects.create(language_code="fr")
self.homepage.copy_for_translation(french)
french_page = self.page.copy_for_translation(french)
with translation.override("fr"):
response = french_page.serve(self.request)
response.render()
self.assertCo... | @@ -495,6 +498,54 @@ def construct_wagtail_userbar(request, items):
self.assertTrue(kwargs.get("called"))
+ @override_settings(
+ WAGTAIL_I18N_ENABLED=True,
+ WAGTAIL_CONTENT_LANGUAGES=[("en", "English"), ("fr", "French")],
+ WAGTAILADMIN_PERMITTED_LANGUAGES=[("en", "English")],... | wagtail/admin/tests/test_userbar.py | 26 | Python | 0.571 | suggestion | 187 | 51 | 51 | false | Fix default preferred language should be an admin permitted language | 13,047 | wagtail/wagtail | 16,097 | Python | zerolab | SebCorbin |
from functools import lru_cache
from django.http import Http404
from django.shortcuts import get_object_or_404, redirect
from django.urls import reverse
from django.utils.text import capfirst
from django.utils.translation import gettext as _
from django.utils.translation import gettext_lazy
from wagtail.admin import ... | I think we'd want to have the `ChecksSidePanel` as well whenever we have the `PreviewSidePanel` to ensure that we have accessibility checks
```diff
diff --git a/wagtail/contrib/settings/tests/generic/test_preview.py b/wagtail/contrib/settings/tests/generic/test_preview.py
index dc6c97d555..88ebf775ce 100644
--- a... | context["site_switcher"] = site_switcher
context["site_for_header"] = site_for_header
return context
def get_success_url(self):
return self.get_edit_url()
def get_success_message(self):
return capfirst(
_("%(setting_type)s updated.")
% {"setting_... | @@ -138,3 +141,35 @@ def get_success_message(self):
_("%(setting_type)s updated.")
% {"setting_type": self.model._meta.verbose_name}
)
+
+ def get_preview_url(self):
+ if isinstance(self.object, PreviewableMixin) and self.object.is_previewable():
+ return reverse(... | wagtail/contrib/settings/views.py | 26 | Python | 0.857 | refactor | 2,070 | 176 | 51 | false | PreviewableMixin compatibility for settings | 13,050 | wagtail/wagtail | 16,097 | Python | laymonage | SebCorbin |
# Check the JSON response
self.assertEqual(response.status_code, 200)
self.assertJSONEqual(
response.content.decode(),
{"is_valid": True, "is_available": True},
)
# Send an invalid update request
response = self.client.post(self.preview_on_edit_u... | Now that you added elements with ids, I wonder how Beautifulsoup fares in terms of performance compared to `assertContains`/`assertNotContains`/ | response = self.client.post(self.preview_on_edit_url, self.post_data)
# Check the JSON response
self.assertEqual(response.status_code, 200)
self.assertJSONEqual(
response.content.decode(),
{"is_valid": True, "is_available": True},
)
# Send an inv... | @@ -0,0 +1,191 @@
+from django.test import TestCase
+from django.urls import reverse
+
+from wagtail.admin.staticfiles import versioned_static
+from wagtail.models import Site
+from wagtail.test.testapp.models import (
+ PreviewableGenericSetting,
+ PreviewableSiteSetting,
+)
+from wagtail.test.utils import Wagta... | wagtail/contrib/settings/tests/shared/test_preview.py | 26 | Python | 0.643 | performance | 144 | 51 | 51 | false | PreviewableMixin compatibility for settings | 13,050 | wagtail/wagtail | 16,097 | Python | SebCorbin | SebCorbin |
sort_key="language_code",
url_name="wagtaillocales:edit",
),
LocaleUsageColumn("usage", label=gettext_lazy("Usage")),
]
def get_add_url(self) -> Optional[str]:
# Removes the "Add" button from the index view.
if self.queryset.count() >= len(
ge... | If there are stale `Locale` records that are not in `WAGTAIL_CONTENT_LANGUAGES`, would this be a problem? | default_ordering = "language_code"
columns = [
LanguageTitleColumn(
"language",
label=gettext_lazy("Language"),
sort_key="language_code",
url_name="wagtaillocales:edit",
),
LocaleUsageColumn("usage", label=gettext_lazy("Usage")),
]
... | @@ -42,14 +53,33 @@ class IndexView(generic.IndexView):
sort_key="language_code",
url_name="wagtaillocales:edit",
),
- UsageColumn("usage", label=gettext_lazy("Usage")),
+ LocaleUsageColumn("usage", label=gettext_lazy("Usage")),
]
+ def get_add_url(self) -> Opt... | wagtail/locales/views.py | 26 | Python | 0.5 | question | 105 | 51 | 51 | false | Hide add locale button when no more languages are available | 13,051 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
from wagtail.models import Locale
from wagtail.permissions import locale_permission_policy
from .forms import LocaleForm
from .utils import get_locale_usage
if TYPE_CHECKING:
from django.http import HttpRequest, HttpResponseBase
class LanguageTitleColumn(TitleColumn):
cell_template_name = "wagtaillocales/_l... | Missing `.count()`:
```suggestion
return Locale.objects.filter(language_code__in=defined_locales).count() < len(
defined_locales
)
``` | from wagtail.models import Locale
from wagtail.permissions import locale_permission_policy
from .forms import LocaleForm
from .utils import get_locale_usage
if TYPE_CHECKING:
from django.http import HttpRequest, HttpResponseBase
class LanguageTitleColumn(TitleColumn):
cell_template_name = "wagtaillocales/_l... | @@ -18,14 +25,29 @@ def get_value(self, locale):
return locale
-class UsageColumn(Column):
+def _can_add_locale() -> bool:
+ defined_locales = [
+ language[0]
+ # WAGTAIL_CONTENT_LANGUAGES is a list of tuples (language_code, language)
+ for language in getattr(settings, "WAGTAIL_CON... | wagtail/locales/views.py | 26 | Python | 0.714 | suggestion | 157 | 51 | 51 | false | Hide add locale button when no more languages are available | 13,051 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
from wagtail.admin.ui.tables import Column, TitleColumn
from wagtail.admin.views import generic
from wagtail.admin.viewsets.model import ModelViewSet
from wagtail.models import Locale
from wagtail.permissions import locale_permission_policy
from .forms import LocaleForm
from .utils import get_locale_usage
if TYPE_CHE... | I think we can use `get_content_languages().keys()` no? | from wagtail.admin.views import generic
from wagtail.admin.viewsets.model import ModelViewSet
from wagtail.coreutils import get_content_languages
from wagtail.models import Locale
from wagtail.permissions import locale_permission_policy
from .forms import LocaleForm
from .utils import get_locale_usage
if TYPE_CHECKIN... | @@ -18,14 +25,29 @@ def get_value(self, locale):
return locale
-class UsageColumn(Column):
+def _can_add_locale() -> bool:
+ defined_locales = [
+ language[0]
+ # WAGTAIL_CONTENT_LANGUAGES is a list of tuples (language_code, language)
+ for language in getattr(settings, "WAGTAIL_CON... | wagtail/locales/views.py | 26 | Python | 0.429 | question | 55 | 51 | 51 | false | Hide add locale button when no more languages are available | 13,051 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
homepage = Page.objects.get(url_path="/home/")
new_page = page.copy(to=homepage)
self.assertNotEqual(page.id, new_page.id)
def test_copy_page_with_additional_excluded_fields(self):
homepage = Page.objects.get(url_path="/home/")
page = PageWithExcludedCopyField(
... | ```suggestion
# special_field and special_stream are in the list to be excluded,
``` |
homepage = Page.objects.get(url_path="/home/")
new_page = page.copy(to=homepage)
self.assertNotEqual(page.id, new_page.id)
def test_copy_page_with_additional_excluded_fields(self):
homepage = Page.objects.get(url_path="/home/")
page = PageWithExcludedCopyField(
... | @@ -1994,24 +1996,34 @@ def test_copy_page_with_o2o_relation(self):
def test_copy_page_with_additional_excluded_fields(self):
homepage = Page.objects.get(url_path="/home/")
- page = homepage.add_child(
- instance=PageWithExcludedCopyField(
- title="Discovery",
- ... | wagtail/tests/test_page_model.py | 26 | Python | 0.571 | suggestion | 94 | 51 | 51 | false | Handle non-JSON-safe fields in exclude_fields_in_copy | 13,082 | wagtail/wagtail | 16,097 | Python | laymonage | gasman |
};
const onDoubleClick = () => {
this.props.store.dispatch(
setFocusedComment(this.props.comment.localId, {
updatePinnedComment: true,
forceFocus: true,
}),
);
};
const top = this.props.layout.getCommentPosition(
this.props.comment.localId,
);
... | I think we should first check if the element's available, just in case we can avoid the delay.
I have not run this code, but here's a rough start.
```suggestion
// Allow delay for side panel to open and comment card to fade in with animations
checkCanFocusTrap: ({ containers = [] }) => {... | };
const onDoubleClick = () => {
this.props.store.dispatch(
setFocusedComment(this.props.comment.localId, {
updatePinnedComment: true,
forceFocus: true,
}),
);
};
const top = this.props.layout.getCommentPosition(
this.props.comment.localId,
);
... | @@ -629,6 +629,11 @@ export default class CommentComponent extends React.Component<CommentProps> {
}),
);
},
+ // Allow delay for side panel to open and comment card to fade in with animations
+ checkCanFocusTrap: () =>
+ new Promise((resol... | client/src/components/CommentApp/components/Comment/index.tsx | 26 | TypeScript | 0.857 | suggestion | 1,055 | 51 | 51 | false | fixes 11021 - added prop to FocusTrap to ensure proper comment focus | 13,106 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
const top = this.props.layout.getCommentPosition(
this.props.comment.localId,
);
return (
<FocusTrap
focusTrapOptions={
{
preventScroll: true,
clickOutsideDeactivates: true,
onDeactivate: () => {
this.props.store.dispatch(
... | Let's remove this `delayFocus`, as noted, it's not in the API for focus-trap any more and the default is probably what we want.
```suggestion
```
Alternatively, be explicit that we do want the default.
```suggestion
delayInitialFocus: true,
```
> delayInitialFocus {boolean}: Default: true. ... |
const top = this.props.layout.getCommentPosition(
this.props.comment.localId,
);
return (
<FocusTrap
focusTrapOptions={{
preventScroll: true,
clickOutsideDeactivates: true,
onDeactivate: () => {
this.props.store.dispatch(
setFocus... | @@ -629,6 +629,11 @@ export default class CommentComponent extends React.Component<CommentProps> {
}),
);
},
+ // Allow delay for side panel to open and comment card to fade in with animations
+ checkCanFocusTrap: () =>
+ new Promise((resol... | client/src/components/CommentApp/components/Comment/index.tsx | 26 | TypeScript | 0.857 | refactor | 521 | 51 | 51 | false | fixes 11021 - added prop to FocusTrap to ensure proper comment focus | 13,106 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
);
};
const top = this.props.layout.getCommentPosition(
this.props.comment.localId,
);
return (
<FocusTrap
focusTrapOptions={
{
preventScroll: true,
clickOutsideDeactivates: true,
onDeactivate: () => {
this.props.sto... | This gets us pretty close, but it still does not focus when there is an existing comment AND the comment side panel is closed.
```suggestion
container.matches('[data-form-side="comments"].form-side--comments [data-focus-target="true"]')
```
| );
};
const top = this.props.layout.getCommentPosition(
this.props.comment.localId,
);
return (
<FocusTrap
focusTrapOptions={{
preventScroll: true,
clickOutsideDeactivates: true,
onDeactivate: () => {
this.props.store.dispatch(
... | @@ -629,8 +629,22 @@ export default class CommentComponent extends React.Component<CommentProps> {
}),
);
},
+ // Allow delay for side panel to open and comment card to fade in with animations
+ checkCanFocusTrap: (containers: (HTMLElement | SVGElement)... | client/src/components/CommentApp/components/Comment/index.tsx | 26 | TypeScript | 0.786 | suggestion | 267 | 51 | 51 | false | fixes 11021 - added prop to FocusTrap to ensure proper comment focus | 13,106 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
onDeactivate: () => {
this.props.store.dispatch(
setFocusedComment(null, {
updatePinnedComment: true,
forceFocus: false,
}),
);
},
// Allow delay for side panel to open and comment card to... | We can now remove this line & the `as any` as we have since updated the library. | this.props.store.dispatch(
setFocusedComment(null, {
updatePinnedComment: true,
forceFocus: false,
}),
);
},
/** Allow delay for side panel to open and comment card to fade in with animations. */
checkCanFo... | @@ -629,8 +629,22 @@ export default class CommentComponent extends React.Component<CommentProps> {
}),
);
},
+ // Allow delay for side panel to open and comment card to fade in with animations
+ checkCanFocusTrap: (containers: (HTMLElement | SVGElement)... | client/src/components/CommentApp/components/Comment/index.tsx | 26 | TypeScript | 0.429 | refactor | 80 | 51 | 51 | false | fixes 11021 - added prop to FocusTrap to ensure proper comment focus | 13,106 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
setFocusedComment(this.props.comment.localId, {
updatePinnedComment: true,
forceFocus: true,
}),
);
};
const top = this.props.layout.getCommentPosition(
this.props.comment.localId,
);
return (
<FocusTrap
focusTrapOptions={
{
... | ```suggestion
/** Allow delay for side panel to open and comment card to fade in with animations */
```
Let's use JSDoc syntax, it will support better editor integration for documenting this option's purpose. | setFocusedComment(this.props.comment.localId, {
updatePinnedComment: true,
forceFocus: true,
}),
);
};
const top = this.props.layout.getCommentPosition(
this.props.comment.localId,
);
return (
<FocusTrap
focusTrapOptions={{
preven... | @@ -629,8 +629,22 @@ export default class CommentComponent extends React.Component<CommentProps> {
}),
);
},
+ // Allow delay for side panel to open and comment card to fade in with animations | client/src/components/CommentApp/components/Comment/index.tsx | 26 | TypeScript | 0.857 | suggestion | 225 | 51 | 51 | false | fixes 11021 - added prop to FocusTrap to ensure proper comment focus | 13,106 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
from django.template import Context, Engine, TemplateSyntaxError, Variable
from django.test import TestCase
from wagtail.images.models import Image, Rendition
from wagtail.images.templatetags.wagtailimages_tags import ImageNode
from wagtail.images.tests.utils import (
get_test_bad_image,
get_test_image_file,
... | I hadn’t registered until now that SVG images produce those `.0` values. I wonder if this is worth changing? It looks like according to the HTML spec those [dimension attributes](https://html.spec.whatwg.org/multipage/embedded-content-other.html#dimension-attributes) have to be "valid non-negative integers". | width="180"
height="135"
>
</picture>
"""
self.assertHTMLEqual(rendered, expected)
def test_preserve_svg_with_svg_image(self):
filenames = [
get_test_image_filename(self.svg_image, "width-40"),
get_test_image_fi... | @@ -483,3 +485,54 @@ def test_chaining_filterspecs(self):
</picture>
"""
self.assertHTMLEqual(rendered, expected)
+
+ def test_preserve_svg_with_raster_image(self):
+ filenames = [
+ get_test_image_filename(self.image, "width-180.format-avif"),
+ get_test_i... | wagtail/images/tests/test_templatetags.py | 26 | Python | 0.571 | suggestion | 309 | 486 | 31 | false | Handle preserve-svg for multiple renditions | 13,125 | wagtail/wagtail | 16,097 | Python | thibaudcolas | gasman |
var jcropapi;
function setupJcrop(image, original, focalPointOriginal, fields) {
var $chooser = image.closest('div.focal-point-chooser');
// To avoid an inline style, max-width and max-height are passed as data attributes
// from the focal-point-chooser class because they are dynamic values
$chooser.css('max-... | The original code directly sets the inline styles in the HTML and does nothing with it in the JavaScript. This means we only need to set it once on initial load.
So, I think we can move this to the on load function (the `$(function() {...})` below) so that it's only run once instead of also on resize and "remove" bu... | var jcropapi;
function setupJcrop(image, original, focalPointOriginal, fields) {
image.Jcrop(
{
trueSize: [original.width, original.height],
bgColor: 'rgb(192, 192, 192)',
onSelect: function (box) {
var x = Math.floor((box.x + box.x2) / 2);
var y = Math.floor((box.y + box.y2) / ... | @@ -1,6 +1,13 @@
var jcropapi;
function setupJcrop(image, original, focalPointOriginal, fields) {
+ var $chooser = image.closest('div.focal-point-chooser');
+
+ // To avoid an inline style, max-width and max-height are passed as data attributes
+ // from the focal-point-chooser class because they are dynamic val... | wagtail/images/static_src/wagtailimages/js/focal-point-chooser.js | 9 | JavaScript | 0.643 | refactor | 332 | 34 | 34 | false | refactor style-src to avoid unsafe-inline CSP | 13,147 | wagtail/wagtail | 16,097 | Python | laymonage | Chiemezuo |
block_val = EmbedValue("http://www.example.com/foo")
serialized_val = block.get_prep_value(block_val)
self.assertEqual(serialized_val, "http://www.example.com/foo")
serialized_empty_val = block.get_prep_value(None)
self.assertEqual(serialized_empty_val, "")
@patch("wagtail.... | These tests have been updated to use the `responses` library to simulate HTTP responses rather than mocking `get_embed`, as the latter was masking the error that occurs when the embed finder attempts to retrieve an embed at an empty URL. | def test_deserialize(self):
"""
Deserialising the JSONish value of an EmbedBlock (a URL) should give us an EmbedValue
for that URL
"""
block = EmbedBlock(required=False)
block_val = block.to_python("http://www.example.com/foo")
self.assertIsInstance(block_val... | @@ -920,12 +938,12 @@ def test_serialize(self):
serialized_empty_val = block.get_prep_value(None)
self.assertEqual(serialized_empty_val, "")
- @patch("wagtail.embeds.embeds.get_embed")
- def test_render(self, get_embed):
- get_embed.return_value = Embed(html="<h1>Hello world!</h1>")
+ ... | wagtail/embeds/tests/test_embeds.py | 26 | Python | 0.786 | suggestion | 237 | 51 | 51 | false | Fix saving of empty values in EmbedBlock | 13,160 | wagtail/wagtail | 16,097 | Python | gasman | gasman |
return {
"shortcuts": {
("actions-common", _("Common actions")): [
(_("Copy"), f"{KEYS.MOD} + c"),
(_("Cut"), f"{KEYS.MOD} + x"),
(_("Paste"), f"{KEYS.MOD} + v"),
(
_("Paste and match style")
... | I recommend we revise this approach so we do not have to repeat all the items that sit alongside the comment one each time.
```py
("actions-model", _("Actions")): [
(_("Save changes"), f"{KEYS.MOD} + s"),
(_("Preview"), f"{KEYS.MOD} + p"),
(_("Minimap")... | return {
"shortcuts": {
("actions-common", _("Common actions")): [
(_("Copy"), f"{KEYS.MOD} + c"),
(_("Cut"), f"{KEYS.MOD} + x"),
(_("Paste"), f"{KEYS.MOD} + v"),
(
_("Paste and match style")
... | @@ -1332,11 +1332,13 @@ def keyboard_shortcuts_dialog(context):
_("Add or show comments"),
f"{KEYS.CTRL} + {KEYS.ALT} + m",
),
+ (_("Minimap"), f"{KEYS.MOD} + ]"), | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.857 | suggestion | 908 | 51 | 51 | false | Added keyboard shortcut for minimap | 13,167 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
setPanelsExpanded(true);
}, [anchorsContainer, setPanelsExpanded]);
return (
<div>
<CollapseAll
expanded={panelsExpanded}
onClick={() => {
setPanelsExpanded(!panelsExpanded);
toggleAllPanels(!panelsExpanded);
}}
floating
insideMinimap={expan... | ```suggestion
data-w-kbd-key-value="alt+]"
``` | setPanelsExpanded(true);
}, [anchorsContainer, setPanelsExpanded]);
return (
<div>
<CollapseAll
expanded={panelsExpanded}
onClick={() => {
setPanelsExpanded(!panelsExpanded);
toggleAllPanels(!panelsExpanded);
}}
floating
insideMinimap={expan... | @@ -222,6 +222,9 @@ const Minimap: React.FunctionComponent<MinimapProps> = ({
className="w-minimap__toggle"
// Not the most correct label, but matches side panels with similar toggles.
aria-label={gettext('Toggle side panel')}
+ data-controller="w-kbd"
+ data... | client/src/components/Minimap/Minimap.tsx | 26 | TypeScript | 0.571 | suggestion | 60 | 51 | 51 | false | Added keyboard shortcut for minimap | 13,167 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
)
def get_filterset_kwargs(self):
kwargs = super().get_filterset_kwargs()
kwargs["is_searching"] = self.is_searching
return kwargs
def get_next_url(self):
next_url = self.index_url
request_query_string = self.request.META.get("QUERY_STRING")
if request_q... | Need tests that confirm:
- the view mode is passed correctly
- the listings’ HTML are adapted based on the view mode
From Sage: need tests that would fail if they ran against the previous implementation of those listings (so demonstrate the changes add this new behavior).
---
Assert contents of title colum... |
def get_add_url(self):
# Pass the collection filter to prefill the add form's collection field
return set_query_params(
super().get_add_url(),
{"collection_id": self.current_collection and self.current_collection.pk},
)
def get_filterset_kwargs(self):
kw... | @@ -111,12 +111,15 @@ def get_next_url(self):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
+ view_mode = self.request.GET.get("view", "grid")
+
context.update(
{
"next": self.get_next_url(),
"current_col... | wagtail/images/views/images.py | 26 | Python | 0.5 | bug | 392 | 51 | 51 | false | List View for Image Listing | 13,172 | wagtail/wagtail | 16,097 | Python | thibaudcolas | joelwilliam2005 |
# Upon validation, the cleaned data is a Collection instance
return self.filters and self.filters.form.cleaned_data.get("collection_id")
def get_add_url(self):
# Pass the collection filter to prefill the add form's collection field
return set_query_params(
super().get_ad... | This is probably worth extracting into a cached property on the view, e.g.
```py
@cached_property
def view_mode(self):
return self.request.GET.get("view", "grid")
```
So you can use it in other methods/properties as `self.view_mode`, e.g. when you're defining the `columns`.
And if we do want to preserv... | .prefetch_renditions("max-165x165")
)
return images
@cached_property
def current_collection(self):
# Upon validation, the cleaned data is a Collection instance
return self.filters and self.filters.form.cleaned_data.get("collection_id")
def get_add_url(self):
... | @@ -111,12 +111,15 @@ def get_next_url(self):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
+ view_mode = self.request.GET.get("view", "grid") | wagtail/images/views/images.py | 26 | Python | 0.857 | performance | 684 | 51 | 51 | false | List View for Image Listing | 13,172 | wagtail/wagtail | 16,097 | Python | laymonage | joelwilliam2005 |
horz = int((focal_point.x * 100) // self.width)
vert = int((focal_point.y * 100) // self.height)
return f"background-position: {horz}% {vert}%;"
else:
return "background-position: 50% 50%;"
@property
def background_position_x(self):
"""
Re... | ```suggestion
This can be passed as a data attribute to then be used in JavaScript to set the `background-position-x` CSS property instead of using inline styles.
<div class="my-bg-image" data-background-position-x="{{ image.background_position_x }}">
</div>
``` | return f"background-position: {horz} {vert};"
@property
def background_position_x(self):
"""
Returns the horizontal background position as a percentage string.
This positions the rendition horizontally according to the focal point's x coordinate.
If no focal point is se... | @@ -1408,6 +1408,62 @@ def background_position_style(self):
else:
return "background-position: 50% 50%;"
+ @property
+ def background_position_x(self):
+ """
+ Returns the horizontal background position as a percentage string.
+
+ This positions the rendition horizonta... | wagtail/images/models.py | 26 | Python | 0.857 | suggestion | 300 | 51 | 51 | false | refactor background_position_style into x & y methods | 13,173 | wagtail/wagtail | 16,097 | Python | laymonage | Chiemezuo |
image_focal_point = self.image.get_focal_point()
if image_focal_point:
transform = self.filter.get_transform(self.image)
return image_focal_point.transform(transform)
@property
def background_position_style(self):
"""
Returns a `background-position` rule ... | We can refactor this (and the above lines) to use the newly added `background_position_x` and `background_position_y`, e.g.
```py
horz = self.background_position_x
vert = self.background_position_y
return f"background-position: {horz} {vert};"
``` | image_focal_point = self.image.get_focal_point()
if image_focal_point:
transform = self.filter.get_transform(self.image)
return image_focal_point.transform(transform)
@property
def background_position_style(self):
"""
Returns a `background-position` rule ... | @@ -1408,6 +1408,62 @@ def background_position_style(self):
else:
return "background-position: 50% 50%;" | wagtail/images/models.py | 26 | Python | 0.857 | refactor | 254 | 51 | 51 | false | refactor background_position_style into x & y methods | 13,173 | wagtail/wagtail | 16,097 | Python | laymonage | Chiemezuo |
return Array.from(
document.querySelectorAll(
`[${this.schema.controllerAttribute}="${identifier}"]`,
),
)
.map((element) =>
this.getControllerForElementAndIdentifier(element, identifier),
)
.filter(Boolean) as Controller[];
}
}
/**
* Initialises the Wagtail Sti... | Can we please add a basic JSDoc here.
I love the function though, super helpful.
We probably should also add this as a requested feature in Stimulus itself. | * ```ts
* const controller = window.wagtail.app.queryController('w-preview');
* const content = await controller?.extractContent();
* ```
*/
queryController(identifier: string): Controller | null {
return this.getControllerForElementAndIdentifier(
document.querySelector(
`[${this.sche... | @@ -1,6 +1,29 @@
-import type { Definition } from '@hotwired/stimulus';
+import type { Controller, Definition } from '@hotwired/stimulus';
import { Application } from '@hotwired/stimulus';
+class WagtailApplication extends Application {
+ queryController(identifier: string): Controller | null {
+ return this.get... | client/src/includes/initStimulus.ts | 26 | TypeScript | 0.429 | suggestion | 165 | 34 | 51 | false | Add API for extracting preview page content | 13,197 | wagtail/wagtail | 16,097 | Python | lb- | laymonage |
// The control at index n will insert a block at index n
this.inserters = [];
// Incrementing counter used to generate block prefixes, also reflected in the
// 'count' hidden input. This count includes deleted items
this.blockCounter = 0;
this.countInput = dom.find('[data-streamfield-stream-cou... | I was wondering why TypeScript didn’t raise alarm balls about this. Turns out we’re inside a `.js` file! | // The control at index n will insert a block at index n
this.inserters = [];
// Incrementing counter used to generate block prefixes, also reflected in the
// 'count' hidden input. This count includes deleted items
this.blockCounter = 0;
this.countInput = dom.find('[data-streamfield-stream-cou... | @@ -230,6 +231,8 @@ export class StreamBlock extends BaseSequenceBlock {
}
this.initDragNDrop();
+
+ setAttrs(this.container, this.blockDef.meta.attrs || {}); | client/src/components/StreamField/blocks/StreamBlock.js | 26 | JavaScript | 0.643 | suggestion | 104 | 51 | 51 | false | Add `form_attrs` support to all StreamField blocks | 13,211 | wagtail/wagtail | 16,097 | Python | thibaudcolas | laymonage |
add_url_name = "wagtailimages:add_multiple"
edit_url_name = "wagtailimages:edit"
template_name = "wagtailimages/images/index.html"
results_template_name = "wagtailimages/images/index_results.html"
def get_paginate_by(self, queryset):
return getattr(settings, "WAGTAILIMAGES_INDEX_PAGE_SIZE",... | Bulk fetching of references? @joelwilliam2005 says this might need further work? cc @laymonage.
We think we can proceed with this current implementation as-is since we’re only showing usage count not ordering / filtering. And can add bulk fetching once we support filtering / ordering.
| add_url_name = "wagtailimages:add_multiple"
edit_url_name = "wagtailimages:edit"
template_name = "wagtailimages/images/index.html"
results_template_name = "wagtailimages/images/index_results.html"
def get_paginate_by(self, queryset):
return getattr(settings, "WAGTAILIMAGES_INDEX_PAGE_SIZE",... | @@ -80,13 +83,29 @@ def get_valid_orderings(self):
return self.ORDERING_OPTIONS
def get_base_queryset(self):
- # Get images (filtered by user permission)
+ # Get images (filtered by user permission and annotated with usage counts)
images = (
permission_policy.instance... | wagtail/images/views/images.py | 26 | Python | 0.429 | suggestion | 288 | 51 | 51 | false | Usage count column for media listings | 13,234 | wagtail/wagtail | 16,097 | Python | thibaudcolas | joelwilliam2005 |
header_icon = "image"
page_title = gettext_lazy("Images")
add_item_label = gettext_lazy("Add an image")
index_url_name = "wagtailimages:index"
index_results_url_name = "wagtailimages:index_results"
add_url_name = "wagtailimages:add_multiple"
edit_url_name = "wagtailimages:edit"
template_... | This annotation is currently not used if we're using the grid view. Are we planning to show it in the grid view as well? If not, we should not add the annotation in that case. | header_icon = "image"
page_title = gettext_lazy("Images")
add_item_label = gettext_lazy("Add an image")
index_url_name = "wagtailimages:index"
index_results_url_name = "wagtailimages:index_results"
add_url_name = "wagtailimages:add_multiple"
edit_url_name = "wagtailimages:edit"
template_... | @@ -80,13 +83,29 @@ def get_valid_orderings(self):
return self.ORDERING_OPTIONS
def get_base_queryset(self):
- # Get images (filtered by user permission)
+ # Get images (filtered by user permission and annotated with usage counts)
images = (
permission_policy.instance... | wagtail/images/views/images.py | 26 | Python | 0.429 | suggestion | 175 | 51 | 51 | false | Usage count column for media listings | 13,234 | wagtail/wagtail | 16,097 | Python | laymonage | joelwilliam2005 |
permission_checker = PermissionPolicyChecker(permission_policy)
Document = get_document_model()
class BulkActionsColumn(BulkActionsCheckboxColumn):
def __init__(self, *args, **kwargs):
super().__init__(*args, obj_type="document", **kwargs)
def get_header_context_data(self, parent_context):
c... | There's no document-specific/image-specific code here and they both can use the same class, so could you put this in `wagtail/admin/ui/tables/__init__.py` please? |
class BulkActionsColumn(BulkActionsCheckboxColumn):
def __init__(self, *args, **kwargs):
super().__init__(*args, obj_type="document", **kwargs)
def get_header_context_data(self, parent_context):
context = super().get_header_context_data(parent_context)
parent = parent_context.get("cur... | @@ -48,6 +53,10 @@ def get_context_data(self, parent_context):
return context
+class UsageCountColumn(BaseColumn):
+ cell_template_name = "wagtailadmin/tables/usage_count_column_cell.html" | wagtail/documents/views/documents.py | 26 | Python | 0.571 | question | 162 | 51 | 51 | false | Usage count column for media listings | 13,234 | wagtail/wagtail | 16,097 | Python | laymonage | joelwilliam2005 |
model = get_document_model()
add_item_label = gettext_lazy("Add a document")
show_other_searches = True
def get_base_queryset(self):
# Get documents (filtered by user permission and annotated with usage counts)
documents = (
self.permission_policy.instances_user_has_any_perm... | Would be nice if we could extract this into a method on the `ReferenceIndex` e.g.
```py
@classmethod
def usage_count_subquery(cls, model):
return Coalesce(
Subquery(
ReferenceIndex.objects.filter(
to_content_type=ContentType.objects.get_for_model(model),
... | self.request.user, ["change", "delete"]
).select_related("collection")
# Annotate with usage count from the ReferenceIndex
documents = documents.annotate(
usage_count=ReferenceIndex.usage_count_subquery(self.model)
)
return documents
@cached_propert... | @@ -78,10 +87,31 @@ class IndexView(generic.IndexView):
show_other_searches = True
def get_base_queryset(self):
- # Get documents (filtered by user permission)
- return self.permission_policy.instances_user_has_any_permission_for(
- self.request.user, ["change", "delete"]
- )... | wagtail/documents/views/documents.py | 26 | Python | 1 | refactor | 800 | 51 | 51 | false | Usage count column for media listings | 13,234 | wagtail/wagtail | 16,097 | Python | laymonage | joelwilliam2005 |
if self.layout == "grid":
return []
else:
columns = [
BulkActionsColumn("bulk_actions"),
ImagePreviewColumn(
"preview",
label=_("Preview"),
accessor="image",
classname=... | Since we're already going down the route of doing the query as part of the main query, I wonder if we should just allow ordering and see what happens in the wild? | ),
TitleColumnWithFilename(
"title",
label=_("Title"),
sort_key="title",
get_url=self.get_edit_url,
width="35%",
classname="title-with-filename",
),
... | @@ -160,6 +179,7 @@ def columns(self):
label=_("Created"),
sort_key="created_at",
),
+ UsageCountColumn("usage_count", label=_("Usage")), | wagtail/images/views/images.py | 26 | Python | 0.429 | question | 162 | 51 | 51 | false | Usage count column for media listings | 13,234 | wagtail/wagtail | 16,097 | Python | laymonage | joelwilliam2005 |
elif self.workflow_in_progress:
return _("in moderation")
else:
return _("draft")
else:
if self.approved_schedule:
return _("live + scheduled")
elif self.workflow_in_progress:
return _("live + in mode... | Decided to be opinionated here.
It could probably use some logging as I wasn't entirely convinced about a system check. Happy to change/tweak | from django import forms
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core import checks
from django.core.exceptions import Permission... | @@ -1360,13 +1364,19 @@ def status_string(self):
else:
return _("live")
- def get_lock(self):
+ def get_lock(self) -> Union[BaseLock, WorkflowLock, None]:
# Standard locking should take precedence over workflow locking
# because it's possible for both to be used a... | wagtail/models/workflows.py | 26 | Python | 0.429 | suggestion | 144 | 31 | 1,376 | false | Allow defining custom `WorkflowLock` subclasses on workflow `Task`s | 13,239 | wagtail/wagtail | 16,097 | Python | zerolab | zerolab |
else:
return _("draft")
else:
if self.approved_schedule:
return _("live + scheduled")
elif self.workflow_in_progress:
return _("live + in moderation")
elif self.has_unpublished_changes:
return _("live... | thought: should this use `model.__qualname__`? | from django import forms
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core import checks
from django.core.exceptions import Permission... | @@ -1360,13 +1367,27 @@ def status_string(self):
else:
return _("live")
- def get_lock(self):
+ def get_lock(self) -> Union[BaseLock, WorkflowLock, None]:
# Standard locking should take precedence over workflow locking
# because it's possible for both to be used a... | wagtail/models/workflows.py | 26 | Python | 0.286 | question | 46 | 37 | 1,376 | false | Allow defining custom `WorkflowLock` subclasses on workflow `Task`s | 13,239 | wagtail/wagtail | 16,097 | Python | zerolab | zerolab |
return _("expired")
elif self.approved_schedule:
return _("scheduled")
elif self.workflow_in_progress:
return _("in moderation")
else:
return _("draft")
else:
if self.approved_schedule:
... | The comment doesn't seem to reflect what's happening now that we no longer swap out the lock class if it's not a `WorkflowLock` subclass. | from django import forms
from django.conf import settings
from django.contrib.auth.models import Group
from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.core import checks
from django.core.exceptions import Permission... | @@ -1360,13 +1367,27 @@ def status_string(self):
else:
return _("live")
- def get_lock(self):
+ def get_lock(self) -> Union[BaseLock, WorkflowLock, None]:
# Standard locking should take precedence over workflow locking
# because it's possible for both to be used a... | wagtail/models/workflows.py | 26 | Python | 0.5 | suggestion | 137 | 42 | 1,376 | false | Allow defining custom `WorkflowLock` subclasses on workflow `Task`s | 13,239 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
from wagtail.coreutils import get_content_type_label
from wagtail.forms import TaskStateCommentForm
from wagtail.locks import BaseLock, WorkflowLock
from wagtail.log_actions import log
from wagtail.query import SpecificQuerySetMixin
from wagtail.signals import (
task_approved,
task_cancelled,
task_rejected... | No longer used
```suggestion
``` | from wagtail.locks import WorkflowLock
from wagtail.log_actions import log
from wagtail.query import SpecificQuerySetMixin
from wagtail.signals import (
task_approved,
task_cancelled,
task_rejected,
task_submitted,
workflow_approved,
workflow_cancelled,
workflow_rejected,
workflow_submit... | @@ -41,6 +44,8 @@
from .revisions import Revision, RevisionMixin
from .specific import SpecificMixin
+logger = logging.getLogger(__name__)
+ | wagtail/models/workflows.py | 26 | Python | 0.5 | suggestion | 34 | 51 | 51 | false | Allow defining custom `WorkflowLock` subclasses on workflow `Task`s | 13,239 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
notifier.notification = notification
self.assertSetEqual(notifier.get_valid_recipients(self.object), set())
class TestCustomWorkflowLockOnTask(BasePageWorkflowTests):
model_name = "page"
def setup_workflow_and_tasks(self):
self.workflow = Workflow.objects.create(name="... | ```suggestion
@mock.patch.object(CustomLockTask, "lock_class", new_callable=mock.PropertyMock)
def test_typeerror_if_custom_lock_class_inherits_basic_locks(self, mock_property):
mock_property.return_value = BasicLock
self.post("submit")
with self.assertRaises(TypeError):
... | notifier.notification = notification
self.assertSetEqual(notifier.get_valid_recipients(self.object), set())
class TestCustomWorkflowLockOnTask(BasePageWorkflowTests):
def setup_workflow_and_tasks(self):
self.workflow = Workflow.objects.create(name="test_workflow")
s... | @@ -4851,3 +4854,29 @@ def test_base_workflowstate_email_notifier_get_valid_recipients(
with self.subTest(f"Testing with {notification}_notifications"):
notifier.notification = notification
self.assertSetEqual(notifier.get_valid_recipients(self.object), set())
+
+
+class T... | wagtail/admin/tests/test_workflows.py | 26 | Python | 1 | suggestion | 755 | 29 | 34 | false | Allow defining custom `WorkflowLock` subclasses on workflow `Task`s | 13,239 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
current_workflow_task_state = self.current_workflow_task_state
if current_workflow_task_state:
return current_workflow_task_state.task.specific
@property
def status_string(self):
if not self.live:
if self.expired:
return _("expired")
e... | ```suggestion
def get_lock(self):
```
The `get_lock` annotation in `LockableMixin` doesn't have annotation yet, so I'm not sure about adding it only here. Also, we've dropped Python 3.9 support, so we can use the `|` union syntax if we want to add type hints. | return current_workflow_task_state.task.specific
@property
def status_string(self):
if not self.live:
if self.expired:
return _("expired")
elif self.approved_schedule:
return _("scheduled")
elif self.workflow_in_progress:
... | @@ -1360,13 +1364,14 @@ def status_string(self):
else:
return _("live")
- def get_lock(self):
+ def get_lock(self) -> Union[BaseLock, WorkflowLock, None]: | wagtail/models/workflows.py | 26 | Python | 1 | suggestion | 268 | 37 | 35 | false | Allow defining custom `WorkflowLock` subclasses on workflow `Task`s | 13,239 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
notifications = ["approved", "rejected", "submitted"]
for notification in notifications:
with self.subTest(f"Testing with {notification}_notifications"):
notifier.notification = notification
self.assertSetEqual(
notifier.get_valid_recipient... | ```suggestion
```
and we should make a subclass of this test with `BaseSnippetWorkflowTests` | notifications = ["approved", "rejected", "submitted"]
for notification in notifications:
with self.subTest(f"Testing with {notification}_notifications"):
notifier.notification = notification
self.assertSetEqual(
notifier.get_valid_recipient... | @@ -4851,3 +4854,29 @@ def test_base_workflowstate_email_notifier_get_valid_recipients(
with self.subTest(f"Testing with {notification}_notifications"):
notifier.notification = notification
self.assertSetEqual(notifier.get_valid_recipients(self.object), set())
+
+
+class T... | wagtail/admin/tests/test_workflows.py | 26 | Python | 0.643 | suggestion | 93 | 48 | 51 | false | Allow defining custom `WorkflowLock` subclasses on workflow `Task`s | 13,239 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
* ```
*/
export class KeyboardController extends Controller<
HTMLButtonElement | HTMLAnchorElement
> {
static values = {
key: { default: '', type: String },
scope: { default: '', type: String },
};
/** Keyboard shortcut string. */
declare keyValue: string;
/** Scope of the keyboard shortcut, defa... | Maybe we could consider using the Wagtail config approach instead?
See `client/src/config/wagtailConfig.ts` & `wagtail/admin/templates/wagtailadmin/admin_base.html` (`wagtail-config`) & `wagtail/admin/templatetags/wagtailadmin_tags.py` (`wagtail_config` template tag)
.
And then just not register the controller at... | * ```html
* <button type="button" data-controller="w-kbd" aria-keyshortcuts="alt+p">Trigger me with alt+p.</button>
* ```
*/
export class KeyboardController extends Controller<
HTMLButtonElement | HTMLAnchorElement
> {
static values = {
key: { default: '', type: String },
scope: { default: '', type: Str... | @@ -54,6 +54,22 @@ export class KeyboardController extends Controller<
}
}
+ customKeyboardShortcutsEnabled(): boolean { | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.643 | suggestion | 435 | 51 | 51 | false | Added user account setting for disabling custom keyboard shortcuts | 13,258 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
import { Application } from '@hotwired/stimulus';
import Mousetrap from 'mousetrap';
import { KeyboardController } from './KeyboardController';
jest.mock('../config/wagtailConfig', () => ({
WAGTAIL_CONFIG: {
KEYBOARD_SHORTCUT_PREFERENCE: true,
},
}));
describe('KeyboardController', () => {
let app;
const... | It might be better to add the 'default' (true) to the core stubs instead.
`client/tests/stubs.js` | import { Application } from '@hotwired/stimulus';
import Mousetrap from 'mousetrap';
import { KeyboardController } from './KeyboardController';
jest.mock('../config/wagtailConfig', () => ({
WAGTAIL_CONFIG: {
KEYBOARD_SHORTCUTS_ENABLED: true,
},
}));
describe('KeyboardController', () => {
let app;
const b... | @@ -3,6 +3,12 @@ import Mousetrap from 'mousetrap';
import { KeyboardController } from './KeyboardController';
+jest.mock('../config/wagtailConfig', () => ({
+ WAGTAIL_CONFIG: {
+ KEYBOARD_SHORTCUT_PREFERENCE: true, | client/src/controllers/KeyboardController.test.js | 8 | JavaScript | 0.571 | suggestion | 100 | 33 | 33 | false | Added user account setting for disabling custom keyboard shortcuts | 13,258 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
* @example
* ```html
* <button type="button" data-controller="w-kbd" data-w-kbd-key="[">Trigger me with the <kbd>[</kbd> key.</button>
* ```
*
* @example - use `mod` for `ctrl` on Windows and `cmd` on MacOS
* ```html
* <button type="button" data-controller="w-kbd" data-w-kbd-key="mod+s">Trigger me with <kbd>ctr... | ```suggestion
* If custom keyboard shortcuts are disabled by user in settings then controller will not be loaded.
``` | *
* @example
* ```html
* <button type="button" data-controller="w-kbd" data-w-kbd-key="[">Trigger me with the <kbd>[</kbd> key.</button>
* ```
*
* @example - use `mod` for `ctrl` on Windows and `cmd` on MacOS
* ```html
* <button type="button" data-controller="w-kbd" data-w-kbd-key="mod+s">Trigger me with <kbd>... | @@ -34,6 +35,13 @@ import 'mousetrap/plugins/global-bind/mousetrap-global-bind';
export class KeyboardController extends Controller<
HTMLButtonElement | HTMLAnchorElement
> {
+ /**
+ * If custom keyboard shortcuts are disabled by user in settings then controller will not be loaded | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.786 | suggestion | 122 | 51 | 51 | false | Added user account setting for disabling custom keyboard shortcuts | 13,258 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
this.prefix + '-value',
initialState,
undefined,
capabilities,
);
initCollapsiblePanel(this.element.querySelector('[data-panel-toggle]'));
if (collapsed) {
this.collapse();
}
this.toggleElement.addEventListener('wagtail:panel-toggle', () => {
const label = this... | Not a must but this felt like a better use of available space on desktop. | // we want to control the collapsible rendering from here instead.
if (this.blockDef instanceof StructBlockDefinition) {
this.blockDef.collapsible = false;
}
this.block = this.blockDef.render(
blockElement,
this.prefix + '-value',
initialState,
undefined,
capabilitie... | @@ -217,12 +217,12 @@ export class BaseSequenceChild extends EventTarget {
}
this.toggleElement.addEventListener('wagtail:panel-toggle', () => {
- const label = this.getTextLabel({ maxLength: 50 });
+ const label = this.getTextLabel({ maxLength: 70 });
this.titleElement.text(label || '');
... | client/src/components/StreamField/blocks/BaseSequenceBlock.js | 26 | JavaScript | 0.286 | suggestion | 73 | 51 | 51 | false | Always show block types in StreamField UI | 13,263 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
def render(self, context):
fragment = self.nodelist.render(context) if self.nodelist else ""
# Only strip the leading and trailing spaces, unlike
# {% blocktrans trimmed %} that also does line-by-line stripping.
# Then, use mark_safe because the SafeString returned by
# Node... | Add an `include` example so it's clearer why you might need the `fragment` over just adding `asvar` to `blocktrans`.
Edit: actually, now that I think about it, this use case can still be covered by `blocktrans trimmed asvar`... |
def render(self, context):
fragment = self.nodelist.render(context) if self.nodelist else ""
# Only strip the leading and trailing spaces, unlike
# {% blocktrans trimmed %} that also does line-by-line stripping.
# Then, use mark_safe because the SafeString returned by
# Node... | @@ -978,28 +978,33 @@ def fragment(parser, token):
Store a template fragment as a variable.
Usage:
+
+ .. code-block:: html+django
+
{% fragment as header_title %}
{% blocktrans trimmed %}Welcome to the {{ site_name }} Wagtail CMS{% endblocktrans %}
{% endfragment %}
+ ... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.643 | suggestion | 230 | 51 | 51 | false | Add UI components documentation | 13,281 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
fragment = self.nodelist.render(context) if self.nodelist else ""
# Only strip the leading and trailing spaces, unlike
# {% blocktrans trimmed %} that also does line-by-line stripping.
# Then, use mark_safe because the SafeString returned by
# NodeList.render() is lost after stri... | Now that we use this in documentation, I think a link to the Slippers docs will be more appropriate.
```suggestion
Adopted from `slippers' fragment template tag <https://mitchel.me/slippers/docs/template-tags-filters/#fragment>`_ with a few tweaks.
``` | fragment = self.nodelist.render(context) if self.nodelist else ""
# Only strip the leading and trailing spaces, unlike
# {% blocktrans trimmed %} that also does line-by-line stripping.
# Then, use mark_safe because the SafeString returned by
# NodeList.render() is lost after stri... | @@ -978,28 +978,33 @@ def fragment(parser, token):
Store a template fragment as a variable.
Usage:
+
+ .. code-block:: html+django
+
{% fragment as header_title %}
{% blocktrans trimmed %}Welcome to the {{ site_name }} Wagtail CMS{% endblocktrans %}
{% endfragment %}
+ ... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.857 | suggestion | 258 | 51 | 51 | false | Add UI components documentation | 13,281 | wagtail/wagtail | 16,097 | Python | thibaudcolas | laymonage |
from rest_framework.authentication import SessionAuthentication
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response
from wagtail.api.v2.views import PagesAPIViewSet
from wagtail.models import Page
from .actions.convert_alias import ConvertAliasPageAPIAction
from .actions.cop... | Can we put this in https://github.com/wagtail/wagtail/blob/bb8800927c74207fe7de9f4efca8a8961e2f95ab/wagtail/api/v2/views.py#L37-L38 instead as per https://github.com/wagtail/wagtail/issues/13265#issuecomment-3107821235? | from rest_framework.response import Response
from wagtail.api.v2.views import PagesAPIViewSet
from wagtail.models import Page
from .actions.convert_alias import ConvertAliasPageAPIAction
from .actions.copy import CopyPageAPIAction
from .actions.copy_for_translation import CopyForTranslationAPIAction
from .actions.cre... | @@ -26,6 +28,23 @@ class PagesAdminAPIViewSet(PagesAPIViewSet):
base_serializer_class = AdminPageSerializer
authentication_classes = [SessionAuthentication]
+ @property
+ def renderer_classes(self): | wagtail/admin/api/views.py | 26 | Python | 0.5 | question | 219 | 51 | 51 | false | Fix #13262 admin API renderer classes when rest_framework not installed | 13,284 | wagtail/wagtail | 16,097 | Python | laymonage | vijay-x-Raj |
self.assertEqual(len(renderer_classes), 2)
self.assertIn(JSONRenderer, renderer_classes)
self.assertIn(BrowsableAPIRenderer, renderer_classes)
@patch('wagtail.admin.api.views.apps.is_installed')
def test_renderer_classes_without_rest_framework(self, mock_is_installed):
"""Test t... | Can we have another test that verifies the API can still return HTML with the right `Accept` header? | @patch("wagtail.api.v2.views.apps.is_installed")
def test_renderer_classes_without_rest_framework(self, mock_is_installed):
"""Test that only JSONRenderer is included when rest_framework is not installed."""
# Mock rest_framework as not installed
def mock_installed(app):
ret... | @@ -0,0 +1,70 @@
+import json
+from unittest.mock import patch
+
+from django.test import TestCase
+from django.urls import reverse
+
+from wagtail.admin.api.views import PagesAdminAPIViewSet
+from wagtail.test.utils import WagtailTestUtils
+
+
+class TestPagesAdminAPIRendererClasses(WagtailTestUtils, TestCase):
+ "... | wagtail/admin/tests/api/test_renderer_classes.py | 26 | Python | 0.5 | question | 100 | 48 | 39 | false | Fix #13262 admin API renderer classes when rest_framework not installed | 13,284 | wagtail/wagtail | 16,097 | Python | laymonage | vijay-x-Raj |
from wagtail.api import APIField
from wagtail.models import Page, PageViewRestriction, Site
from .filters import (
AncestorOfFilter,
ChildOfFilter,
DescendantOfFilter,
FieldsFilter,
LocaleFilter,
OrderingFilter,
SearchFilter,
TranslationOfFilter,
)
from .pagination import WagtailPagina... | Maybe we should use `classproperty` just in case people do `renderer_classes = BaseAPIViewSet.renderer_classes + [...]` in their subclasses | from rest_framework.viewsets import GenericViewSet
from wagtail.api import APIField
from wagtail.models import Page, PageViewRestriction, Site
from .filters import (
AncestorOfFilter,
ChildOfFilter,
DescendantOfFilter,
FieldsFilter,
LocaleFilter,
OrderingFilter,
SearchFilter,
Translati... | @@ -35,7 +36,21 @@
class BaseAPIViewSet(GenericViewSet):
- renderer_classes = [JSONRenderer, BrowsableAPIRenderer]
+ @property | wagtail/api/v2/views.py | 26 | Python | 0.571 | suggestion | 139 | 51 | 51 | false | Fix #13262 admin API renderer classes when rest_framework not installed | 13,284 | wagtail/wagtail | 16,097 | Python | laymonage | vijay-x-Raj |
import json
from unittest.mock import patch
from django.test import TestCase
from django.urls import reverse
from wagtail.api.v2.views import BaseAPIViewSet
from wagtail.test.utils import WagtailTestUtils
class TestBaseAPIViewSetRendererClasses(WagtailTestUtils, TestCase):
"""Test that BaseAPIViewSet renderer b... | Probably better to have the same test in `admin.tests.api` for good measure | import json
from unittest.mock import patch
from django.test import TestCase
from django.urls import reverse
from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer
from wagtail.api.v2.views import BaseAPIViewSet
from wagtail.test.utils import WagtailTestUtils
class TestBaseAPIViewSetRendererClasses... | @@ -0,0 +1,101 @@
+import json
+from unittest.mock import patch
+
+from django.test import TestCase
+from django.urls import reverse
+
+from wagtail.api.v2.views import BaseAPIViewSet
+from wagtail.test.utils import WagtailTestUtils
+
+
+class TestBaseAPIViewSetRendererClasses(WagtailTestUtils, TestCase):
+ """Test ... | wagtail/api/v2/tests/test_renderer_classes.py | 23 | Python | 0.429 | suggestion | 75 | 48 | 48 | false | Fix #13262 admin API renderer classes when rest_framework not installed | 13,284 | wagtail/wagtail | 16,097 | Python | laymonage | vijay-x-Raj |
reverse("wagtailapi_v2:pages:listing"), HTTP_ACCEPT="application/json"
)
self.assertEqual(response.status_code, 200)
self.assertEqual(response["Content-Type"], "application/json")
# Should be valid JSON
content = json.loads(response.content.decode("UTF-8"))
... | Turns out we can't have these tests due to the test mechanism added in #12251... I'll remove them for now and raise a separate PR to change that mechanism. | import json
from unittest.mock import patch
from django.test import TestCase
from django.urls import reverse
from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer
from wagtail.api.v2.views import BaseAPIViewSet
from wagtail.test.utils import WagtailTestUtils
class TestBaseAPIViewSetRendererClasses... | @@ -0,0 +1,88 @@
+import json
+from unittest.mock import patch
+
+from django.test import TestCase
+from django.urls import reverse
+from rest_framework.renderers import BrowsableAPIRenderer, JSONRenderer
+
+from wagtail.api.v2.views import BaseAPIViewSet
+from wagtail.test.utils import WagtailTestUtils
+
+
+class Test... | wagtail/api/v2/tests/test_renderer_classes.py | 26 | Python | 0.429 | suggestion | 155 | 40 | 60 | false | Fix #13262 admin API renderer classes when rest_framework not installed | 13,284 | wagtail/wagtail | 16,097 | Python | laymonage | vijay-x-Raj |
Column,
DateColumn,
TitleColumn,
UsageCountColumn,
)
from wagtail.admin.utils import get_valid_next_url_from_request, set_query_params
from wagtail.admin.views import generic
from wagtail.images import get_image_model
from wagtail.images.exceptions import InvalidFilterSpecError
from wagtail.images.forms... | This should be put in the `BaseMediaFilterSet` so that it's shared with the `DocumentsFilterSet` as well | DateColumn,
TitleColumn,
UsageCountColumn,
)
from wagtail.admin.utils import get_valid_next_url_from_request, set_query_params
from wagtail.admin.views import generic
from wagtail.images import get_image_model
from wagtail.images.exceptions import InvalidFilterSpecError
from wagtail.images.forms import URLG... | @@ -43,6 +44,17 @@
class ImagesFilterSet(BaseMediaFilterSet):
permission_policy = permission_policy
+ usage_count = django_filters.RangeFilter( | wagtail/images/views/images.py | 26 | Python | 0.571 | suggestion | 104 | 51 | 51 | false | Added Usage Count Filter | 13,291 | wagtail/wagtail | 16,097 | Python | laymonage | joelwilliam2005 |
from wagtail.images.exceptions import InvalidFilterSpecError
from wagtail.images.forms import URLGeneratorForm, get_image_form
from wagtail.images.models import Filter, SourceImageIOError
from wagtail.images.permissions import permission_policy
from wagtail.images.utils import generate_signature
from wagtail.models imp... | I don't think we have `help_text` in any of our built-in filters, so adding it only for this filter would introduce inconsistency | from wagtail.images.forms import URLGeneratorForm, get_image_form
from wagtail.images.models import Filter, SourceImageIOError
from wagtail.images.permissions import permission_policy
from wagtail.images.utils import generate_signature
from wagtail.models import ReferenceIndex, Site
permission_checker = PermissionPoli... | @@ -43,6 +44,17 @@
class ImagesFilterSet(BaseMediaFilterSet):
permission_policy = permission_policy
+ usage_count = django_filters.RangeFilter(
+ field_name="usage_count",
+ label=gettext_lazy("Usage count"),
+ widget=django_filters.widgets.RangeWidget(
+ attrs={
+ ... | wagtail/images/views/images.py | 26 | Python | 0.5 | style | 129 | 51 | 51 | false | Added Usage Count Filter | 13,291 | wagtail/wagtail | 16,097 | Python | laymonage | joelwilliam2005 |
UsageCountColumn,
)
from wagtail.admin.utils import get_valid_next_url_from_request, set_query_params
from wagtail.admin.views import generic
from wagtail.images import get_image_model
from wagtail.images.exceptions import InvalidFilterSpecError
from wagtail.images.forms import URLGeneratorForm, get_image_form
from... | The range widget will add a dash `-` between the two inputs. Since we stack the inputs vertically, it looks a bit awkward. Maybe it's better to create a subclass of `SuffixedMultiWidget` and add placeholders to the inputs that indicate they are min/max inputs, similar to how we do it for date ranges:
https://github.... | )
from wagtail.admin.utils import get_valid_next_url_from_request, set_query_params
from wagtail.admin.views import generic
from wagtail.images import get_image_model
from wagtail.images.exceptions import InvalidFilterSpecError
from wagtail.images.forms import URLGeneratorForm, get_image_form
from wagtail.images.models... | @@ -43,6 +44,17 @@
class ImagesFilterSet(BaseMediaFilterSet):
permission_policy = permission_policy
+ usage_count = django_filters.RangeFilter(
+ field_name="usage_count",
+ label=gettext_lazy("Usage count"),
+ widget=django_filters.widgets.RangeWidget( | wagtail/images/views/images.py | 26 | Python | 0.643 | suggestion | 418 | 51 | 51 | false | Added Usage Count Filter | 13,291 | wagtail/wagtail | 16,097 | Python | laymonage | joelwilliam2005 |
import datetime
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import TestCase
from django.urls import reverse
from wagtail.admin.filters import FilteredModelChoiceField
from wagtail.documents import get_document_model
from wagtail... | This test module is in `wagtail.admin` and it should not have a dependency to `wagtail.documents`/`wagtail.images`. The tests for documents and images views should go to those modules (specifically `wagtail.{documents,images}.tests.test_admin_views` like in #13234). | from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import TestCase
from wagtail.admin.filters import FilteredModelChoiceField
from wagtail.test.utils import WagtailTestUtils
User = get_user_model()
class TestFilteredModelChoiceField(... | @@ -1,9 +1,18 @@
+import datetime
+
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.models import Group
from django.test import TestCase
+from django.urls import reverse
from wagtail.admin.filters import FilteredModelChoiceField
+from wagtail.documents import get_... | wagtail/admin/tests/test_filters.py | 13 | Python | 0.643 | suggestion | 266 | 38 | 38 | false | Added Usage Count Filter | 13,291 | wagtail/wagtail | 16,097 | Python | laymonage | joelwilliam2005 |
import { gettext } from '../../utils/gettext';
import { initCommentApp } from '../../components/CommentApp/main';
import { WAGTAIL_CONFIG } from '../../config/wagtailConfig';
const KEYCODE_M = 77;
/**
* Entrypoint loaded when the comments system is in use.
*/
window.comments = (() => {
const commentApp = initCom... | ```suggestion
* shortcut and custom keyboard shortcuts enabled by user in settings.
```
Just a small nitpick. | import { gettext } from '../../utils/gettext';
import { initCommentApp } from '../../components/CommentApp/main';
import { WAGTAIL_CONFIG } from '../../config/wagtailConfig';
const KEYCODE_M = 77;
/**
* Entrypoint loaded when the comments system is in use.
*/
window.comments = (() => {
const commentApp = initCom... | @@ -11,10 +13,15 @@ window.comments = (() => {
/**
* Returns true if the provided keyboard event is using the 'add/focus comment' keyboard
- * shortcut
+ * shortcut and custom keyboard shortcuts enabled by user in settings | client/src/entrypoints/admin/comments.js | 16 | JavaScript | 0.786 | suggestion | 118 | 41 | 41 | false | Handled user keyboard shortcut preference for comments shortcut | 13,313 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
import { gettext } from '../../utils/gettext';
import { initCommentApp } from '../../components/CommentApp/main';
import { WAGTAIL_CONFIG } from '../../config/wagtailConfig';
const KEYCODE_M = 77;
/**
* Entrypoint loaded when the comments system is in use.
*/
window.comments = (() => {
const commentApp = initCom... | Let's check for this first, before we check the key combinations. | import { gettext } from '../../utils/gettext';
import { initCommentApp } from '../../components/CommentApp/main';
import { WAGTAIL_CONFIG } from '../../config/wagtailConfig';
const KEYCODE_M = 77;
/**
* Entrypoint loaded when the comments system is in use.
*/
window.comments = (() => {
const commentApp = initCom... | @@ -11,10 +13,15 @@ window.comments = (() => {
/**
* Returns true if the provided keyboard event is using the 'add/focus comment' keyboard
- * shortcut
+ * shortcut and custom keyboard shortcuts enabled by user in settings
*/
function isCommentShortcut(e) {
- return (e.ctrlKey || e.metaKey) && e.... | client/src/entrypoints/admin/comments.js | 23 | JavaScript | 0.214 | suggestion | 65 | 48 | 48 | false | Handled user keyboard shortcut preference for comments shortcut | 13,313 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
errorMessage.classList.add('error-message');
section.appendChild(errorMessage);
button.click();
await jest.runAllTimersAsync();
expect(document.activeElement).toBe(errorMessage);
});
});
describe('dispatching events before & after focusing', () => {
beforeEach(async () => {
... | Not needed? Or is it on purpose? 🤔 | errorMessage.classList.add('error-message');
section.appendChild(errorMessage);
button.click();
await jest.runAllTimersAsync();
expect(document.activeElement).toBe(errorMessage);
});
});
describe('dispatching events before & after focusing', () => {
beforeEach(async () => {
... | @@ -201,4 +201,78 @@ describe('FocusController', () => {
expect(document.activeElement).toBe(errorMessage);
});
});
+
+ describe('dispatching events before & after focusing', () => {
+ beforeEach(async () => {
+ await setup(
+ `
+ <main>
+ <button
+ type="button"
+ d... | client/src/controllers/FocusController.test.js | 26 | JavaScript | 0.071 | suggestion | 34 | 51 | 51 | false | Add a button to jump to the first validation error in header messages | 13,317 | wagtail/wagtail | 16,097 | Python | thibaudcolas | lb- |
await setup(
`
<main>
<button
type="button"
data-controller="w-focus"
data-action="w-focus#focus"
data-w-focus-target-value=".focus-target"
>
Focus target
</button>
<div class="focus-target">Focus me</div>
</main>`,
// { ident... | nitpick - elsewhere we tend to have an assertion on call stack length or ".toHaveBeenCalled" that would fail a bit more neatly?
```suggestion
expect(focusSpy).toHaveBeenCalled();
const [event] = focusSpy.mock.calls[0];
``` | await setup(
`
<main>
<button
type="button"
data-controller="w-focus"
data-action="w-focus#focus"
data-w-focus-target-value=".focus-target"
>
Focus target
</button>
<div class="focus-target">Focus me</div>
</main>`,
// { ident... | @@ -201,4 +201,78 @@ describe('FocusController', () => {
expect(document.activeElement).toBe(errorMessage);
});
});
+
+ describe('dispatching events before & after focusing', () => {
+ beforeEach(async () => {
+ await setup(
+ `
+ <main>
+ <button
+ type="button"
+ d... | client/src/controllers/FocusController.test.js | 26 | JavaScript | 0.786 | bug | 236 | 51 | 51 | false | Add a button to jump to the first validation error in header messages | 13,317 | wagtail/wagtail | 16,097 | Python | thibaudcolas | lb- |
class TestRevisionDeletion(CommentTestingUtils, TestCase):
fixtures = ["test.json"]
def setUp(self):
super().setUp()
self.revision_3 = self.page.save_revision()
self.old_comment = self.create_comment(self.revision_1)
self.new_comment = self.create_comment(self.revision_3)
... | I'm a bit hesitant to have only unit tests specifically for the `has_valid_contentpath()` method instead of on a higher level where it is actually used, particularly because we end up mostly testing the behaviour of `get_block_by_content_path` in the `CommentableJSONField`... which was written specifically for the test... | from django.contrib.auth import get_user_model
from django.test import TestCase
from wagtail.models import Comment, Page
class CommentTestingUtils:
def setUp(self):
self.page = Page.objects.get(title="Welcome to the Wagtail test site!")
self.revision_1 = self.page.save_revision()
self.rev... | @@ -41,3 +43,66 @@ def test_deleting_most_recent_revision_deletes_created_comments(self):
self.revision_3.delete()
with self.assertRaises(Comment.DoesNotExist):
self.new_comment.refresh_from_db()
+
+
+class TestContentPath(WagtailTestUtils, TestCase): | wagtail/tests/test_comments.py | 26 | Python | 0.643 | suggestion | 1,095 | 51 | 44 | false | Tests for Allow deep contentpath for comments on fields other than StreamField | 13,326 | wagtail/wagtail | 16,097 | Python | laymonage | lasse-cs |
rendered = Template(template).render(Context({"request": self.request}))
soup = self.get_soup(rendered)
meta_tag = soup.find("meta", {"name": "color-scheme"})
self.assertIsNotNone(meta_tag)
self.assertEqual(meta_tag["content"], "light")
class FormattedfieldTagTestCase(SimpleTe... | Make the test class inherit from `WagtailTestUtils` (in addition to `SimpleTestCase`) and use `self.get_soup` instead
```suggestion
return self.get_soup(html).find()
``` |
soup = self.get_soup(rendered)
meta_tag = soup.find("meta", {"name": "color-scheme"})
self.assertIsNotNone(meta_tag)
self.assertEqual(meta_tag["content"], "light")
class FormattedfieldTagTestCase(WagtailTestUtils, SimpleTestCase):
def render_template(self, template, field_name="ti... | @@ -1084,3 +1086,139 @@ def test_light_mode(self):
meta_tag = soup.find("meta", {"name": "color-scheme"})
self.assertIsNotNone(meta_tag)
self.assertEqual(meta_tag["content"], "light")
+
+
+class FormattedfieldTagTestCase(SimpleTestCase):
+ def render_template(self, template, field_name="ti... | wagtail/admin/tests/test_templatetags.py | 26 | Python | 0.786 | suggestion | 182 | 51 | 51 | false | Add support for `attrs` in `formattedfield` tag | 13,335 | wagtail/wagtail | 16,097 | Python | laymonage | lb- |
/**
* Handle the key event by preventing the default action and performng the specified action.
*/
handleKey(event: Event) {
if (event.preventDefault) event.preventDefault();
const targetElement =
this.elementTargets.length > 0 ? this.elementTargets[0] : this.element;
if (this.actionValue ==... | Is there any way to avoid this specific sidebar handling here? It feels like we are making this controller have to do very specific work for this use case, instead of keeping it generic.
Also, a reminder that we have a `forceFocus` util that's better at handling forcing focus as it smooths over a few nuances.
Ide... | this.keyValue = ariaKeyShortcuts;
}
}
}
/**
* Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Event) {
if (event.preventDefault) event.preventDefault();
const targetElement =
this.elementTargets.length > 0 ? this... | @@ -85,15 +96,60 @@ export class KeyboardController extends Controller<
}
/**
- * Handle the key event by preventing the default action and triggering a click on the target element.
+ * Handle the key event by preventing the default action and performng the specified action.
*/
handleKey(event: Event... | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.643 | suggestion | 1,161 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
export class KeyboardController extends Controller<
HTMLButtonElement | HTMLAnchorElement
> {
static targets = ['element'];
static values = {
key: { default: '', type: String },
scope: { default: '', type: String },
action: { default: 'click', type: String },
slim: { default: false, type: Boolean... | Let's try to use a TypeScript Enum for this instead, it's a bit nicer to work with than bare strings. | * <section type="button" data-controller="w-kbd" data-w-kbd-key-value="[">
* Trigger my button with the <kbd>[</kbd> key.
* <button type="button" id="my-button" data-w-kbd-target="element">My Button</button>
* </section>
* ```
*
* @example - trigger a focus instead of a click
* ```html
* <input type="text"... | @@ -57,7 +60,15 @@ export class KeyboardController extends Controller<
declare scopeValue: '' | 'global';
/** Allow an explicit target to be the element that the keyboard activates instead of the controlled element. */
- declare readonly elementTargets: (HTMLButtonElement | HTMLAnchorElement)[];
+ declare rea... | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.571 | suggestion | 101 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
{/* Classes marked important to trump the base input styling set in _forms.scss */}
<input
className={`
${slim || !isVisible ? 'w-hidden' : ''}
!w-pl-[55px]
!w-py-[13px]
!w-subpixel-antialiased
!w-absolute
!w-left-0
... | I think the controller will not need both key-value and aria-keyshortcuts, just one. Probably the aria one. | >
<Icon className="icon--menuitem" name="search" />
</button>
</Tippy>
<label className="w-sr-only" htmlFor="menu-search-q">
{gettext('Search')}
</label>
{/* Classes marked important to trump the base input styling set in _forms.scss */}
... | @@ -116,6 +116,12 @@ export const SearchInput: React.FunctionComponent<SearchInputProps> = ({
name="q"
placeholder={gettext('Search')}
ref={searchInput}
+ data-controller="w-kbd"
+ data-w-kbd-key-value="/" | client/src/components/Sidebar/modules/Search.tsx | 26 | TypeScript | 0.357 | suggestion | 107 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
*/
handleKey(event: Event) {
if (event.preventDefault) event.preventDefault();
const targetElement =
this.elementTargets.length > 0 ? this.elementTargets[0] : this.element;
if (this.actionValue === KeyboardAction.FOCUS) {
this.handleFocus(targetElement as HTMLInputElement);
} else {
... | How come we need to call select.here?
@dhruvipatel14 | }
/**
* Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Event) {
if (event.preventDefault) event.preventDefault();
const targetElement =
this.elementTargets.length > 0 ? this.elementTargets[0] : this.element;
if (this.actionVa... | @@ -85,15 +97,35 @@ export class KeyboardController extends Controller<
}
/**
- * Handle the key event by preventing the default action and triggering a click on the target element.
+ * Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Even... | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.214 | question | 56 | 50 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
/**
* Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Event) {
if (event.preventDefault) event.preventDefault();
const targetElement =
this.elementTargets.length > 0 ? this.elementTargets[0] : this.element;
if (this.actionValue =... | Can we please use the forceFocus util, it will be more robust for focusing on things that may not be an input in the future. | }
}
}
/**
* Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Event) {
if (event.preventDefault) event.preventDefault();
const targetElement =
this.elementTargets.length > 0 ? this.elementTargets[0] : this.element;
if ... | @@ -85,15 +97,35 @@ export class KeyboardController extends Controller<
}
/**
- * Handle the key event by preventing the default action and triggering a click on the target element.
+ * Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Even... | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.429 | suggestion | 125 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
* ```
*/
export class KeyboardController extends Controller<
HTMLButtonElement | HTMLAnchorElement
> {
static targets = ['element'];
static values = {
key: { default: '', type: String },
scope: { default: '', type: String },
action: { default: KeyboardAction.CLICK, type: String },
};
/** Keybo... | Please add a JSDoc above this.
```suggestion
/** Some description here */
declare actionValue: KeyboardAction;
``` | * </section>
* ```
*
* @example - trigger a focus instead of a click
* ```html
* <input type="text" data-controller="w-kbd" data-w-kbd-action-value="focus" data-w-kbd-key-value="x">
* Focus on this input with the <kbd>x</kbd> key.
* </input>
* ```
*/
export class KeyboardController extends Controller<
HTM... | @@ -57,7 +63,13 @@ export class KeyboardController extends Controller<
declare scopeValue: '' | 'global';
/** Allow an explicit target to be the element that the keyboard activates instead of the controlled element. */
- declare readonly elementTargets: (HTMLButtonElement | HTMLAnchorElement)[];
+ declare rea... | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.714 | suggestion | 125 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
}
}
/**
* Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Event) {
if (event.preventDefault) event.preventDefault();
const targetElement =
this.elementTargets.length > 0 ? this.elementTargets[0] : this.element;
if (this.ac... | ```suggestion
* Handle the focus action on target element and if possible select the text in the input.
``` |
if (ariaKeyShortcuts) {
this.keyValue = ariaKeyShortcuts;
}
}
}
/**
* Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Event) {
if (event.preventDefault) event.preventDefault();
const targetElement =
this.e... | @@ -85,15 +97,35 @@ export class KeyboardController extends Controller<
}
/**
- * Handle the key event by preventing the default action and triggering a click on the target element.
+ * Handle the key event by preventing the default action and performing the specified action.
*/
handleKey(event: Even... | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.857 | suggestion | 112 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
* <button type="button" data-controller="w-kbd" data-w-kbd-key="mod+s" data-w-kbd-scope-value="global">Trigger me globally.</button>
* ```
*
* @example - use aria-keyshortcuts (when the key string is compatible with Mousetrap's syntax)
* @see https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attribut... | Let's move the `action` to the top of the values, keep things alpha sorted unless there's a reason why, this helps keep the code maintainable and understood.
Same with the `actionValue`.
I can do this when merging though.
Also, let's default to an empty string, it's simpler and the code will work as is. | * <button type="button" data-controller="w-kbd" data-w-kbd-key-value="mod+s" data-w-kbd-scope-value="global">Trigger me globally.</button>
* ```
*
* @example - use aria-keyshortcuts (when the key string is compatible with Mousetrap's syntax)
* @see https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/At... | @@ -49,6 +55,7 @@ export class KeyboardController extends Controller<
static values = {
key: { default: '', type: String },
scope: { default: '', type: String },
+ action: { default: KeyboardAction.CLICK, type: String }, | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.643 | style | 313 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
import { Controller } from '@hotwired/stimulus';
import Mousetrap from 'mousetrap';
// import with side-effect to add global-bind plugin (see https://github.com/ccampbell/mousetrap/tree/master/plugins/global-bind)
import 'mousetrap/plugins/global-bind/mousetrap-global-bind';
import { WAGTAIL_CONFIG } from '../config/... | I will add an example for focus usage in the examples when merging, also I found a typo where we were not using the value correctly. I can fix this up when merging. | import { Controller } from '@hotwired/stimulus';
import Mousetrap from 'mousetrap';
// import with side-effect to add global-bind plugin (see https://github.com/ccampbell/mousetrap/tree/master/plugins/global-bind)
import 'mousetrap/plugins/global-bind/mousetrap-global-bind';
import { WAGTAIL_CONFIG } from '../config/... | @@ -5,6 +5,12 @@ import Mousetrap from 'mousetrap';
import 'mousetrap/plugins/global-bind/mousetrap-global-bind';
import { WAGTAIL_CONFIG } from '../config/wagtailConfig';
+import { forceFocus } from '../utils/forceFocus';
+
+export enum KeyboardAction {
+ CLICK = 'click',
+ FOCUS = 'focus',
+}
/**
* Adds th... | client/src/controllers/KeyboardController.ts | 16 | TypeScript | 0.357 | nitpick | 164 | 41 | 41 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
* <button type="button" id="my-button" data-w-kbd-target="element">My Button</button>
* </section>
* ```
*/
export class KeyboardController extends Controller<
HTMLButtonElement | HTMLAnchorElement
> {
static targets = ['element'];
static values = {
key: { default: '', type: String },
scope: { defa... | We no longer need this change, let's just make it simple and use `HTMLElement`. I can do this when merging. | * <button type="button" id="my-button" data-w-kbd-target="element">My Button</button>
* </section>
* ```
*
* @example - trigger a focus instead of a click
* ```html
* <input type="text" data-controller="w-kbd" data-w-kbd-action-value="focus" data-w-kbd-key-value="x">
* Focus on this input with the <kbd>x</k... | @@ -57,7 +64,14 @@ export class KeyboardController extends Controller<
declare scopeValue: '' | 'global';
/** Allow an explicit target to be the element that the keyboard activates instead of the controlled element. */
- declare readonly elementTargets: (HTMLButtonElement | HTMLAnchorElement)[];
+ declare rea... | client/src/controllers/KeyboardController.ts | 26 | TypeScript | 0.571 | suggestion | 107 | 51 | 51 | false | Added shortcut to focus on search bar | 13,336 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.