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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
default_privacy_setting["type"] == BaseViewRestriction.NONE
): # default privacy setting is public no need to do anything
pass
elif default_privacy_setting["type"] == BaseViewRestriction.LOGIN:
PageViewRestriction.objects.create(
page=self.page, restr... | Suggestion: Include what the invalid setting is, so it's easier to debug. | # default privacy setting is public no need to do anything
pass
elif default_privacy_setting["type"] == BaseViewRestriction.LOGIN:
PageViewRestriction.objects.create(
page=self.page,
restriction_type=BaseViewRestriction.LOGIN,
)
... | @@ -182,13 +188,47 @@ def get_view_draft_message_button(self):
def get_view_live_message_button(self):
return messages.button(self.page.url, _("View live"), new_window=False)
+ def set_default_privacy_setting(self):
+ # privacy setting options BaseViewRestriction.RESTRICTION_CHOICES
+ d... | wagtail/admin/views/pages/create.py | 26 | Python | 0.357 | bug | 73 | 51 | 51 | false | Add method to set default privacy option | 12,278 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | smark-1 |
page = Page.objects.get(
path__startswith=self.root_page.path, slug="hello-world"
).specific
self.assertTrue(
PageViewRestriction.objects.filter(
page=page, restriction_type="password"
).count()
== 1
)
SimplePage.g... | Issue: If this test fails part way though, it can corrupt the model. If you need to change how this works, I'd recommend using `unittest.mock` instead. | post_data = {
"title": "New page!",
"content": "Some content",
"slug": "hello-world",
"action-publish": "Publish",
}
self.client.post(
reverse(
"wagtailadmin_pages:add",
args=("tests", "simplepage", self... | @@ -763,6 +763,137 @@ def test_create_simplepage_post_existing_slug(self):
# form should be marked as having unsaved changes for the purposes of the dirty-forms warning
self.assertContains(response, 'data-w-unsaved-force-value="true"')
+ def test_create_default_privacy_page_public(self):
+ ... | wagtail/admin/tests/pages/test_create_page.py | 26 | Python | 0.571 | bug | 151 | 51 | 51 | false | Add method to set default privacy option | 12,278 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | smark-1 |
post_data = {
"title": "New page!",
"content": "Some content",
"slug": "hello-world",
"action-publish": "Publish",
}
def get_default_privacy_setting(self, request):
return {"type": "password", "password": "password"}
SimplePag... | Issue: `self.assertEqual`.
This is the same for a lot of other assertions. |
# Find the page and check it
page = Page.objects.get(
path__startswith=self.root_page.path, slug="hello-world"
).specific
self.assertEqual(
PageViewRestriction.objects.filter(
page=page, restriction_type="login"
).count(),
... | @@ -763,6 +763,137 @@ def test_create_simplepage_post_existing_slug(self):
# form should be marked as having unsaved changes for the purposes of the dirty-forms warning
self.assertContains(response, 'data-w-unsaved-force-value="true"')
+ def test_create_default_privacy_page_public(self):
+ ... | wagtail/admin/tests/pages/test_create_page.py | 26 | Python | 0.357 | suggestion | 77 | 51 | 51 | false | Add method to set default privacy option | 12,278 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | smark-1 |
"slug",
"The slug 'hello-world' is already in use within the parent page",
)
# form should be marked as having unsaved changes for the purposes of the dirty-forms warning
self.assertContains(response, 'data-w-unsaved-force-value="true"')
def test_create_default_priv... | Nit: You should be able to remove the `path` check. Or use `self.root_page.get_children().filter` | post_data = {
"title": "New page!",
"content": "Some content",
"slug": "hello-world",
"action-publish": "Publish",
}
response = self.client.post(
reverse(
"wagtailadmin_pages:add",
args=("tests", "simplep... | @@ -763,6 +763,137 @@ def test_create_simplepage_post_existing_slug(self):
# form should be marked as having unsaved changes for the purposes of the dirty-forms warning
self.assertContains(response, 'data-w-unsaved-force-value="true"')
+ def test_create_default_privacy_page_public(self):
+ ... | wagtail/admin/tests/pages/test_create_page.py | 26 | Python | 0.429 | suggestion | 97 | 51 | 51 | false | Add method to set default privacy option | 12,278 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | smark-1 |
page=self.page,
restriction_type=BaseViewRestriction.PASSWORD,
password=default_privacy_setting["password"],
)
elif default_privacy_setting["type"] == BaseViewRestriction.GROUPS:
# Create a page view restriction for groups
group... | Question: What happens if the user set privacy settings as part of the initial save? Are they kept?
It'd be great to have a test for this. | page=self.page,
restriction_type=BaseViewRestriction.PASSWORD,
password=default_privacy_setting["password"],
)
elif default_privacy_setting["type"] == BaseViewRestriction.GROUPS:
# Create a page view restriction for groups
group... | @@ -182,13 +188,47 @@ def get_view_draft_message_button(self):
def get_view_live_message_button(self):
return messages.button(self.page.url, _("View live"), new_window=False)
+ def set_default_privacy_setting(self):
+ # privacy setting options BaseViewRestriction.RESTRICTION_CHOICES
+ d... | wagtail/admin/views/pages/create.py | 26 | Python | 0.429 | suggestion | 141 | 51 | 51 | false | Add method to set default privacy option | 12,278 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | smark-1 |
self.history_url = reverse(
"wagtailadmin_pages:history",
args=(self.object.pk,),
)
def get_status_templates(self, context):
templates = super().get_status_templates(context)
templates.insert(
-1, "wagtailadmin/shar... | Question: Why is this being removed? | if permissions.can_view_revisions():
self.history_url = reverse(
"wagtailadmin_pages:history",
args=(self.object.pk,),
)
def get_status_templates(self, context):
templates = super().get_status_templates(context)
tem... | @@ -272,9 +272,6 @@ def get_context_data(self, parent_context):
context = super().get_context_data(parent_context)
page = self.object
- if self.parent_page: | wagtail/admin/ui/side_panels.py | 26 | Python | 0.143 | question | 36 | 51 | 51 | false | Add method to set default privacy option | 12,278 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | smark-1 |
context["usage_url_text"] = ngettext(
"Referenced %(count)s time",
"Referenced %(count)s times",
context["usage_count"],
) % {"count": context["usage_count"]}
return context
def get_context_data(self, parent_context):
context = super().get_context... | ```suggestion
if page.get_default_privacy_setting(self.request)["type"] != BaseViewRestriction.NONE:
``` | context = super().get_usage_context()
context["usage_url_text"] = ngettext(
"Referenced %(count)s time",
"Referenced %(count)s times",
context["usage_count"],
) % {"count": context["usage_count"]}
return context
def get_context_data(self, parent_c... | @@ -286,6 +283,19 @@ def get_context_data(self, parent_context):
"unlock_url": reverse("wagtailadmin_pages:unlock", args=(page.id,)),
}
)
+ else:
+ # set is_public context for new pages based on parent page settings and default privacy setting
+ ... | wagtail/admin/ui/side_panels.py | 26 | Python | 0.857 | suggestion | 118 | 51 | 51 | false | Add method to set default privacy option | 12,278 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | smark-1 |
if default_privacy_setting["type"] == BaseViewRestriction.NONE:
# default privacy setting is public no need to do anything
pass
elif default_privacy_setting["type"] == BaseViewRestriction.LOGIN:
PageViewRestriction.objects.create(
page=self.page, restr... | Suggestion: Simplify the exception message, since this should come from an enum.
```suggestion
raise ValueError(
f"Invalid privacy setting {default_privacy_setting.get("type")!r}"
)
``` | if default_privacy_setting["type"] == BaseViewRestriction.NONE:
# default privacy setting is public no need to do anything
pass
elif default_privacy_setting["type"] == BaseViewRestriction.LOGIN:
PageViewRestriction.objects.create(
page=self.page,
... | @@ -182,13 +188,47 @@ def get_view_draft_message_button(self):
def get_view_live_message_button(self):
return messages.button(self.page.url, _("View live"), new_window=False)
+ def set_default_privacy_setting(self):
+ # privacy setting options BaseViewRestriction.RESTRICTION_CHOICES
+ d... | wagtail/admin/views/pages/create.py | 26 | Python | 1 | refactor | 232 | 51 | 51 | false | Add method to set default privacy option | 12,278 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | smark-1 |
self.json_body.body = [("rich_text", RichText("<h2>hello world</h2>"))]
self.json_body.save()
# the body should now be a stream consisting of a single rich_text block
fetched_body = JSONStreamModel.objects.get(id=self.json_body.id).body
self.assertIsInstance(fetched_body, Stream... | Maybe I should also write about the crash or the issue that has been fixed, otherwise the reasoning behind this small change compared to the original test may be unclear to a new reader? | self.json_body.body = [("rich_text", RichText("<h2>hello world</h2>"))]
self.json_body.save()
# the body should now be a stream consisting of a single rich_text block
fetched_body = JSONStreamModel.objects.get(id=self.json_body.id).body
self.assertIsInstance(fetched_body, Stream... | @@ -237,6 +237,22 @@ def test_can_append(self):
self.assertEqual(fetched_body[1].block_type, "text")
self.assertEqual(fetched_body[1].value, "bar")
+ def test_can_append_on_queried_instance(self):
+ # The test is analog to test_can_append(), but instead of working with the
+ # in-me... | wagtail/tests/test_streamfield.py | 26 | Python | 0.429 | bug | 186 | 51 | 51 | false | Fix StreamValue._prefetch_blocks() to skip manually inserted items | 12,322 | wagtail/wagtail | 16,097 | Python | th3hamm0r | th3hamm0r |
del self._bound_blocks[i]
del self._raw_data[i]
def insert(self, i, item):
self._bound_blocks.insert(i, self._construct_stream_child(item))
self._raw_data.insert(i, None)
@cached_property
def raw_data(self):
return StreamValue.RawDataView(self)
def _prefetch_bl... | Should I place a comment above like?
```python
# May be None if inserted with insert()
``` | del self._bound_blocks[i]
del self._raw_data[i]
def insert(self, i, item):
self._bound_blocks.insert(i, self._construct_stream_child(item))
self._raw_data.insert(i, None)
@cached_property
def raw_data(self):
return StreamValue.RawDataView(self)
def _prefetch_bl... | @@ -710,7 +710,9 @@ def _prefetch_blocks(self, type_name):
raw_values = OrderedDict(
(i, raw_item["value"])
for i, raw_item in enumerate(self._raw_data)
- if raw_item["type"] == type_name and self._bound_blocks[i] is None
+ if raw_item | wagtail/blocks/stream_block.py | 26 | Python | 0.643 | suggestion | 93 | 51 | 51 | false | Fix StreamValue._prefetch_blocks() to skip manually inserted items | 12,322 | wagtail/wagtail | 16,097 | Python | th3hamm0r | th3hamm0r |
# the body should now be a stream consisting of a single rich_text block
fetched_body = JSONStreamModel.objects.get(id=self.json_body.id).body
self.assertIsInstance(fetched_body, StreamValue)
self.assertEqual(len(fetched_body), 1)
self.assertIsInstance(fetched_body[0].value, Ric... | How about
```suggestion
# It tests adding data to child blocks that
# have not yet been lazy loaded. This would previously crash.
```
? |
# the body should now be a stream consisting of a single rich_text block
fetched_body = JSONStreamModel.objects.get(id=self.json_body.id).body
self.assertIsInstance(fetched_body, StreamValue)
self.assertEqual(len(fetched_body), 1)
self.assertIsInstance(fetched_body[0].value, Ric... | @@ -237,6 +237,24 @@ def test_can_append(self):
self.assertEqual(fetched_body[1].block_type, "text")
self.assertEqual(fetched_body[1].value, "bar")
+ def test_can_append_on_queried_instance(self):
+ # The test is analog to test_can_append(), but instead of working with the
+ # in-me... | wagtail/tests/test_streamfield.py | 26 | Python | 0.714 | bug | 158 | 51 | 51 | false | Fix StreamValue._prefetch_blocks() to skip manually inserted items | 12,322 | wagtail/wagtail | 16,097 | Python | zerolab | th3hamm0r |
]
def purge_page_from_cache(page, backend_settings=None, backends=None, *, request=None):
urls = _get_page_cached_urls(page, request=request)
purge_urls_from_cache(urls, backend_settings, backends)
def purge_pages_from_cache(
pages, backend_settings=None, backends=None, *, request=None
):
batch ... | Question: Because `get_full_url` is used, could using this request result in the wrong site being used to resolve the URLs hostname? | """
urls = _get_page_cached_urls(page, cache_object)
purge_urls_from_cache(urls, backend_settings, backends)
def purge_pages_from_cache(
pages, backend_settings=None, backends=None, *, cache_object=None
):
"""
Purge multiple pages from the frontend cache.
:param pages: An iterable of page... | @@ -132,36 +132,41 @@ def purge_urls_from_cache(urls, backend_settings=None, backends=None):
backend.purge_batch(urls)
-def _get_page_cached_urls(page):
- page_url = page.full_url
+def _get_page_cached_urls(page, *, request=None):
+ page_url = page.get_full_url(request)
if page_url is None: ... | wagtail/contrib/frontend_cache/utils.py | 26 | Python | 0.571 | bug | 132 | 51 | 51 | false | Frontend cache: Fix n+1 query issues when batch purging page urls | 12,448 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | ababic |
def purge_urls_from_cache(urls, backend_settings=None, backends=None):
"""
Purge multiple URLs from the frontend cache.
:param urls: An iterable of URLs to purge from the cache.
:type urls: iterable of str
:param backend_settings: Optional custom backend settings to use instead of those defined i... | I don't think this should be an opaque "cache object" - the `get_full_url` implementation definitely heavily assumes it's a request. |
:param urls: An iterable of URLs to purge from the cache.
:type urls: iterable of str
:param backend_settings: Optional custom backend settings to use instead of those defined in ``settings.WAGTAILFRONTENDCACHE``.
:type backend_settings: dict, optional
:param backends: Optional list of strings refe... | @@ -132,36 +170,87 @@ def purge_urls_from_cache(urls, backend_settings=None, backends=None):
backend.purge_batch(urls)
-def _get_page_cached_urls(page):
- page_url = page.full_url
+def _get_page_cached_urls(page, cache_object=None): | wagtail/contrib/frontend_cache/utils.py | 26 | Python | 0.571 | performance | 132 | 51 | 51 | false | Frontend cache: Fix n+1 query issues when batch purging page urls | 12,448 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | ababic |
def get_context(self, request, *args, **kwargs):
context = {
PAGE_TEMPLATE_VAR: self,
"self": self,
"request": request,
}
if self.context_object_name:
context[self.context_object_name] = self
return context
def get_preview_contex... | Question: Why the property which uppers the methods? This will create new strings for every request, which seems unnecessary.
Django's [`require_http_methods`](https://docs.djangoproject.com/en/5.1/topics/http/decorators/#django.views.decorators.http.require_http_methods) decorator expects methods to be uppercase - ... | _updated_ids=_updated_ids,
)
update_aliases.alters_data = True
def publish(
self,
revision,
user=None,
changed=True,
log_action=True,
previous_revision=None,
skip_permission_checks=False,
):
return PublishPageRevis... | @@ -2074,6 +2095,14 @@ def get_preview_template(self, request, mode_name):
return self.get_template(request)
def serve(self, request, *args, **kwargs):
+ if request.method not in self.allowed_http_methods_upper: | wagtail/models/__init__.py | 26 | Python | 0.571 | suggestion | 352 | 51 | 51 | false | Allow page types to easily restrict what type of requests they respond to | 12,473 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | ababic |
label = _("Workflow: resume task")
def format_message(self, log_entry):
try:
return _("Resubmitted '%(task)s'. Workflow resumed") % {
"task": log_entry.data["workflow"]["task"]["title"],
}
except (KeyError, TypeError):
... | Issue: It feels surprising that `OPTIONS` methods aren't handled by the page class at all. Could this be moved into `serve`? | except (KeyError, TypeError):
return _("Workflow task rejected. Workflow complete")
@actions.register_action("wagtail.workflow.resume")
class ResumeWorkflowActionFormatter(WorkflowLogFormatter):
label = _("Workflow: resume task")
def format_message(self, log_entry):... | @@ -551,3 +552,14 @@ def format_message(self, log_entry):
}
except (KeyError, TypeError):
return _("Workflow cancelled")
+
+
+@hooks.register("before_serve_page", order=0)
+def serve_options_response(page: Page, request: HttpRequest, *args, **kwargs): | wagtail/wagtail_hooks.py | 26 | Python | 0.714 | question | 124 | 34 | 43 | false | Allow page types to easily restrict what type of requests they respond to | 12,473 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | ababic |
"task": log_entry.data["workflow"]["task"]["title"],
}
except (KeyError, TypeError):
return _("Workflow task resubmitted. Workflow resumed")
@actions.register_action("wagtail.workflow.cancel")
class CancelWorkflowActionFormatter(WorkflowLogFormatt... | Suggestion: Let Django / the app server deal with setting the content length.
```suggestion
``` | label = _("Workflow: resume task")
def format_message(self, log_entry):
try:
return _("Resubmitted '%(task)s'. Workflow resumed") % {
"task": log_entry.data["workflow"]["task"]["title"],
}
except (KeyError, TypeError):
... | @@ -551,3 +552,14 @@ def format_message(self, log_entry):
}
except (KeyError, TypeError):
return _("Workflow cancelled")
+
+
+@hooks.register("before_serve_page", order=0)
+def serve_options_response(page: Page, request: HttpRequest, *args, **kwargs):
+ """Handle respon... | wagtail/wagtail_hooks.py | 26 | Python | 0.571 | suggestion | 98 | 29 | 38 | false | Allow page types to easily restrict what type of requests they respond to | 12,473 | wagtail/wagtail | 16,097 | Python | RealOrangeOne | ababic |
HTTPMethod.HEAD,
HTTPMethod.OPTIONS,
HTTPMethod.PATCH,
HTTPMethod.POST,
HTTPMethod.PUT,
]
@staticmethod
def route_for_request(request: HttpRequest, path: str) -> RouteResult | None:
"""
Find the page route for the given HTTP request object, and URL pa... | Would it be better to only allow GET by default? So that it becomes an opt-in strategy for page types that need to support other methods? | "index_entries",
"latest_revision",
COMMENTS_RELATION_NAME,
]
# Define these attributes early to avoid masking errors. (Issue #3078)
# The canonical definition is in wagtailadmin.panels.
content_panels = []
promote_panels = []
settings_panels = []
# Privacy options ... | @@ -1393,6 +1394,19 @@ class Page(AbstractPage, index.Indexed, ClusterableModel, metaclass=PageBase):
# Privacy options for page
private_page_options = ["password", "groups", "login"]
+ # Allows page types to specify a list of HTTP method names that page instances will
+ # respond to. When the request... | wagtail/models/__init__.py | 26 | Python | 0.571 | question | 137 | 51 | 51 | false | Allow page types to easily restrict what type of requests they respond to | 12,473 | wagtail/wagtail | 16,097 | Python | allcaps | ababic |
def check_request_method(self, request, *args, **kwargs):
"""
Checks the ``method`` attribute of the request against those supported
by the page (as defined by :attr:`allowed_http_methods`) and responds
accordingly.
If supported, ``None`` is returned, and the request is proc... | This kept causing issues, spent about 30mins trying to get this resolved.
This did not work (even though we have Intersphinx configured), any tips @laymonage
```
:attr:`python:http.HTTPMethod.OPTIONS`
```
I also tried importing the `http` module `import http # noqa: F401` but this did not work either.
For... | return self.get_context(request)
def get_template(self, request, *args, **kwargs):
if request.headers.get("x-requested-with") == "XMLHttpRequest":
return self.ajax_template or self.template
else:
return self.template
def get_preview_template(self, request, mode_... | @@ -2095,6 +2116,38 @@ def serve(self, request, *args, **kwargs):
self.get_context(request, *args, **kwargs),
)
+ def check_request_method(self, request, *args, **kwargs):
+ """
+ Checks the ``method`` attribute of the request against those supported
+ by the page (as def... | wagtail/models/__init__.py | 26 | Python | 1 | suggestion | 529 | 51 | 51 | false | Allow page types to easily restrict what type of requests they respond to | 12,473 | wagtail/wagtail | 16,097 | Python | lb- | ababic |
*
* @example As a button to skip to the top of a section
* ```html
* <section>
* <div class="section-top"><h3>Section title</h3></div>
* <p>...lots of content...</p>
* <button type="button" data-controller="w-focus" data-w-focus-target-value=".section-top" data-action="w-focus#focus">Skip to top</button>
... | Note. We should move this logic to the focus method. And add a unit test for the focus target appearing after initial render. | *
* @example As a button to skip to the top of a section
* ```html
* <section>
* <div class="section-top"><h3>Section title</h3></div>
* <p>...lots of content...</p>
* <button type="button" data-controller="w-focus" data-w-focus-target-value=".section-top" data-action="w-focus#focus">Skip to top</button>
... | @@ -0,0 +1,56 @@
+import { Controller } from '@hotwired/stimulus';
+
+import { forceFocus } from '../utils/forceFocus';
+
+/**
+ * Allows a target element (either via `href` or the targetValue as a selector) to be focused.
+ * If the element does not have a `tabindex` attribute, it will be added and removed when the el... | client/src/controllers/FocusController.ts | 26 | TypeScript | 0.429 | refactor | 126 | 39 | 39 | false | Rename `SkipLinkController` to `FocusController`, update unit tests & add story | 12,555 | wagtail/wagtail | 16,097 | Python | lb- | lb- |
import { forceFocus } from './forceFocus';
jest.useFakeTimers();
describe('forceFocus', () => {
it('should focus on the provided element', async () => {
document.body.innerHTML = '<input id="input" type="text" />';
const element = document.getElementById('input');
forceFocus(element);
expect(docum... | Add another test for an element 'just created'. | expect(document.activeElement).toBe(element);
});
it('should add tabIndex to the element if it does not have it', async () => {
document.body.innerHTML =
'<div id="element">CONTENT</div><button id="button" type="button">BUTTON</button>';
const element = document.getElementById('element');
e... | @@ -0,0 +1,44 @@
+import { forceFocus } from './forceFocus';
+
+jest.useFakeTimers();
+
+describe('forceFocus', () => {
+ it('should focus on the provided element', async () => {
+ document.body.innerHTML = '<input id="input" type="text" />';
+
+ const element = document.getElementById('input');
+ forceFocus(... | client/src/utils/forceFocus.test.js | 26 | JavaScript | 0.071 | suggestion | 48 | 45 | 29 | false | Rename `SkipLinkController` to `FocusController`, update unit tests & add story | 12,555 | wagtail/wagtail | 16,097 | Python | lb- | lb- |
import { debounce } from './debounce';
/**
* Trigger a focus on a potentially non-focusable element, awaiting
* for any delays in DOM creation. Smoothly scroll to the element
* if it is not already in view, then trigger a DOM focus.
*
* Once the target element loses focus, the `tabindex` attribute,
* if it was a... | Is there any particular reason why this accepts `Element` rather than `HTMLElement`?
Also, I saw that in `FocusController` we still check whether the element is `null` or not (i.e. `if (target) forceFocus(target)`). If the expectation is that the caller is responsible for the validity of the element, then the util f... | import { debounce } from './debounce';
/**
* Trigger a focus on a potentially non-focusable element, awaiting
* for any delays in DOM creation. Smoothly scroll to the element
* if it is not already in view, then trigger a DOM focus.
*
* Once the target element loses focus, the `tabindex` attribute,
* if it was a... | @@ -0,0 +1,41 @@
+import { debounce } from './debounce';
+
+/**
+ * Trigger a focus on a potentially non-focusable element, awaiting
+ * for any delays in DOM creation. Smoothly scroll to the element
+ * if it is not already in view, then trigger a DOM focus.
+ *
+ * Once the target element loses focus, the `tabindex` ... | client/src/utils/forceFocus.ts | 18 | TypeScript | 0.786 | suggestion | 629 | 42 | 41 | false | Rename `SkipLinkController` to `FocusController`, update unit tests & add story | 12,555 | wagtail/wagtail | 16,097 | Python | laymonage | lb- |
* forceFocus(document.getElementById('my-element') as HTMLElement);
* ```
*/
export const forceFocus = debounce(
(element: Element | null, { preventScroll = false }: FocusOptions = {}) => {
if (!element) return;
if (!element.hasAttribute('tabindex')) {
const handleBlur = () => {
element.remo... | The reason why I raised the comment about the typing of the `element` parameter is because of this `instanceof` check. Doing a runtime `HTMLElement` check to conditionally call the `focus()` method seems strange for a function that's supposed to force focus on (what's supposed to be) an HTML element.
However, I can ... | * forceFocus(document.getElementById('my-element') as HTMLElement);
* ```
*/
export const forceFocus = debounce(
(
element: HTMLElement | SVGElement,
{ preventScroll = false }: FocusOptions = {},
) => {
if (!element.hasAttribute('tabindex')) {
const handleBlur = () => {
element.removeAt... | @@ -0,0 +1,41 @@
+import { debounce } from './debounce';
+
+/**
+ * Trigger a focus on a potentially non-focusable element, awaiting
+ * for any delays in DOM creation. Smoothly scroll to the element
+ * if it is not already in view, then trigger a DOM focus.
+ *
+ * Once the target element loses focus, the `tabindex` ... | client/src/utils/forceFocus.ts | 26 | TypeScript | 1 | refactor | 831 | 30 | 29 | false | Rename `SkipLinkController` to `FocusController`, update unit tests & add story | 12,555 | wagtail/wagtail | 16,097 | Python | laymonage | lb- |
from wagtail.models import Page
from wagtail.test.testapp.models import RestaurantTag
from wagtail.test.utils import WagtailTestUtils
from wagtail.utils.deprecation import (
RemovedInWagtail70Warning,
)
class TestHome(WagtailTestUtils, TestCase):
def setUp(self):
# Login
self.login()
def ... | Would it be better to use BeautifulSoup here so we don't have to assert `class="skiplink button"` and can actually select an element with `id="main"`? | from wagtail.models import Page
from wagtail.test.testapp.models import RestaurantTag
from wagtail.test.utils import WagtailTestUtils
from wagtail.utils.deprecation import (
RemovedInWagtail70Warning,
)
class TestHome(WagtailTestUtils, TestCase):
def setUp(self):
# Login
self.login()
def ... | @@ -31,6 +31,15 @@ def test_simple(self):
self.assertEqual(response.status_code, 200)
self.assertContains(response, "Test Site")
+ def test_accessible_skip_link_exists(self):
+ response = self.client.get(reverse("wagtailadmin_home"))
+ self.assertEqual(response.status_code, 200)
+ ... | wagtail/admin/tests/tests.py | 26 | Python | 0.571 | question | 150 | 51 | 51 | false | Rename `SkipLinkController` to `FocusController`, update unit tests & add story | 12,555 | wagtail/wagtail | 16,097 | Python | laymonage | lb- |
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.http import Http404, JsonResponse
from taggit.models import Tag, TagBase
WAGTAIL_TAGS_AUTOCOMPLETE_LIMIT = getattr(settings, "WAGTAIL_TAGS_AUTOCOMPLETE_LIMIT", 10)
def autocomplete(request, app_name=None, model_nam... | @aayushman-singh for now, as per discussion on https://github.com/wagtail/wagtail/issues/12588 - let's keep this away from being a setting.
However, it may be nice to have this 'constant' pulled out to the top of this file anyway, just without reading from settings.
```suggestion
WAGTAIL_TAGS_AUTOCOMPLETE_LIMIT... | from django.contrib.contenttypes.models import ContentType
from django.http import Http404, JsonResponse
from taggit.models import Tag, TagBase
TAGS_AUTOCOMPLETE_LIMIT = 10
def autocomplete(request, app_name=None, model_name=None):
if app_name and model_name:
try:
content_type = ContentType.o... | @@ -1,7 +1,9 @@
+from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.http import Http404, JsonResponse
from taggit.models import Tag, TagBase
+WAGTAIL_TAGS_AUTOCOMPLETE_LIMIT = getattr(settings, "WAGTAIL_TAGS_AUTOCOMPLETE_LIMIT", 10) | wagtail/admin/views/tags.py | 6 | Python | 0.786 | suggestion | 441 | 31 | 31 | false | Add Wagtail prefix to non-taggit settings | 12,639 | wagtail/wagtail | 16,097 | Python | lb- | aayushman-singh |
import json
import unittest
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from django.core import mail
from django.core.management import call_command
from django.test import TestCase, override_settings
from django.urls import reverse, reverse_lazy
from django.utils.translat... | @aayushman-singh I see what you were intending here but this change will not actually test that there are ten items but just that the import is used to reflect the item limit.
Which means if there's a typo in this value or something else wrong, it will not throw an error in the test.
Instead, we should leave thi... | import json
import unittest
from django.conf import settings
from django.contrib.auth.models import Group, Permission
from django.core import mail
from django.core.management import call_command
from django.test import TestCase, override_settings
from django.urls import reverse, reverse_lazy
from django.utils.translat... | @@ -13,6 +13,7 @@
from wagtail.admin.auth import user_has_any_page_permission
from wagtail.admin.mail import send_mail
from wagtail.admin.menu import MenuItem
+from wagtail.admin.views.tags import WAGTAIL_TAGS_AUTOCOMPLETE_LIMIT | wagtail/admin/tests/tests.py | 16 | Python | 0.643 | bug | 515 | 41 | 41 | false | Add Wagtail prefix to non-taggit settings | 12,639 | wagtail/wagtail | 16,097 | Python | lb- | aayushman-singh |
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.http import Http404, JsonResponse
from taggit.models import Tag, TagBase
WAGTAIL_TAGS_AUTOCOMPLETE_LIMIT = 10
def autocomplete(request, app_name=None, model_name=None):
if app_name and model_name:
try:
... | Do you mind updating this to
```suggestion
TAGS_AUTOCOMPLETE_LIMIT = 10
```
Without the WAGTAIL_ prefix.
If we do add a setting usage in the future we can rename accordingly.
For now it's just an abstracted constant.
Also a reminder to remove the `settings` import as it's no longer used. | from django.contrib.contenttypes.models import ContentType
from django.http import Http404, JsonResponse
from taggit.models import Tag, TagBase
TAGS_AUTOCOMPLETE_LIMIT = 10
def autocomplete(request, app_name=None, model_name=None):
if app_name and model_name:
try:
content_type = ContentType.o... | @@ -1,7 +1,9 @@
+from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.http import Http404, JsonResponse
from taggit.models import Tag, TagBase
+WAGTAIL_TAGS_AUTOCOMPLETE_LIMIT = 10 | wagtail/admin/views/tags.py | 6 | Python | 0.857 | refactor | 306 | 31 | 31 | false | Add Wagtail prefix to non-taggit settings | 12,639 | wagtail/wagtail | 16,097 | Python | lb- | aayushman-singh |
params = self.get_js_init_params(html)
self.assertEqual(
params,
[
"alpha",
"/admin/tag-autocomplete/",
{"allowSpaces": False, "tagLimit": 3, "autocompleteOnly": False},
],
)
@override_settings(TAG_SPACES_A... | This can be simplified with `self.assertWarns()`. We also want to assert the warning message – we can use `self.assertWarnsMessage()` for this. And the deprecation is only raised when `render()` is called, so let's minimise the scope of the context manager's block to be more specific. Finally, I think we should check t... | ):
html = widget.render("tags", None, attrs={"id": "alpha"})
params = self.get_js_init_params(html)
self.assertEqual(
params,
[
"alpha",
"/admin/tag-autocomplete/",
{"allowSpaces": True, "tagLimit": 3, "autocompl... | @@ -552,6 +554,39 @@ def test_tags_help_text_no_spaces_allowed(self):
html,
)
+ @override_settings(WAGTAIL_TAG_SPACES_ALLOWED=False, WAGTAIL_TAG_LIMIT=3)
+ def test_render_js_init_with_legacy_settings(self):
+ """Checks that the 'w-tag' controller attributes are correctly added to t... | wagtail/admin/tests/test_widgets.py | 26 | Python | 0.857 | suggestion | 1,125 | 51 | 51 | false | Add Wagtail prefix to non-taggit settings | 12,639 | wagtail/wagtail | 16,097 | Python | laymonage | aayushman-singh |
self.assertEqual(
help_text, "Tags can only consist of a single word, no spaces allowed."
)
self.assertIn(
"""<p class="help">%s</p>""" % escape(help_text),
html,
)
@override_settings(WAGTAIL_TAG_SPACES_ALLOWED=False, WAGTAIL_TAG_LIMIT=3)
def... | The settings applied doesn't seem to match what the docstring suggests (i.e. they are the new settings, not the legacy ones).
I think rather than separating the methods by the output, i.e. one test for deprecation and one test for the rendered params, we should separate them by setting. This ensures we test the comp... | help_text, "Tags can only consist of a single word, no spaces allowed."
)
self.assertIn(
"""<p class="help">%s</p>""" % escape(help_text),
html,
)
@override_settings(TAG_LIMIT=3)
def test_legacy_tag_limit_setting(self):
widget = widgets.Admin... | @@ -552,6 +554,39 @@ def test_tags_help_text_no_spaces_allowed(self):
html,
)
+ @override_settings(WAGTAIL_TAG_SPACES_ALLOWED=False, WAGTAIL_TAG_LIMIT=3)
+ def test_render_js_init_with_legacy_settings(self):
+ """Checks that the 'w-tag' controller attributes are correctly added to t... | wagtail/admin/tests/test_widgets.py | 26 | Python | 0.857 | suggestion | 1,346 | 51 | 51 | false | Add Wagtail prefix to non-taggit settings | 12,639 | wagtail/wagtail | 16,097 | Python | laymonage | aayushman-singh |
def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
if self.tag_model == Tag:
autocomplete_url = reverse("wagtailadmin_tag_autocomplete")
else:
autocomplete_url = reverse(
"wagtailadmin_tag_model_autocomplete",... | This comment doesn't seem to provide any value
```suggestion
"WAGTAIL_TAG_SPACES_ALLOWED",
``` | def get_context(self, name, value, attrs):
context = super().get_context(name, value, attrs)
if self.tag_model == Tag:
autocomplete_url = reverse("wagtailadmin_tag_autocomplete")
else:
autocomplete_url = reverse(
"wagtailadmin_tag_model_autocomplete",... | @@ -39,21 +42,44 @@ def get_context(self, name, value, attrs):
else:
free_tagging = self.free_tagging
- tag_spaces_allowed = getattr(settings, "TAG_SPACES_ALLOWED", True)
+ if hasattr(settings, "TAG_SPACES_ALLOWED"):
+ warn(
+ "The setting 'TAG_SPACES_ALLO... | wagtail/admin/widgets/tags.py | 26 | Python | 0.714 | suggestion | 111 | 51 | 51 | false | Add Wagtail prefix to non-taggit settings | 12,639 | wagtail/wagtail | 16,097 | Python | laymonage | aayushman-singh |
from django.utils.translation import gettext_lazy as _
from wagtail.compat import AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME
from wagtail.coreutils import safe_md5
delete_user_perm = "{}.delete_{}".format(
AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME.lower()
)
def user_can_delete_user(current_user, user_to_delete):... | ```suggestion
def get_gravatar_url(email, size=50, default_params={"d": "mp"}):
```
Let's put the default `mp` into the default_params here. | from django.utils.translation import gettext_lazy as _
from wagtail.compat import AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME
from wagtail.coreutils import safe_md5
delete_user_perm = "{}.delete_{}".format(
AUTH_USER_APP_LABEL, AUTH_USER_MODEL_NAME.lower()
)
def user_can_delete_user(current_user, user_to_delete):... | @@ -25,24 +27,37 @@ def user_can_delete_user(current_user, user_to_delete):
return True
-def get_gravatar_url(email, size=50):
- default = "mm"
- size = (
- int(size) * 2
- ) # requested at retina size by default and scaled down at point of use with css
+def get_gravatar_url(email, size=50, de... | wagtail/users/utils.py | 26 | Python | 0.714 | suggestion | 145 | 51 | 51 | false | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | lb- | ayaan-qadri |
def get_gravatar_url(email, size=50, default_params={}):
DEFAULT_IMAGE = "mp"
DEFAULT_GRAVATAR_PROVIDER_URL = "www.gravatar.com/avatar"
params = {
"s": int(size)
* 2, # requested at retina size by default and scaled down at point of use with css
"d": DEFAULT_IMAGE,
}
gra... | Then, move this to up above, setting up the base params first, then allowing the params from the url to override this.
```py
params = {
**default_params
# requested at retina size by default and scaled down at point of use with css
"s": int(size) * 2,
}
```
|
def get_gravatar_url(email, size=50, default_params={"d": "mp"}):
"""
See https://gravatar.com/site/implement/images/ for Gravatar image options.
Example usage:
.. code-block:: python
# Basic usage
gravatar_url = get_gravatar_url('user@example.com')
# Customize size and def... | @@ -25,24 +27,37 @@ def user_can_delete_user(current_user, user_to_delete):
return True
-def get_gravatar_url(email, size=50):
- default = "mm"
- size = (
- int(size) * 2
- ) # requested at retina size by default and scaled down at point of use with css
+def get_gravatar_url(email, size=50, de... | wagtail/users/utils.py | 26 | Python | 0.857 | refactor | 300 | 42 | 51 | false | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | lb- | ayaan-qadri |
return True
def get_gravatar_url(email, size=50, default_params={}):
DEFAULT_IMAGE = "mp"
DEFAULT_GRAVATAR_PROVIDER_URL = "www.gravatar.com/avatar"
params = {
"s": int(size)
* 2, # requested at retina size by default and scaled down at point of use with css
"d": DEFAULT_IMAG... | You probably do not need to do this array handling if you use `doseq=True`.
```suggestion
**parse_qs(parsed_url.query),
``` |
return True
def get_gravatar_url(email, size=50, default_params={"d": "mp"}):
"""
See https://gravatar.com/site/implement/images/ for Gravatar image options.
Example usage:
.. code-block:: python
# Basic usage
gravatar_url = get_gravatar_url('user@example.com')
# Custo... | @@ -25,24 +27,37 @@ def user_can_delete_user(current_user, user_to_delete):
return True
-def get_gravatar_url(email, size=50):
- default = "mm"
- size = (
- int(size) * 2
- ) # requested at retina size by default and scaled down at point of use with css
+def get_gravatar_url(email, size=50, de... | wagtail/users/utils.py | 26 | Python | 0.786 | suggestion | 140 | 44 | 51 | false | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | lb- | ayaan-qadri |
"s": int(size)
* 2, # requested at retina size by default and scaled down at point of use with css
"d": DEFAULT_IMAGE,
}
gravatar_provider_url = getattr(
settings, "WAGTAIL_GRAVATAR_PROVIDER_URL", DEFAULT_GRAVATAR_PROVIDER_URL
)
if (not email) or (gravatar_provider_url... | ```suggestion
f"//{parsed_url.netloc}{parsed_url.path}/{email_hash}?{urlencode(params, doseq=True)}"
```
This should encode the URL params back to duplicate values instead of formatting an array.
https://docs.djangoproject.com/en/5.0/ref/utils/#django.utils.http.urlencode
This is based on the Python ur... |
.. code-block:: python
# Basic usage
gravatar_url = get_gravatar_url('user@example.com')
# Customize size and default image
gravatar_url = get_gravatar_url(
'user@example.com',
size=100,
default_params={'d': 'robohash', 'f': 'y'}
)
... | @@ -25,24 +27,37 @@ def user_can_delete_user(current_user, user_to_delete):
return True
-def get_gravatar_url(email, size=50):
- default = "mm"
- size = (
- int(size) * 2
- ) # requested at retina size by default and scaled down at point of use with css
+def get_gravatar_url(email, size=50, de... | wagtail/users/utils.py | 26 | Python | 0.857 | refactor | 644 | 35 | 51 | false | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | lb- | ayaan-qadri |
)
Note: If any parameter in `default_params` also exists in the provider URL,
It will be overridden by the provider URL's query parameter.
```
"""
DEFAULT_GRAVATAR_PROVIDER_URL = "//www.gravatar.com/avatar"
params = {
**default_params,
# requested at retina size by default ... | Let's keep this simple, just prepare the params in one go, if there's no qs to parse, just parse an empty string.
No need to pop/remove `s` this way.
Do not worry about the size edge case, if the developer really wants to use `size`, they will probably know what they are doing and want to do it intentionally.
... | 'user@example.com',
size=100,
default_params={'d': 'robohash', 'f': 'y'}
)
Note:
If any parameter in ``default_params`` also exists in the provider URL,
it will be overridden by the provider URL's query parameter.
"""
gravatar_provider_url = geta... | @@ -25,26 +27,59 @@ def user_can_delete_user(current_user, user_to_delete):
return True
-def get_gravatar_url(email, size=50):
- default = "mp"
- size = (
- int(size) * 2
- ) # requested at retina size by default and scaled down at point of use with css
+def get_gravatar_url(email, size=50, de... | wagtail/users/utils.py | 26 | Python | 1 | bug | 554 | 47 | 44 | false | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | lb- | ayaan-qadri |
Example usage:
```python
# Basic usage
gravatar_url = get_gravatar_url('user@example.com')
# Customize size and default image
gravatar_url = get_gravatar_url(
'user@example.com',
size=100,
default_params={'d': 'robohash', 'f': 'y'}
)
Note: If any parameter in `de... | I would not worry about this change, pulling this out to a variable feels unnecessary. |
Example usage:
.. code-block:: python
# Basic usage
gravatar_url = get_gravatar_url('user@example.com')
# Customize size and default image
gravatar_url = get_gravatar_url(
'user@example.com',
size=100,
default_params={'d': 'robohash', 'f': ... | @@ -25,26 +27,59 @@ def user_can_delete_user(current_user, user_to_delete):
return True
-def get_gravatar_url(email, size=50):
- default = "mp"
- size = (
- int(size) * 2
- ) # requested at retina size by default and scaled down at point of use with css
+def get_gravatar_url(email, size=50, de... | wagtail/users/utils.py | 26 | Python | 0.286 | suggestion | 86 | 51 | 51 | false | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | lb- | ayaan-qadri |
return False
if user_to_delete.is_superuser and not current_user.is_superuser:
# ordinary users may not delete superusers
return False
return True
def get_gravatar_url(email, size=50, default_params={"d": "mp"}):
"""
See https://gravatar.com/site/implement/images/ for Gravata... | move the note to outside the code example.
````suggestion
```
Note: If any parameter in `default_params` also exists in the provider URL,
It will be overridden by the provider URL's query parameter.
````
Also Markdown code examples will not work here, they need to be RST.
See a good example... | return False
if user_to_delete.is_superuser and not current_user.is_superuser:
# ordinary users may not delete superusers
return False
return True
def get_gravatar_url(email, size=50, default_params={"d": "mp"}):
"""
See https://gravatar.com/site/implement/images/ for Gravata... | @@ -25,26 +27,59 @@ def user_can_delete_user(current_user, user_to_delete):
return True
-def get_gravatar_url(email, size=50):
- default = "mp"
- size = (
- int(size) * 2
- ) # requested at retina size by default and scaled down at point of use with css
+def get_gravatar_url(email, size=50, de... | wagtail/users/utils.py | 26 | Python | 0.857 | suggestion | 443 | 51 | 51 | false | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | lb- | ayaan-qadri |
from django.test import TestCase, override_settings
from wagtail.users.utils import get_gravatar_url
class TestGravatar(TestCase):
def test_gravatar_default(self):
# Test with the default settings
self.assertEqual(
get_gravatar_url("something@example.com"),
"//www.gravatar... | These tests are great, thank you for methodically going through every scenario. | "https://robohash.org/avatar/76ebd6fecabc982c205dd056e8f0415a?d=robohash&f=y&s=100",
)
@override_settings(WAGTAIL_GRAVATAR_PROVIDER_URL="https://robohash.org/avatar/")
def test_gravatar_trailing_slash(self):
"""Test with a trailing slash in the URL"""
self.assertEqual(
... | @@ -0,0 +1,74 @@
+from django.test import TestCase, override_settings
+
+from wagtail.users.utils import get_gravatar_url
+
+
+class TestGravatar(TestCase):
+ def test_gravatar_default(self):
+ # Test with the default settings
+ self.assertEqual(
+ get_gravatar_url("something@example.com"),
... | wagtail/users/tests/test_utils.py | 26 | Python | 0.214 | suggestion | 79 | 75 | 27 | false | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | lb- | ayaan-qadri |
from django.test import TestCase, override_settings
from wagtail.users.utils import get_gravatar_url
class TestGravatar(TestCase):
def test_gravatar_default(self):
# Test with the default settings
self.assertEqual(
get_gravatar_url("something@example.com"),
"//www.gravatar... | ```suggestion
""" Test with the default settings. """
```
This is not critical but it might be nice to use the triple quotations for test docs, it makes it a bit easier to read and while we do not use this consistently in the unit tests it's nice to write new tests with this approach. | from django.test import TestCase, override_settings
from wagtail.users.utils import get_gravatar_url
class TestGravatar(TestCase):
def test_gravatar_default(self):
"""Test with the default settings"""
self.assertEqual(
get_gravatar_url("something@example.com"),
"//www.grav... | @@ -0,0 +1,74 @@
+from django.test import TestCase, override_settings
+
+from wagtail.users.utils import get_gravatar_url
+
+
+class TestGravatar(TestCase):
+ def test_gravatar_default(self):
+ # Test with the default settings | wagtail/users/tests/test_utils.py | 8 | Python | 0.857 | suggestion | 298 | 33 | 33 | false | Enhanced get_gravatar_url & added unit test for it | 12,670 | wagtail/wagtail | 16,097 | Python | lb- | ayaan-qadri |
from wagtail.admin.widgets.button import ButtonWithDropdown
from wagtail.search.backends import get_search_backend
from wagtail.search.index import class_is_indexed
from wagtail.utils.utils import flatten_choices
class WagtailAdminTemplateMixin(TemplateResponseMixin, ContextMixin):
"""
Mixin for views that re... | We probably should name this `base_breadcrumbs_items` instead. I initially only followed the existing patterns for `page_title`, `page_subtitle`, and `header_icon` having their respective `get_foo` methods.
I wasn't sure how the API would eventually take shape once we migrated all the views and made the page views u... | from wagtail.admin.widgets.button import ButtonWithDropdown
from wagtail.search.backends import get_search_backend
from wagtail.search.index import class_is_indexed
from wagtail.utils.utils import flatten_choices
class WagtailAdminTemplateMixin(TemplateResponseMixin, ContextMixin):
"""
Mixin for views that re... | @@ -41,9 +41,17 @@ class WagtailAdminTemplateMixin(TemplateResponseMixin, ContextMixin):
page_title = ""
page_subtitle = ""
header_icon = ""
- # Breadcrumbs are opt-in until we have a design that can be consistently applied
- _show_breadcrumbs = False
+
breadcrumbs_items = [{"url": reverse_laz... | wagtail/admin/views/generic/base.py | 26 | Python | 0.643 | refactor | 657 | 51 | 51 | false | Enable breadcrumbs by default and remove `_show_breadcrumbs` | 12,676 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
.dispatchEvent(new MouseEvent('mouseleave')),
);
expect(document.querySelector('header').outerHTML).toEqual(previousHTML);
});
});
describe('save the expanded state of breadcrumbs to local storage', () => {
beforeEach(async () => {
jest.spyOn(Storage.prototype, 'setItem').mockI... | We should not have any console logging left in the code for merging.
```suggestion
``` | .dispatchEvent(new MouseEvent('mouseleave')),
);
expect(document.querySelector('header').outerHTML).toEqual(previousHTML);
});
});
describe('saving and retrieving the opened/closed state from local storage', () => {
beforeEach(async () => {
jest.spyOn(Storage.prototype, 'setIte... | @@ -455,4 +455,49 @@ describe('RevealController', () => {
expect(document.querySelector('header').outerHTML).toEqual(previousHTML);
});
});
+
+ describe('save the expanded state of breadcrumbs to local storage', () => {
+ beforeEach(async () => {
+ jest.spyOn(Storage.prototype, 'setItem').mockIm... | client/src/controllers/RevealController.test.js | 26 | JavaScript | 0.643 | suggestion | 91 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
const storeValue = this.storeValue;
const key = `wagtail:${this.identifier}:opened`;
if (storeValue) {
try {
const storedValue = localStorage.getItem(key);
if (storedValue === storeValue) {
return true;
}
} catch (error) {
// Ignore if localStorage is no... | Maybe we should abstract this out as a getter.
```
get localStorageKey() {
return `wagtail:${this.identifier}:opened`;
}
```
Then. We can use it like.
```
const key = this.localStorageKey
```
| }
/**
* Collects all toggles, those controlled by this controller and any external
* that have an aria-controls references to any content target elements.
*/
get toggles() {
const toggles = this.contentTargets
.map((content) => content.id)
.flatMap((id) =>
Array.from(
d... | @@ -214,6 +217,37 @@ export class RevealController extends Controller<HTMLElement> {
});
}
+ get stored() {
+ const storeValue = this.storeValue;
+ const key = `wagtail:${this.identifier}:opened`;
+ if (storeValue) {
+ try {
+ const storedValue = localStorage.getItem(key);
+ if ... | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.857 | refactor | 214 | 35 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
return true;
}
} catch (error) {
// Ignore if localStorage is not available
}
}
return false;
}
set stored(isOpened) {
const storeValue = this.storeValue;
const key = `wagtail:${this.identifier}:opened`;
try {
if (isOpened) {
localStorage.set... | It looks like we'll need a unit test for this branch, when closing the breadcrumbs. | get toggles() {
const toggles = this.contentTargets
.map((content) => content.id)
.flatMap((id) =>
Array.from(
document.querySelectorAll<HTMLButtonElement>(
`[aria-controls~="${id}"]`,
),
),
)
.concat(...this.toggleTargets);
return Array.... | @@ -214,6 +217,37 @@ export class RevealController extends Controller<HTMLElement> {
});
}
+ get stored() {
+ const storeValue = this.storeValue;
+ const key = `wagtail:${this.identifier}:opened`;
+ if (storeValue) {
+ try {
+ const storedValue = localStorage.getItem(key);
+ if ... | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.214 | nitpick | 84 | 29 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
* @example
* <section data-controller="w-reveal">
* <button type="button" data-action="w-reveal#toggle" data-w-reveal-target="toggle" aria-controls="my-content" type="button">Toggle</button>
* <div id="my-content">CONTENT</div>
* </section>
*/
export class RevealController extends Controller<HTMLElement> {
st... | Let's call this `storageKey`, and instead use it as a key and not a value. After a bit of digging, I can see that this gets a bit confusing and we can add more flexibility if we make this the key.
```suggestion
storageKey: { default: '', type: String },
``` | /**
* Adds the ability to make the controlled element be used as an
* opening/closing (aka collapsing) element.
* Supports, and relies on, correct usage of aria-* attributes.
*
* @see https://w3c.github.io/aria/#aria-expanded
*
* @example - Basic usage
* ```html
* <section data-controller="w-reveal">
* <but... | @@ -28,6 +28,7 @@ export class RevealController extends Controller<HTMLElement> {
closed: { default: false, type: Boolean },
peeking: { default: false, type: Boolean },
peekTarget: { default: '', type: String },
+ store: { default: '', type: String }, | client/src/controllers/RevealController.ts | 26 | TypeScript | 1 | suggestion | 266 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
store: { default: '', type: String },
};
declare closedValue: boolean;
declare peekingValue: boolean;
declare readonly closedClass: string;
declare readonly closedClasses: string[];
declare readonly closeIconClass: string;
declare readonly contentTarget: HTMLElement;
declare readonly contentTarget... | Let's update this to `storageKeyValue` and while we are at it, do you mind doing a bit of a clean up of these, adding JSDoc.
See if this makes sense, this should replace the whole block after the `values` and before the `cleanUpPeekListener`. Also, there's a bunch of items unused, let's just remove them (historicall... | * ```
*/
export class RevealController extends Controller<HTMLElement> {
static classes = [
'closed',
'closeIcon',
'opened',
'openedContent',
'openIcon',
];
static targets = ['content', 'toggle'];
static values = {
closed: { default: false, type: Boolean },
peeking: { default: fa... | @@ -48,6 +49,7 @@ export class RevealController extends Controller<HTMLElement> {
declare readonly openedContentClasses: string[];
declare readonly openIconClass: string;
declare readonly peekTargetValue: string;
+ declare readonly storeValue: string; | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.857 | refactor | 1,704 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
}
if (isInitial) return;
// If we have known toggles, dispatch on those buttons
toggles.forEach((target) => {
this.dispatch('toggled', {
cancelable: false,
detail: {
closed: shouldClose,
},
target,
});
});
}
close() {
this.closedValue =... | This can cause issues as we have a 'peek' mode and a 'fixed' mode, open/close gets called in both.
This means we will be saving the storage state when the user is just 'peeking', and potentially thrashing the local storage in the meantime + causing an edge case if the user refreshes while peeking it will save their ... | */
closedValueChanged(shouldClose: boolean, previouslyClosed?: boolean) {
if (previouslyClosed === shouldClose) return;
const closedClasses = this.closedClasses;
const openedClasses = this.openedClasses;
const contentTargets = this.contentTargets;
const isInitial = previouslyClosed === undefin... | @@ -142,10 +144,12 @@ export class RevealController extends Controller<HTMLElement> {
close() {
this.closedValue = true;
+ this.stored = false;
}
open() {
this.closedValue = false;
+ this.stored = true; | client/src/controllers/RevealController.ts | 26 | TypeScript | 1 | bug | 361 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
content.hidden = false; // eslint-disable-line no-param-reassign
});
this.element.classList.remove(...closedClasses);
this.element.classList.add(...openedClasses);
this.dispatch('opened', { cancelable: false });
}
if (isInitial) return;
// If we have known toggles, dispatch ... | ```suggestion
```
See comment on `open()` method. |
/**
* Handles changes to the closed state,updating element classes and `aria-expanded` attributes accordingly.
*
* Note: This may not trigger when clicking the toggle button if the element is already open in peeking mode.
*/
closedValueChanged(shouldClose: boolean, previouslyClosed?: boolean) {
if ... | @@ -142,10 +144,12 @@ export class RevealController extends Controller<HTMLElement> {
close() {
this.closedValue = true;
+ this.stored = false; | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.571 | suggestion | 53 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
this.closedValue = !this.closedValue;
}
/**
* Collects all toggles, those controlled by this controller and any external
* that have an aria-controls references to any content target elements.
*/
get toggles() {
const toggles = this.contentTargets
.map((content) => content.id)
.flatM... | Let's leave the code a bit cleaner, adding JSdoc items along the way.
```suggestion
/**
* Open (show) the reveal content.
*/
open() {
``` | }
if (isInitial) return;
// If we have known toggles, dispatch on those buttons
toggles.forEach((target) => {
this.dispatch('toggled', {
cancelable: false,
detail: {
closed: shouldClose,
},
target,
});
});
}
/**
* Close (hide) the reveal... | @@ -142,10 +144,12 @@ export class RevealController extends Controller<HTMLElement> {
close() {
this.closedValue = true;
+ this.stored = false;
}
open() { | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.714 | suggestion | 155 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
if (this.peekingValue) {
this.peekingValue = false;
// if peeking and toggle clicked, is already open
// visually set the icon to the opened variant so it can be closed.
this.updateToggleIcon(false);
return;
}
this.closedValue = !this.closedValue;
}
/**
* Collects all t... | ```suggestion
/**
* Close (hide) the reveal content.
*/
close() {
```
let's leave the code a bit better documented. | contentTargets.forEach((content) => {
content.classList.add(...openedContentClasses);
content.hidden = false;
});
this.element.classList.remove(...closedClasses);
this.element.classList.add(...openedClasses);
this.dispatch('opened', { cancelable: false });
}
if (is... | @@ -142,10 +144,12 @@ export class RevealController extends Controller<HTMLElement> {
close() { | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.786 | suggestion | 133 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
/**
* Collects all toggles, those controlled by this controller and any external
* that have an aria-controls references to any content target elements.
*/
get toggles() {
const toggles = this.contentTargets
.map((content) => content.id)
.flatMap((id) =>
Array.from(
docume... | This comment is not at the right line, but we should move our 'storing' into the `toggle` method.
This is because this is the only method that gets called when the user actually clicks something (either to 'keep/fix' it open or to close it). We have a bit of logic to ensure we respect if the mode is peeking and then... | // If we have known toggles, dispatch on those buttons
toggles.forEach((target) => {
this.dispatch('toggled', {
cancelable: false,
detail: {
closed: shouldClose,
},
target,
});
});
}
/**
* Close (hide) the reveal content.
*/
close() {
th... | @@ -142,10 +144,12 @@ export class RevealController extends Controller<HTMLElement> {
close() {
this.closedValue = true;
+ this.stored = false;
}
open() {
this.closedValue = false;
+ this.stored = true;
}
| client/src/controllers/RevealController.ts | 26 | TypeScript | 0.857 | suggestion | 1,242 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
import { Controller } from '@hotwired/stimulus';
/**
* Adds the ability to make the controlled element be used as an
* opening/closing (aka collapsing) element.
* Supports, and relies on, correct usage of aria-* attributes.
*
* @see https://w3c.github.io/aria/#aria-expanded
*
* @example
* <section data-control... | This is super close, however, upon reviewing the code I realised that we are boxing ourselves in a bit with the suggested approach. Sorry for the confusion on my original comments & POC.
Instead, let's generate the local storage key with the `storageKeyValue` as part of the KEY and then the value can be our 'opened'... | if (value === null) return undefined;
return value === RevealState.CLOSED;
} catch (error) {
// Ignore if localStorage is not available.
}
return undefined;
}
/**
* Set the stored state of this controller in the local storage.
* If the store key value is not set, do nothing.
... | @@ -214,6 +218,41 @@ export class RevealController extends Controller<HTMLElement> {
});
}
+ get localStorageKey() {
+ return `wagtail:${this.identifier}:opened`;
+ }
+
+ get stored(): boolean {
+ const storeValue = this.storeValue;
+ const key = this.localStorageKey;
+ if (storeValue) {
+ ... | client/src/controllers/RevealController.ts | 26 | TypeScript | 1 | suggestion | 1,993 | 260 | 31 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
declare readonly hasOpenIconClass: string;
declare readonly hasToggleTarget: boolean;
declare readonly initialClasses: string[];
declare readonly openedClasses: string[];
declare readonly openedContentClasses: string[];
declare readonly openIconClass: string;
declare readonly peekTargetValue: string;
de... | The other thing that's needed is actually reading out the stored value from local storage, not sure if it worked for you but from what I could test, it never actually had any code to read from local storage.
Here's an updated `connect` method that works for me, along with a bit of JSDoc help for us all future devs.
... | closed: { default: false, type: Boolean },
peeking: { default: false, type: Boolean },
peekTarget: { default: '', type: String },
storageKey: { default: '', type: String },
};
declare closedValue: boolean;
declare peekingValue: boolean;
declare readonly closedClasses: string[];
declare reado... | @@ -48,6 +49,7 @@ export class RevealController extends Controller<HTMLElement> {
declare readonly openedContentClasses: string[];
declare readonly openIconClass: string;
declare readonly peekTargetValue: string;
+ declare readonly storeValue: string;
declare readonly toggleTarget: HTMLButtonElement;
de... | client/src/controllers/RevealController.ts | 26 | TypeScript | 1 | suggestion | 2,272 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
import { Application } from '@hotwired/stimulus';
import { RevealController } from './RevealController';
jest.useFakeTimers();
describe('RevealController', () => {
const eventNames = [
'w-reveal:closed',
'w-reveal:opened',
'w-reveal:ready',
'w-reveal:toggled',
];
const events = {};
let appl... | Thanks, these tests will need some refinements with the updated `data-w-breadcrumbs-storage-key-value="header"` DOM.
Also, it's really important we not only test that it writes to LocalStorage but also actually gets read, we should have some assertions in the unit tests that check the content is expanded/opened base... |
await Promise.resolve(toggleButton.click());
expect(toggleButton.getAttribute('aria-expanded')).toBe('true');
expect(Storage.prototype.setItem).toHaveBeenLastCalledWith(
'wagtail:w-breadcrumbs:header-test',
'opened',
);
});
it('should not load and save state if no stor... | @@ -455,4 +455,65 @@ describe('RevealController', () => {
expect(document.querySelector('header').outerHTML).toEqual(previousHTML);
});
});
+
+ describe('save the expanded state of breadcrumbs to local storage', () => {
+ beforeEach(async () => {
+ jest.spyOn(Storage.prototype, 'setItem').mockIm... | client/src/controllers/RevealController.test.js | 26 | JavaScript | 0.643 | nitpick | 400 | 520 | 29 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
describe('save the expanded state of breadcrumbs to local storage', () => {
beforeEach(async () => {
jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {});
jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {});
});
afterEach(() => {
jest.restoreAllMocks()... | This is the test line where it’s currently failing. The `aria-expanded` attribute is not changing, whereas I can see in the browser’s inspector that it does change after clicking the button. | describe('saving and retrieving the opened/closed state from local storage', () => {
beforeEach(async () => {
jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {});
jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {});
});
afterEach(() => {
jest.restoreA... | @@ -455,4 +455,64 @@ describe('RevealController', () => {
expect(document.querySelector('header').outerHTML).toEqual(previousHTML);
});
});
+
+ describe('save the expanded state of breadcrumbs to local storage', () => {
+ beforeEach(async () => {
+ jest.spyOn(Storage.prototype, 'setItem').mockIm... | client/src/controllers/RevealController.test.js | 26 | JavaScript | 0.571 | bug | 190 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | Srishti-j18 | Srishti-j18 |
peekZone.removeEventListener('mouseleave', onMouseLeave);
};
}
// Set initial state based on stored value if available
if (this.storageKeyValue) {
const isStoredAsClosed = this.stored;
if (
typeof isStoredAsClosed === 'boolean' &&
isStoredAsClosed !== this.closedV... | This (else condition )addition is optional, as per https://github.com/wagtail/wagtail/pull/12677#issuecomment-2763302576, Due to this, It's always storing the default state even when the user doesn't interact with it (initially). | ? this.element.closest<HTMLElement>(this.peekTargetValue)
: false;
if (peekZone) {
const onMouseLeave = () => {
if (this.peekingValue) this.close();
this.peekingValue = false;
};
peekZone.addEventListener('mouseleave', onMouseLeave, { passive: true });
this.clean... | @@ -75,6 +84,21 @@ export class RevealController extends Controller<HTMLElement> {
};
}
+ // Set initial state based on stored value if available
+
+ if (this.storageKeyValue) {
+ const isStoredAsClosed = this.stored;
+ if (
+ typeof isStoredAsClosed === 'boolean' &&
+ isStor... | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.5 | suggestion | 229 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | Srishti-j18 | Srishti-j18 |
*/
get localStorageKey() {
const storeValue = this.storageKeyValue;
if (!storeValue) return null;
return ['wagtail', this.identifier, storeValue].join(':');
}
/**
* Get the stored (closed) state of this controller from local storage.
* If the key is not available, return undefined.
*/
g... | ```suggestion
* Set the stored state of this controller in the local storage.
```
We are no longer just storing if closed. | }
});
}
/**
* Prepare a unique local storage key for this controller joined with the store value,
* if not provided then assume we do not want to store the state of this controller.
*/
get localStorageKey() {
const storeValue = this.storageKeyValue;
if (!storeValue) return null;
... | @@ -217,6 +261,51 @@ export class RevealController extends Controller<HTMLElement> {
});
}
+ /**
+ * Prepare a unique local storage key for this controller joined with the store value,
+ * if not provided then assume we do not want to store the state of this controller.
+ */
+ get localStorageKey() ... | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.714 | suggestion | 130 | 47 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
close() {
this.closedValue = true;
}
/**
* Open (show) the reveal content.
*/
open() {
this.closedValue = false;
}
peek() {
if (this.closedValue) {
this.peekingValue = true;
this.open();
}
}
/**
* Toggle the open/closed state of the controller, accounting for the ... | Let's streamline this a bit.
```suggestion
this.stored = this.peekingValue ? false : !this.closedValue;
``` | },
target,
});
});
}
/**
* Close (hide) the reveal content.
*/
close() {
this.closedValue = true;
}
/**
* Open (show) the reveal content.
*/
open() {
this.closedValue = false;
}
peek() {
if (this.closedValue) {
this.peekingValue = true;
th... | @@ -158,7 +194,15 @@ export class RevealController extends Controller<HTMLElement> {
}
}
+ /**
+ * Toggle the open/closed state of the controller, accounting for the peeking state (visually open, but not 'fixed' as open).
+ * The updated closed value will be stored in local storage if available.
+ */
... | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.714 | suggestion | 116 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
export class RevealController extends Controller<HTMLElement> {
static classes = [
'closed',
'closeIcon',
'opened',
'openedContent',
'openIcon',
];
static targets = ['content', 'toggle'];
static values = {
closed: { default: false, type: Boolean },
peeking: { default: false, type: ... | Let's add another example above
```ts
* @example - Saving to local storage
* ```html
* <section data-controller="w-reveal" data-w-reveal-storage-key="saved-state">
* <button type="button" aria-controls="my-content" type="button" data-action="w-reveal#toggle" data-w-reveal-target="toggle">Toggle</button>
... | * <button type="button" data-action="w-reveal#toggle" data-w-reveal-target="toggle" aria-controls="my-content" type="button">Toggle</button>
* <div id="my-content">CONTENT</div>
* </section>
* ```
*
* @example - Saving to local storage
* ```html
* <section data-controller="w-reveal" data-w-reveal-storage-ke... | @@ -32,31 +32,40 @@ export class RevealController extends Controller<HTMLElement> {
closed: { default: false, type: Boolean }, | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.929 | suggestion | 391 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
*/
get stored(): boolean | undefined {
const key = this.localStorageKey;
if (!key) return undefined;
try {
const value = localStorage.getItem(key);
if (value === null) return undefined;
return value === 'closed';
} catch (error) {
// Ignore if localStorage is not available.... | Let's use an enum here and where we use closed, declaring the enum after the imports at the top of the file.
```
enum RevealState {
OPENED = 'opened',
CLOSED = 'closed',
}
``` | if (!storeValue) return null;
return ['wagtail', this.identifier, storeValue].join(':');
}
/**
* Get the stored (closed) state of this controller from local storage.
* If the key is not available, return undefined.
*/
get stored(): boolean | undefined {
const key = this.localStorageKey;
... | @@ -217,6 +261,51 @@ export class RevealController extends Controller<HTMLElement> {
});
}
+ /**
+ * Prepare a unique local storage key for this controller joined with the store value,
+ * if not provided then assume we do not want to store the state of this controller.
+ */
+ get localStorageKey() ... | client/src/controllers/RevealController.ts | 26 | TypeScript | 0.786 | suggestion | 187 | 37 | 44 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
await Promise.resolve(document.querySelector('button').click());
expect(allItemsVisible).toEqual(true);
expect(getIconInfo()).toEqual(['icon icon-cross', '#icon-cross']);
// confirm peeking is unset
expect(
document
.querySelector('.w-breadcrumbs')
.getAttribu... | ```suggestion
describe('saving and retrieving the opened/closed state from local storage', () => {
```
Let's avoid the specific usage in the description if possible, instead focus on behaviour. | await Promise.resolve(document.querySelector('button').click());
expect(allItemsVisible).toEqual(true);
expect(getIconInfo()).toEqual(['icon icon-cross', '#icon-cross']);
// confirm peeking is unset
expect(
document
.querySelector('.w-breadcrumbs')
.getAttribu... | @@ -455,4 +455,69 @@ describe('RevealController', () => {
expect(document.querySelector('header').outerHTML).toEqual(previousHTML);
});
});
+
+ describe('save the expanded state of breadcrumbs to local storage', () => { | client/src/controllers/RevealController.test.js | 26 | JavaScript | 0.857 | suggestion | 200 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
.getAttribute('data-w-breadcrumbs-peeking-value'),
).toEqual('false');
const previousHTML = document.querySelector('header').outerHTML;
// mouseleave on peek target should not do anything now
await Promise.resolve(
document
.querySelector('header')
.dispat... | For the tests below, let's add some tests for asserting the local storage gets called. I can add this when merging though. | .getAttribute('data-w-breadcrumbs-peeking-value'),
).toEqual('false');
const previousHTML = document.querySelector('header').outerHTML;
// mouseleave on peek target should not do anything now
await Promise.resolve(
document
.querySelector('header')
.dispat... | @@ -455,4 +455,69 @@ describe('RevealController', () => {
expect(document.querySelector('header').outerHTML).toEqual(previousHTML);
});
});
+
+ describe('save the expanded state of breadcrumbs to local storage', () => {
+ beforeEach(async () => {
+ jest.spyOn(Storage.prototype, 'setItem').mockIm... | client/src/controllers/RevealController.test.js | 26 | JavaScript | 0.357 | suggestion | 122 | 51 | 51 | false | Save the expanded state of Breadcrumbs to local storage | 12,677 | wagtail/wagtail | 16,097 | Python | lb- | Srishti-j18 |
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"
return {
"shortcuts": {
("actions-common", _("Common actions")): [
(_("Copy"), f"{modifier} + c"),
... | Let's use the same terminology/label as we provide to screen readers for the actual button.
```suggestion
(_("Toggle sidebar"), f"{modifier} + ["),
```

| (_("Superscript"), f"{KEYS.MOD} + ."),
(_("Subscript"), f"{KEYS.MOD} + ,"),
],
}
}
@register.inclusion_tag("wagtailadmin/shared/human_readable_date.html")
def human_readable_date(date, description=None, placement="top"):
if isinstance(date, datetime.datetime... | @@ -1380,6 +1380,7 @@ def keyboard_shortcuts_dialog(context):
("actions-model", _("Actions")): [
(_("Save changes"), f"{modifier} + s"),
(_("Preview"), f"{modifier} + p"),
+ (_("Main menu"), f"{modifier} + ["), | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.857 | suggestion | 299 | 51 | 28 | false | Added keyboard shortcut for main menu | 12,694 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
key: index,
slim,
expandingOrCollapsing,
onHideMobile,
onSearchClick,
currentPath,
navigate,
}),
);
return (
<>
<button
onClick={onClickOpenCloseToggle}
aria-label={gettext('Toggle sidebar')}
aria-expanded={visibleOnMobile ? 'true' : '... | Based on main comment, let's replace this with the 'target' attribute.
```suggestion
data-w-kbd-target={isMobile ? 'element' : undefined}
```
Also, we should set the `aria-keyshortcuts` further up for completeness & accessibility.
```ts
return (
<>
<button
onClick={onClickOp... | key: index,
slim,
expandingOrCollapsing,
onHideMobile,
onSearchClick,
currentPath,
navigate,
}),
);
return (
<>
<button
onClick={onClickOpenCloseToggle}
aria-expanded={visibleOnMobile ? 'true' : 'false'}
aria-keyshortcuts="["
a... | @@ -193,6 +193,9 @@ export const Sidebar: React.FunctionComponent<SidebarProps> = ({
}
type="button"
ref={mobileNavToggleRef}
+ data-controller="w-kbd"
+ data-w-kbd-key-value="mod+["
+ data-w-kbd-scope-value="global" | client/src/components/Sidebar/Sidebar.tsx | 26 | TypeScript | 1 | suggestion | 486 | 51 | 51 | false | Added keyboard shortcut for main menu | 12,694 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
onBlur={onBlurHandler}
>
<div
className={`sm:w-mt-2 ${
slim ? 'w-justify-center' : 'w-justify-end'
} w-flex w-items-center`}
>
<button
onClick={onClickCollapseToggle}
aria-label={gettext('Toggle sidebar'... | Same here, let's use the target approach, making it NOT the target when we are in mobile view.
```suggestion
data-w-kbd-target={!isMobile ? 'element' : undefined}
```
And, let's set `aria-keyshortcuts` further up.
```ts
// ...
<button
onClick={onClickCollapseToggle}... | >
<div
className={`sm:w-mt-2 ${
slim ? 'w-justify-center' : 'w-justify-end'
} w-flex w-items-center`}
>
<button
onClick={onClickCollapseToggle}
aria-expanded={slim ? 'false' : 'true'}
aria-keyshortcu... | @@ -233,6 +236,9 @@ export const Sidebar: React.FunctionComponent<SidebarProps> = ({
hover:opacity-100
more-contrast:w-border-border-interactive-more-contrast-dark-bg
hover:more-contrast:w-border-border-interactive-more-contrast-dark-bg-hover`}
+ data-cont... | client/src/components/Sidebar/Sidebar.tsx | 26 | TypeScript | 1 | suggestion | 508 | 41 | 39 | false | Added keyboard shortcut for main menu | 12,694 | wagtail/wagtail | 16,097 | Python | lb- | dhruvipatel14 |
self.assertSummaryContains("0 Pages")
def test_user_with_no_page_permissions_is_not_shown_panel(self):
self.user.is_superuser = False
self.user.save()
self.assertFalse(PagesSummaryItem(self.request).is_shown())
def test_user_with_limited_page_permissions_summary_links_to_their_... | ```suggestion
page=self.test_page,
``` | from django.contrib.auth.models import Group
from django.test import TestCase
from django.urls import reverse
from wagtail.admin.site_summary import PagesSummaryItem
from wagtail.models import GroupPagePermission, Page, Site
from wagtail.test.testapp.models import SimplePage
from wagtail.test.utils import WagtailTestU... | @@ -79,3 +79,15 @@ def test_user_with_limited_page_permissions_sees_proper_page_count(self):
self.user.save()
self.user.groups.add(self.test_page_group)
self.assertSummaryContains("1 Page")
+
+ def test_user_with_only_unlock_permission_sees_proper_page_count(self):
+ self.user.is_su... | wagtail/admin/tests/test_site_summary.py | 26 | Python | 0.571 | suggestion | 52 | 31 | 87 | false | Fix admin permission UI crash and doc update | 12,735 | wagtail/wagtail | 16,097 | Python | laymonage | unyimeudemy |
).values_list("group", flat=True)
q |= Q(groups__in=add_groups) & Q(pk=instance.owner_id)
return (
get_user_model()
._default_manager.filter(is_active=True)
.filter(q)
.distinct()
)
def users_with_permission_for_instance(
... | As mentioned in https://github.com/wagtail/wagtail/issues/12628#issuecomment-2559800970, while we're here, we should also add the `bulk_delete` permission here to be consistent with other "user has any page permission" checks | ).values_list("group", flat=True)
q |= Q(groups__in=add_groups) & Q(pk=instance.owner_id)
return (
get_user_model()
._default_manager.filter(is_active=True)
.filter(q)
.distinct()
)
def users_with_permission_for_instance(
... | @@ -166,7 +166,7 @@ def instances_with_direct_explore_permission(self, user):
return Page.objects.filter(depth=1)
else:
codenames = self._get_permission_codenames(
- {"add", "change", "publish", "lock"}
+ {"add", "change", "publish", "lock", "unlock"} | wagtail/permission_policies/pages.py | 26 | Python | 0.643 | security | 225 | 51 | 51 | false | Fix admin permission UI crash and doc update | 12,735 | wagtail/wagtail | 16,097 | Python | laymonage | unyimeudemy |
file=fake_file,
created_at=created_at,
)
return document
def test_filter_by_created_at(self):
# Reset the search index
self.search_backend.reset_index()
self.search_backend.add_type(models.Document)
# Add two documents with different creatio... | I haven't run the test myself, but does this test actually fail if `FilterField("created_at")` was not added? I don't see any line in the test that suggests we're searching, filtering, or sorting by `created_at`. Not sure how this test is related to the bug/fix 🤔
Also, I could replicate the bug in #12627 even with... | import unittest
from django.core.files.base import ContentFile
from django.test import TestCase
from django.test.utils import override_settings
from django.urls import reverse
from wagtail.documents import models
from wagtail.test.utils import WagtailTestUtils
@override_settings(_WAGTAILSEARCH_FORCE_AUTO_UPDATE=["e... | @@ -107,3 +105,57 @@ def test_issue_613_on_edit(self):
# Check
self.assertEqual(len(results), 1)
self.assertEqual(results[0].id, document.id)
+
+
+class TestIssue12627(WagtailTestUtils, TestCase):
+ def get_elasticsearch_backend(self):
+ if "elasticsearch" not in settings.WAGTAILSEA... | wagtail/documents/tests/test_search.py | 26 | Python | 0.786 | bug | 617 | 34 | 110 | false | Add created_at as a FilterField to enable sorting in Document search | 12,741 | wagtail/wagtail | 16,097 | Python | laymonage | Srishti-j18 |
# The tag shouldn't be ignored, so the result should be the documents
# that have the "one" tag and "test" in the title.
response = self.get({"tag": "one", "q": "test"})
self.assertEqual(response.context["page_obj"].paginator.count, 2)
def test_search_and_order_by_created_at(self):
... | To ensure the search works, we should create a document that doesn't have the word "good" in the title and make sure it doesn't show up in the results. | # The tag shouldn't be ignored, so the result should be the documents
# that have the "one" tag and "test" in the title.
response = self.get({"tag": "one", "q": "test"})
self.assertEqual(response.context["page_obj"].paginator.count, 2)
def test_search_and_order_by_created_at(self):
... | @@ -371,6 +372,33 @@ def test_tag_filtering_with_search_term(self):
response = self.get({"tag": "one", "q": "test"})
self.assertEqual(response.context["page_obj"].paginator.count, 2)
+ def test_search_and_order_by_created_at(self):
+ # Create Documents
+ doc1 = models.Document.objec... | wagtail/documents/tests/test_admin_views.py | 26 | Python | 0.429 | suggestion | 151 | 51 | 51 | false | Add created_at as a FilterField to enable sorting in Document search | 12,741 | wagtail/wagtail | 16,097 | Python | laymonage | Srishti-j18 |
def test_search_and_order_by_created_at(self):
# Create Documents
doc1 = models.Document.objects.create(title="recent good Document")
doc1.created_at = local_datetime(2024, 1, 1)
doc1.save()
doc2 = models.Document.objects.create(title="latest good Document")
doc2.cre... | This should be `assertEqual`. The `self.assertEqual(documents, [old_doc, doc1, doc2])` a few lines above already ensures the first element is the `old_doc` though, so there's no need to check this
```suggestion
```
It would be more useful if we have another `get()` that uses the descending order (`-created_at`) ... | def test_search_and_order_by_created_at(self):
# Create Documents, change their created_at dates after creation as
# the field has auto_now_add=True
doc1 = models.Document.objects.create(title="recent good Document")
doc1.created_at = local_datetime(2024, 1, 1)
doc1.save()
... | @@ -371,6 +372,33 @@ def test_tag_filtering_with_search_term(self):
response = self.get({"tag": "one", "q": "test"})
self.assertEqual(response.context["page_obj"].paginator.count, 2)
+ def test_search_and_order_by_created_at(self):
+ # Create Documents
+ doc1 = models.Document.objec... | wagtail/documents/tests/test_admin_views.py | 26 | Python | 0.857 | suggestion | 342 | 51 | 51 | false | Add created_at as a FilterField to enable sorting in Document search | 12,741 | wagtail/wagtail | 16,097 | Python | laymonage | Srishti-j18 |
"""
Get the panel to use in the Wagtail admin when editing this model.
"""
if hasattr(model, "edit_handler"):
# use the edit handler specified on the model class
panel = model.edit_handler
else:
panels = extract_panel_definitions_from_model_class(model)
panel = Object... | Good opportunity to use a walrus operator :=)
```suggestion
if real_panel := panel.construct()
result.append(real_panel)
``` | """
Get the panel to use in the Wagtail admin when editing this model.
"""
if hasattr(model, "edit_handler"):
# use the edit handler specified on the model class
panel = model.edit_handler
else:
panels = extract_panel_definitions_from_model_class(model)
panel = Object... | @@ -62,6 +63,11 @@ def expand_panel_list(model, panels):
if isinstance(panel, Panel):
result.append(panel)
+ elif isinstance(panel, PanelPlaceholder):
+ real_panel = panel.construct()
+ if real_panel:
+ result.append(real_panel) | wagtail/admin/panels/model_utils.py | 26 | Python | 0.786 | suggestion | 158 | 45 | 44 | false | Allow page models to extend base Page panel definitions without importing wagtail.admin | 12,750 | wagtail/wagtail | 16,097 | Python | laymonage | gasman |
from warnings import warn
from django.forms.widgets import Widget
from django.utils.safestring import mark_safe
from wagtail.utils.deprecation import RemovedInWagtail70Warning
class WidgetWithScript(Widget):
warn(
"The usage of `WidgetWithScript` hook is deprecated. Use external scripts instead.",
... | Thanks! If this does work for you, then I think this is a bit tricky. I tried adding the following to the bakerydemo project:
```py
from django.forms import widgets
from wagtail.utils.widgets import WidgetWithScript
class CustomTextarea(WidgetWithScript, widgets.Textarea):
pass
```
And I get the foll... | from warnings import warn
from django.forms.widgets import Widget
from django.utils.safestring import mark_safe
from wagtail.utils.deprecation import RemovedInWagtail70Warning
class WidgetWithScript(Widget):
warn(
"The usage of `WidgetWithScript` hook is deprecated. Use external scripts instead.",
... | @@ -10,6 +10,7 @@ class WidgetWithScript(Widget):
warn(
"The usage of `WidgetWithScript` hook is deprecated. Use external scripts instead.",
category=RemovedInWagtail70Warning,
+ stacklevel=2, | wagtail/utils/widgets.py | 13 | Python | 0.857 | suggestion | 1,109 | 38 | 38 | false | fix `stacklevel` in the `warn` call in `WidgetWithScript` | 12,754 | wagtail/wagtail | 16,097 | Python | laymonage | jorenham |
)
html = self.render_component(table)
self.assertHTMLEqual(
html,
"""
<table class="listing">
<thead>
<tr><th>Title</th><th>Sites rooted here</th></tr>
</thead>
<tbody>
<t... | This test is too specific to the column without checking the render result when a search is actually performed. I think we need to have tests in `test_explorer_view` and `test_page_search` to test the intended behaviour. | from django.template import Context, Template
from django.test import RequestFactory, TestCase
from django.utils.html import format_html
from wagtail.admin.ui.tables import (
BaseColumn,
Column,
RelatedObjectsColumn,
Table,
TitleColumn,
)
from wagtail.models import Page, Site
class TestTable(Test... | @@ -369,3 +372,44 @@ def test_table_render(self):
</table>
""",
)
+
+
+class TestPageTypeColumn(TestCase): | wagtail/admin/tests/ui/test_tables.py | 26 | Python | 0.571 | suggestion | 220 | 51 | 372 | false | Stop rendering to content type in search result | 12,784 | wagtail/wagtail | 16,097 | Python | laymonage | Srishti-j18 |
# will be used for a complete view, not just the block. Instead, the
# default preview context uses `{% include_block %}`, which will use
# `get_context`.
return parent_context or {}
def get_preview_template(self, value, context=None):
# We do not fall back to `get_template`... | This is inspired from [Django's `Field.has_default()`](https://github.com/django/django/blob/5a2c1bc07d126ce32efaa157e712a8f3a7457b74/django/db/models/fields/__init__.py#L1014-L1016), but I made it a property so we can easily change the value in `ListBlock.__init__()`.
I'm not sure if this is the best approach, thou... | # will be used for a complete view, not just the block. Instead, the
# default preview context uses `{% include_block %}`, which will use
# `get_context`.
return parent_context or {}
def get_preview_template(self, value, context=None):
# We do not fall back to `get_template`... | @@ -298,6 +298,10 @@ def get_preview_value(self):
return self.normalize(self.meta.preview_value)
return self.get_default()
+ @cached_property
+ def _has_default(self):
+ return getattr(self.meta, "default", None) is not None | wagtail/blocks/base.py | 26 | Python | 0.857 | suggestion | 831 | 51 | 51 | false | Fix `Block.is_previewable` detection on blocks with non-`None` unset default values | 12,828 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
self.assertSetEqual(
{r.title for r in results},
{"JavaScript: The good parts"},
)
def test_lexeme_validation(self):
from wagtail.search.backends.database.mysql.query import Lexeme
with self.assertRaises(ValueError):
Lexeme("")
Lexeme("h... | I'd prefer `assertRaisesMessage` for exceptions that we raise ourselves, to help catch any unintended mistakes in the message (e.g. missing/extra spaces). I'll add them in as I merge, hope that's OK! | self.assertSetEqual(
{r.title for r in results},
{"JavaScript: The good parts"},
)
def test_lexeme_validation(self):
from wagtail.search.backends.database.mysql.query import Lexeme
with self.assertRaisesMessage(ValueError, "Lexeme value cannot be empty."):
... | @@ -143,6 +143,20 @@ def test_autocomplete_with_symbols(self):
{"JavaScript: The good parts"},
)
+ def test_lexeme_validation(self):
+ from wagtail.search.backends.database.mysql.query import Lexeme
+
+ with self.assertRaises(ValueError):
+ Lexeme("")
+
+ Lexem... | wagtail/search/tests/test_mysql_backend.py | 26 | Python | 0.714 | suggestion | 199 | 45 | 51 | false | Validate against invalid characters in Lexeme values | 12,830 | wagtail/wagtail | 16,097 | Python | laymonage | gasman |
isOpen: state.isOpen,
highlightedIndex: state.highlightedIndex,
inputValue: state.inputValue,
};
default:
return changes;
}
},
onInputValueChange: (changes) => {
const { inputValue: val } = changes;
if (!val) {
setInputIt... | I spent a lot of time on this wondering what was the better behavior. In the end I thought being more aggressive about hiding the preview was probably the safer option. | isOpen: state.isOpen,
highlightedIndex: state.highlightedIndex,
inputValue: state.inputValue,
};
default:
return changes;
}
},
onInputValueChange: (changes) => {
const { inputValue: val } = changes;
if (!val) {
setInputIt... | @@ -153,12 +153,11 @@ export default function ComboBox<ComboBoxOption extends ComboBoxItem>({
setInputItems(filtered);
// Always reset the first item to highlighted on filtering, to speed up selection.
setHighlightedIndex(0);
+ // Hide any preview when the user starts typing.
+ setPreview... | client/src/components/ComboBox/ComboBox.tsx | 26 | TypeScript | 0.429 | suggestion | 168 | 51 | 51 | false | Adjust block chooser styles to match latest designs for block previews | 12,835 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
getSearchFields: (item: ComboBoxOption) => (string | null | undefined)[];
onSelect: (change: UseComboboxStateChange<ComboBoxOption>) => void;
noResultsText?: string;
}
/**
* Generic ComboBox component built with downshift, with a 2-column layout.
*/
export default function ComboBox<ComboBoxOption extends Combo... | ```suggestion
const [previewedIndex, setPreviewedIndex] = useState<number>(-1);
``` | getSearchFields: (item: ComboBoxOption) => (string | null | undefined)[];
onSelect: (change: UseComboboxStateChange<ComboBoxOption>) => void;
noResultsText?: string;
}
/**
* Generic ComboBox component built with downshift, with a 2-column layout.
*/
export default function ComboBox<ComboBoxOption extends Combo... | @@ -68,6 +68,7 @@ export default function ComboBox<ComboBoxOption extends ComboBoxItem>({
(category) => category.items || [],
);
const [inputItems, setInputItems] = useState<ComboBoxOption[]>(flatItems);
+ const [previewedIndex, setPreviewedIndex] = useState<number>(); | client/src/components/ComboBox/ComboBox.tsx | 26 | TypeScript | 0.643 | suggestion | 87 | 51 | 51 | false | Adjust block chooser styles to match latest designs for block previews | 12,835 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
isOpen: state.isOpen,
highlightedIndex: state.highlightedIndex,
inputValue: state.inputValue,
};
default:
return changes;
}
},
onInputValueChange: (changes) => {
const { inputValue: val } = changes;
if (!val) {
setInputIt... | ```suggestion
setPreviewedIndex(-1);
``` | isOpen: state.isOpen,
highlightedIndex: state.highlightedIndex,
inputValue: state.inputValue,
};
default:
return changes;
}
},
onInputValueChange: (changes) => {
const { inputValue: val } = changes;
if (!val) {
setInputIt... | @@ -153,12 +153,11 @@ export default function ComboBox<ComboBoxOption extends ComboBoxItem>({
setInputItems(filtered);
// Always reset the first item to highlighted on filtering, to speed up selection.
setHighlightedIndex(0);
+ // Hide any preview when the user starts typing.
+ setPreview... | client/src/components/ComboBox/ComboBox.tsx | 26 | TypeScript | 0.429 | suggestion | 48 | 51 | 51 | false | Adjust block chooser styles to match latest designs for block previews | 12,835 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
// Hide any preview when the user starts typing.
setPreviewedIndex(undefined);
},
});
useEffect(() => {
if (inputValue) {
openMenu();
setInputValue(inputValue);
const filtered = findMatches<ComboBoxOption>(
flatItems,
getSearchFields,
inputValue,
... | ```suggestion
const previewedBlock = previewedIndex >= 0 ? inputItems[previewedIndex] : null;
``` | // Hide any preview when the user starts typing.
setPreviewedIndex(-1);
},
});
useEffect(() => {
if (inputValue) {
openMenu();
setInputValue(inputValue);
const filtered = findMatches<ComboBoxOption>(
flatItems,
getSearchFields,
inputValue,
);
... | @@ -178,15 +177,8 @@ export default function ComboBox<ComboBoxOption extends ComboBoxItem>({
}
}, [inputValue]);
- if (
- inputItems[highlightedIndex] &&
- highlightedIndex !== lastHighlightedIndex
- ) {
- setLastHighlightedIndex(highlightedIndex);
- }
-
const previewedBlock =
- inputItems[h... | client/src/components/ComboBox/ComboBox.tsx | 26 | TypeScript | 0.857 | suggestion | 101 | 51 | 51 | false | Adjust block chooser styles to match latest designs for block previews | 12,835 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
className="w-combobox__option"
>
<div className="w-combobox__option-icon">
{icon}
{/* Support for rich text options using text as an icon (for example "B" for bold). */}
{i... | ```suggestion
? -1
``` | className="w-combobox__option"
>
<div className="w-combobox__option-icon">
{icon}
{/* Support for rich text options using text as an icon (for example "B" for bold). */}
{i... | @@ -283,8 +275,15 @@ export default function ComboBox<ComboBoxOption extends ComboBoxItem>({
<button
className="w-combobox__option-preview"
aria-label={comboBoxPreviewLabel}
+ aria-expanded={previewedIndex === itemIn... | client/src/components/ComboBox/ComboBox.tsx | 26 | TypeScript | 0.571 | suggestion | 56 | 51 | 49 | false | Adjust block chooser styles to match latest designs for block previews | 12,835 | wagtail/wagtail | 16,097 | Python | thibaudcolas | thibaudcolas |
isOpen: state.isOpen,
highlightedIndex: state.highlightedIndex,
inputValue: state.inputValue,
};
default:
return changes;
}
},
onInputValueChange: (changes) => {
const { inputValue: val } = changes;
if (!val) {
setInputIt... | Oops, I just noticed one small bug here: this happens after an `if (!val)` check above that does an early return. This means if you do a filter, preview a block, and then empty out the search box in a single change (e.g. by pressing Cmd+Delete or Cmd+A then Delete), you'll end up with a preview of a different block. | isOpen: state.isOpen,
highlightedIndex: state.highlightedIndex,
inputValue: state.inputValue,
};
default:
return changes;
}
},
onInputValueChange: (changes) => {
const { inputValue: val } = changes;
if (!val) {
setInputIt... | @@ -153,12 +153,11 @@ export default function ComboBox<ComboBoxOption extends ComboBoxItem>({
setInputItems(filtered);
// Always reset the first item to highlighted on filtering, to speed up selection.
setHighlightedIndex(0);
+ // Hide any preview when the user starts typing.
+ setPreview... | client/src/components/ComboBox/ComboBox.tsx | 26 | TypeScript | 0.786 | bug | 317 | 51 | 51 | false | Adjust block chooser styles to match latest designs for block previews | 12,835 | wagtail/wagtail | 16,097 | Python | laymonage | thibaudcolas |
warnings.warn(
f"{self.__class__.__name__}.get_template should accept a 'value' argument as first argument",
RemovedInWagtail70Warning,
)
template = self.get_template(**args)
if not template:
return self.render_basic(value, context=con... | The `page_title` variable is intentionally undocumented as it's not that relevant for configuring the preview, and may be confused for `Page.title`. | f"{self.__class__.__name__}.get_template should accept a 'value' argument as first argument",
RemovedInWagtail70Warning,
)
template = self.get_template(**args)
if not template:
return self.render_basic(value, context=context)
if context i... | @@ -274,26 +273,59 @@ def render(self, value, context=None):
return mark_safe(render_to_string(template, new_context))
def get_preview_context(self, value, parent_context=None):
- # We do not fall back to `get_context` here, because the preview context
- # will be used for a complete view,... | wagtail/blocks/base.py | 26 | Python | 0.571 | suggestion | 148 | 51 | 51 | false | Expand docs for StreamField block previews | 12,840 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
if not template:
return self.render_basic(value, context=context)
if context is None:
new_context = self.get_context(value)
else:
new_context = self.get_context(value, parent_context=dict(context))
return mark_safe(render_to_string(template, new_cont... | This is tricky to explain. I don't think devs necessarily need to know the full details of the code path, but I hope this helps clarify the relation between `get_context` and `get_preview_context`. | return self.render_basic(value, context=context)
if context is None:
new_context = self.get_context(value)
else:
new_context = self.get_context(value, parent_context=dict(context))
return mark_safe(render_to_string(template, new_context))
def get_previe... | @@ -274,26 +273,59 @@ def render(self, value, context=None):
return mark_safe(render_to_string(template, new_context))
def get_preview_context(self, value, parent_context=None):
- # We do not fall back to `get_context` here, because the preview context
- # will be used for a complete view,... | wagtail/blocks/base.py | 26 | Python | 0.5 | suggestion | 197 | 51 | 51 | false | Expand docs for StreamField block previews | 12,840 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
def _has_default(self):
return getattr(self.meta, "default", None) is not None
@cached_property
def is_previewable(self):
# To prevent showing a broken preview if the block preview has not been
# configured, consider the block to be previewable if either:
# - a specific prev... | Now I wonder whether we should've allowed the `preview_value` to be a callable as well, so people can just pass a function instead of having to make a subclass and override the method, especially for blocks like `ImageBlock`. | of :meth:`get_preview_context` above (and not the context returned by that
method itself).
Note that the preview template is used to render a complete HTML page of
the preview, not just an HTML fragment for the block. The method returns
the ``preview_template`` attribute from th... | @@ -274,26 +273,59 @@ def render(self, value, context=None):
return mark_safe(render_to_string(template, new_context))
def get_preview_context(self, value, parent_context=None):
- # We do not fall back to `get_context` here, because the preview context
- # will be used for a complete view,... | wagtail/blocks/base.py | 26 | Python | 0.643 | suggestion | 225 | 51 | 51 | false | Expand docs for StreamField block previews | 12,840 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
# will be used for a complete view, not just the block. Instead, the
# default preview context uses `{% include_block %}`, which will use
# `get_context`.
return parent_context or {}
def get_preview_template(self, value, context=None):
# We do not fall back to `get_template`... | Probably makes sense to name the argument `parent_context` for this reason, but I named it `context` to match the signature of `get_template()`...
(The reason why this is the case, if you're curious, is because the template is used by the preview view. In a typical Django view, the template is resolved before `get_c... | when rendering the block's preview. The ``value`` argument is the value
returned by :meth:`get_preview_value`. The ``parent_context`` argument
contains the following variables:
- ``request``: The current request object.
- ``block_def``: The block instance.
- ``block_clas... | @@ -274,26 +273,59 @@ def render(self, value, context=None):
return mark_safe(render_to_string(template, new_context))
def get_preview_context(self, value, parent_context=None):
- # We do not fall back to `get_context` here, because the preview context
- # will be used for a complete view,... | wagtail/blocks/base.py | 26 | Python | 0.643 | suggestion | 386 | 51 | 51 | false | Expand docs for StreamField block previews | 12,840 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
// Should create a new invisible iframe with the correct URL
let iframes = document.querySelectorAll('iframe');
expect(iframes.length).toEqual(2);
const oldIframe = iframes[0];
const newIframe = iframes[1];
const oldIframeId = oldIframe.id;
expect(oldIframeId).toBeTruthy();
expect(newIfr... | Oops this should've been
```suggestion
top: oldIframe.contentWindow.scrollY,
left: oldIframe.contentWindow.scrollX,
```
(and all the rest of the tests) 🤦 . They pass because the values are both `0` | // Should create a new invisible iframe with the correct URL
let iframes = document.querySelectorAll('iframe');
expect(iframes.length).toEqual(2);
const oldIframe = iframes[0];
const newIframe = iframes[1];
const oldIframeId = oldIframe.id;
expect(oldIframeId).toBeTruthy();
expect(newIfr... | @@ -221,10 +221,11 @@ describe('PreviewController', () => {
expect(newIframe.id).toEqual(oldIframeId);
expect(newIframe.src).toEqual(expectedUrl);
expect(newIframe.getAttribute('style')).toBeNull();
- expect(newIframe.contentWindow.scroll).toHaveBeenCalledWith(
- oldIframe.contentWindow.scrollX,
... | client/src/controllers/PreviewController.test.js | 26 | JavaScript | 0.857 | suggestion | 216 | 51 | 51 | false | Force preview panel scroll behavior to instant to avoid flickering | 12,869 | wagtail/wagtail | 16,097 | Python | laymonage | laymonage |
def clean(self):
cleaned_data = super().clean()
if "slug" in self.cleaned_data:
page_slug = cleaned_data["slug"]
if not Page._slug_is_available(page_slug, self.parent_page, self.instance):
self.add_error(
"slug",
forms.... | @the-r3aper7 let's add a unit test to ensure this logic works and the `comments.js` is included or not.
I would recommend adding something to `wagtail/admin/tests/test_edit_handlers.py` in the class `TestCommentPanel`.
See `test_comments_toggle_enabled` and maybe add the assertion for the js existing there and th... |
def clean(self):
cleaned_data = super().clean()
if "slug" in self.cleaned_data:
page_slug = cleaned_data["slug"]
if not Page._slug_is_available(page_slug, self.parent_page, self.instance):
self.add_error(
"slug",
forms.... | @@ -221,6 +221,15 @@ def clean(self):
)
return cleaned_data
+
+ @property
+ def media(self):
+ media = super().media
+ if self.show_comments_toggle:
+ media += forms.Media(
+ js=["wagtailadmin/js/comments.js"],
+ )
+ return ... | wagtail/admin/forms/pages.py | 26 | Python | 1 | suggestion | 898 | 51 | 51 | false | Removes imports from _editor_js.html | 12,882 | wagtail/wagtail | 16,097 | Python | lb- | saisrikardumpeti |
model = FeatureCompleteToy
url_namespace = "feature_complete_toy"
url_prefix = "feature-complete-toy"
menu_label = "Feature Complete Toys"
icon = "media"
template_prefix = "customprefix/"
index_template_name = "tests/fctoy_index.html"
index_view_class = FeatureCompleteToyIndexView
li... | This isn't needed as the model should already be passed from the viewset | model = FeatureCompleteToy
url_namespace = "feature_complete_toy"
url_prefix = "feature-complete-toy"
menu_label = "Feature Complete Toys"
icon = "media"
template_prefix = "customprefix/"
index_template_name = "tests/fctoy_index.html"
index_view_class = FeatureCompleteToyIndexView
li... | @@ -238,12 +238,20 @@ class FeatureCompleteToyViewSet(ModelViewSet):
]
+class FCToyAlt1InspectView(InspectView):
+ model = FeatureCompleteToy | wagtail/test/testapp/views.py | 26 | Python | 0.286 | suggestion | 72 | 51 | 51 | false | Allow customising InspectView field display value via methods on the view | 12,906 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
value = super().get_value(instance)
if value is None:
return None
return bool(value)
class LiveStatusTagColumn(StatusTagColumn):
"""Represents a live/draft status tag"""
def __init__(self, **kwargs):
super().__init__(
"status_string",
label=... | random thought: it doesn't look like we have test for most of the columns defined here. There are indirect ones throught various viewset/listing tests. Worth creating an issue? | class BooleanColumn(Column):
"""Represents a True/False/None value as a tick/cross/question icon"""
cell_template_name = "wagtailadmin/tables/boolean_cell.html"
def get_value(self, instance):
value = super().get_value(instance)
if value is None:
return None
return bool(... | @@ -299,6 +300,29 @@ def __init__(self, **kwargs):
)
+class LocaleColumn(StatusTagColumn): | wagtail/admin/ui/tables/__init__.py | 26 | Python | 0.357 | question | 176 | 51 | 51 | false | Add Locale column to generic listings | 12,917 | wagtail/wagtail | 16,097 | Python | zerolab | zerolab |
return bool(self.index_results_url or self.search_url)
@cached_property
def filterset_class(self):
# Allow filterset_class to be dynamically constructed from list_filter.
# If the model is translatable, ensure a ``WagtailFilterSet`` subclass
# is returned anyway (even if list_f... | question: considering downstream viewset definitions may or may not include the locale column, I wonder if this should also check that the locale column is `self.columns`? | # with an existing database field.
# By default, use the latest log entry's timestamp, but subclasses may
# override this to e.g. use the latest revision's timestamp instead.
log_model = log_registry.get_log_model_for_model(queryset.model)
# If the log model is not a subclass o... | @@ -150,6 +153,13 @@ def _annotate_queryset_updated_at(self, queryset):
)
return queryset.annotate(_updated_at=models.Subquery(latest_log))
+ def get_base_queryset(self):
+ base_queryset = super().get_base_queryset()
+ if self.i18n_enabled: | wagtail/admin/views/generic/models.py | 26 | Python | 0.571 | question | 171 | 51 | 51 | false | Add Locale column to generic listings | 12,917 | wagtail/wagtail | 16,097 | Python | zerolab | zerolab |
foreign_field_name = ""
for model in relations:
foreign_field = model_class._meta.get_field(model)
foreign_field_name = foreign_field.verbose_name
model_class = foreign_field.related_model
label, attr = label_for_field(field, model_class, return_attr=True)
... | Not super happy with this, but we can't initialise `list_display` on init nor make it a (cached) property, because `ModelViewSet` / `SnippetViewSet` fetch `list_display` directly of the index view class, rather than its instance. And `i18n_enabled` checks both the setting and the fact that the given model is translatab... | **kwargs,
)
@cached_property
def list_display(self):
list_display = ["__str__", UpdatedAtColumn()]
if self.i18n_enabled:
list_display.insert(1, LocaleColumn())
return list_display
@cached_property
def columns(self):
# If not explicitly ov... | @@ -266,6 +276,10 @@ def columns(self):
column = self._get_title_column(field)
else:
column = self._get_custom_column(field)
+
+ if isinstance(column, LocaleColumn) and not self.i18n_enabled: | wagtail/admin/views/generic/models.py | 26 | Python | 0.643 | performance | 322 | 51 | 51 | false | Add Locale column to generic listings | 12,917 | wagtail/wagtail | 16,097 | Python | zerolab | zerolab |
return None
return bool(value)
class LiveStatusTagColumn(StatusTagColumn):
"""Represents a live/draft status tag"""
def __init__(self, **kwargs):
super().__init__(
"status_string",
label=kwargs.pop("label", gettext("Status")),
sort_key=kwargs.po... | To make things consistent with the new designs, I think we should use the `w-status--label` styles to get the following look:
<img width="66" alt="image" src="https://github.com/user-attachments/assets/754ca7f6-2e56-4855-91c0-84d3110b2fd9" />
With the way the `StatusTagColumn`'s template is written, and having `p... | return None
return bool(value)
class LiveStatusTagColumn(StatusTagColumn):
"""Represents a live/draft status tag"""
def __init__(self, **kwargs):
super().__init__(
"status_string",
label=kwargs.pop("label", gettext("Status")),
sort_key=kwargs.po... | @@ -305,6 +306,29 @@ def __init__(self, **kwargs):
)
+class LocaleColumn(StatusTagColumn):
+ """Represents a Locale tag."""
+
+ def __init__(self, **kwargs):
+ super().__init__(
+ "locale_id",
+ label=kwargs.pop("label", gettext("Locale")),
+ sort_key=kwargs.po... | wagtail/admin/ui/tables/__init__.py | 26 | Python | 0.643 | style | 482 | 51 | 51 | false | Add Locale column to generic listings | 12,917 | wagtail/wagtail | 16,097 | Python | laymonage | zerolab |
if callable(self.accessor):
return self.accessor(instance)
else:
try:
return multigetattr(instance, self.accessor)
except AttributeError:
return None
def get_cell_context_data(self, instance, parent_context):
context = supe... | I know I suggested overriding `get_value()`, but looking at the other columns it seems more common to override the displayed value via `get_cell_context_data()`. Perhaps so that you can still access the machine-friendly value (number) by calling `get_value()`. | displayed in a cell of this column
"""
if callable(self.accessor):
return self.accessor(instance)
else:
try:
return multigetattr(instance, self.accessor)
except AttributeError:
return None
def get_cell_context_data(... | @@ -167,6 +168,14 @@ def get_cell_context_data(self, instance, parent_context):
return context
+class NumberColumn(Column):
+ """A specialised column that displays numbers with locale-aware formatting"""
+
+ def get_value(self, instance):
+ value = super().get_value(instance)
+ return i... | wagtail/admin/ui/tables/__init__.py | 26 | Python | 0.571 | suggestion | 260 | 51 | 51 | false | Use locale-appropriate formatting on Hits column in promo search report | 12,930 | wagtail/wagtail | 16,097 | Python | laymonage | bmispelon |
label=_("Date"),
field_name="daily_hits__date",
widget=DateRangePickerWidget,
)
class Meta:
model = Query
fields = []
class SearchTermsReportView(ReportView):
page_title = _("Search terms")
header_icon = "search"
is_searchable = True
search_fields = ["q... | To keep the diff minimal
```suggestion
NumberColumn("_hits", label=_("Views"), sort_key="_hits"),
``` | label=_("Date"),
field_name="daily_hits__date",
widget=DateRangePickerWidget,
)
class Meta:
model = Query
fields = []
class SearchTermsReportView(ReportView):
page_title = _("Search terms")
header_icon = "search"
is_searchable = True
search_fields = ["q... | @@ -31,7 +31,11 @@ class SearchTermsReportView(ReportView):
index_results_url_name = "wagtailsearchpromotions:search_terms_results"
columns = [
Column("query_string", label=_("Search term(s)"), sort_key="query_string"),
- Column("_hits", label=_("Views"), sort_key="_hits"),
+ NumberColu... | wagtail/contrib/search_promotions/views/reports.py | 26 | Python | 0.714 | suggestion | 114 | 49 | 45 | false | Use locale-appropriate formatting on Hits column in promo search report | 12,930 | wagtail/wagtail | 16,097 | Python | laymonage | bmispelon |
from django.utils.timezone import now
from wagtail.coreutils import accepts_kwarg, safe_md5
from .exceptions import EmbedUnsupportedProviderException
from .finders import get_finders
from .models import Embed
def get_finder_for_embed(url, max_width=None, max_height=None):
for finder in get_finders():
i... | ```suggestion
```
No need to add this reference, we can see the commits in the history if needed, especially as this is just an 'internal' clean up. |
from django.utils.timezone import now
from wagtail.coreutils import accepts_kwarg, safe_md5
from .exceptions import EmbedUnsupportedProviderException
from .finders import get_finders
from .models import Embed
def get_finder_for_embed(url, max_width=None, max_height=None):
for finder in get_finders():
i... | @@ -20,7 +20,12 @@ def get_finder_for_embed(url, max_width=None, max_height=None):
raise EmbedUnsupportedProviderException
-def get_embed(url, max_width=None, max_height=None, finder=get_finder_for_embed):
+def get_embed(url, max_width=None, max_height=None):
+ """
+ Retrieve an embed for the given URL u... | wagtail/embeds/embeds.py | 26 | Python | 0.714 | refactor | 152 | 51 | 51 | false | Refactor `get_embed` to Remove `finder` Parameter and Improve Tests | 12,933 | wagtail/wagtail | 16,097 | Python | lb- | JigyasuRajput |
self.assertEqual(finders[0].app_id, "1234567890")
self.assertEqual(finders[0].app_secret, "abcdefghijklmnop")
# omitscript defaults to False
self.assertIs(finders[0].omitscript, False)
class TestEmbeds(TestCase):
def setUp(self):
self.hit_count = 0
def dummy_finder(sel... | ```suggestion
```
No need to add comments like this, thanks though. | self.assertEqual(finders[0].app_id, "1234567890")
self.assertEqual(finders[0].app_secret, "abcdefghijklmnop")
# omitscript defaults to False
self.assertIs(finders[0].omitscript, False)
class TestEmbeds(TestCase):
def setUp(self):
self.hit_count = 0
def dummy_finder(sel... | @@ -147,7 +159,13 @@ def dummy_finder(self, url, max_width=None, max_height=None):
@override_settings(WAGTAILEMBEDS_RESPONSIVE_HTML=True)
def test_get_embed_responsive(self):
- embed = get_embed("www.test.com/1234", max_width=400, finder=self.dummy_finder)
+ # Instead of patching just get_embe... | wagtail/embeds/tests/test_embeds.py | 26 | Python | 0.571 | suggestion | 71 | 51 | 51 | false | Refactor `get_embed` to Remove `finder` Parameter and Improve Tests | 12,933 | wagtail/wagtail | 16,097 | Python | lb- | JigyasuRajput |
},
fontFamily: {
sans: 'var(--w-font-sans)',
mono: 'var(--w-font-mono)',
},
fontSize,
fontWeight,
lineHeight,
listStyleType,
letterSpacing,
borderRadius,
borderWidth,
boxShadow: {
...boxShadow,
none: 'none',
},
spacing: {
...spacing,
... | Since TextAlign is not present in Tailwind's config.js file, I added it here.
Note: I also added `text-align: left`; and `text-align: right`; for future use, in case we need `w-text-left` and `w-text-right`. | },
fontFamily: {
sans: 'var(--w-font-sans)',
mono: 'var(--w-font-mono)',
},
fontSize,
fontWeight,
lineHeight,
listStyleType,
letterSpacing,
borderRadius,
borderWidth,
boxShadow: {
...boxShadow,
none: 'none',
},
spacing: {
...spacing,
... | @@ -105,6 +105,11 @@ module.exports = {
'slim-header': '50px',
},
extend: {
+ textAlign: {
+ end: 'end',
+ left: 'left',
+ right: 'right',
+ }, | client/tailwind.config.js | 26 | JavaScript | 0.643 | suggestion | 210 | 51 | 51 | false | CSP style-src HTML-CSS refactorings | 12,943 | wagtail/wagtail | 16,097 | Python | Srishti-j18 | Srishti-j18 |
import { Controller } from '@hotwired/stimulus';
import { WAGTAIL_CONFIG } from '../config/wagtailConfig';
/**
* Adds the ability for an element to activate a discrete action
* such as clicking the button dynamically from some other event or
* triggering a form submission where the form is created dynamically
* in... | This line still uses the lowercase `t` | import { Controller } from '@hotwired/stimulus';
import { WAGTAIL_CONFIG } from '../config/wagtailConfig';
/**
* Adds the ability for an element to activate a discrete action
* such as clicking the button dynamically from some other event or
* triggering a form submission where the form is created dynamically
* in... | @@ -8,49 +8,60 @@ import { WAGTAIL_CONFIG } from '../config/wagtailConfig';
* in the DOM and then submitted.
*
* @example - triggering a click | client/src/controllers/ActionController.ts | 10 | TypeScript | 0.286 | suggestion | 38 | 35 | 35 | false | Cleanup Stimulus controller imports, JSDoc & linting | 12,952 | wagtail/wagtail | 16,097 | Python | laymonage | lb- |
Retrieves the theme name for the current user.
"""
user = context["request"].user
theme_name = (
user.wagtail_userprofile.theme
if hasattr(user, "wagtail_userprofile")
else "system"
)
contrast_name = (
user.wagtail_userprofile.contrast
if hasattr(user, "wa... | ```suggestion
Retrieves the color-scheme of the active theme for current user.
```
Just a small typo. | Retrieves the theme name for the current user.
"""
user = context["request"].user
theme_name = (
user.wagtail_userprofile.theme
if hasattr(user, "wagtail_userprofile")
else "system"
)
contrast_name = (
user.wagtail_userprofile.contrast
if hasattr(user, "wa... | @@ -708,6 +708,28 @@ 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):
+ """
+ Retrives the color-scheme of the active theme for current user. | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.786 | suggestion | 111 | 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 |
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
... | ```suggestion
```
Let's remove the commented out code in this line and above. | 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,28 @@ 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):
+ """
+ Retrives the color-scheme of the active theme for current user.
+ """
+ ... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.643 | suggestion | 82 | 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 |
)
contrast_name = (
user.wagtail_userprofile.contrast
if hasattr(user, "wagtail_userprofile")
else "system"
)
density_name = (
user.wagtail_userprofile.density
if hasattr(user, "wagtail_userprofile")
else "default"
)
contrast_name = contrast_name.s... | ```suggestion
getattr(user, "wagtail_userprofile", None)
```
We should be able to streamline this, try this out, removing the else block. Then below we would reverse the check, checking for dark first. Meaning we don't need to declare light twice. | )
contrast_name = (
user.wagtail_userprofile.contrast
if hasattr(user, "wagtail_userprofile")
else "system"
)
density_name = (
user.wagtail_userprofile.density
if hasattr(user, "wagtail_userprofile")
else "default"
)
contrast_name = contrast_name.s... | @@ -708,6 +708,28 @@ 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):
+ """
+ Retrives the color-scheme of the active theme for current user.
+ """
+ ... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.857 | suggestion | 261 | 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 |
density_name = (
user.wagtail_userprofile.density
if hasattr(user, "wagtail_userprofile")
else "default"
)
contrast_name = contrast_name.split("_")[0]
return f"w-theme-{theme_name} w-density-{density_name} w-contrast-{contrast_name}"
@register.simple_tag(takes_context=True)
def... | Reverse this logic, if no theme preference is found, we can assume light.
Or.. keep the above defaulting to light not None and keep this logic as is.
| density_name = (
user.wagtail_userprofile.density
if hasattr(user, "wagtail_userprofile")
else "default"
)
contrast_name = contrast_name.split("_")[0]
return f"w-theme-{theme_name} w-density-{density_name} w-contrast-{contrast_name}"
@register.simple_tag(takes_context=True)
def... | @@ -708,6 +708,28 @@ 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):
+ """
+ Retrives the color-scheme of the active theme for current user.
+ """
+ ... | wagtail/admin/templatetags/wagtailadmin_tags.py | 26 | Python | 0.429 | suggestion | 156 | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.