ronantakizawa/codereview-bench huggingface dataset:
Repository: wagtail/wagtail
File: client/src/components/Sidebar/Sidebar.tsx (TypeScript)

Code before:
          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')}
              aria-expanded={slim ? 'false' : 'true'}
              type="button"
              className={`${!slim ? 'w-mr-4' : ''}
                button
                sidebar__collapse-toggle
                w-flex
                w-justify-center
                w-items-center
                hover:w-bg-surface-menu-item-active
                hover:text-white
                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-controller="w-kbd"
              data-w-kbd-key-value="mod+["
              data-w-kbd-scope-value="global"
            >
              <Icon
                name="expand-right"
                className={!collapsed ? '-w-rotate-180' : ''}
              />
            </button>
          </div>

          {renderedModules}
        </div>
      </div>
    </>
  );
};


Review comment (suggestion):
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}
              aria-label={gettext('Toggle sidebar')}
              aria-expanded={slim ? 'false' : 'true'}
              aria-keyshortcuts="["
              type="button"
// ...
```

Code after:
        >
          <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-keyshortcuts="["
              aria-label={gettext('Toggle sidebar')}
              type="button"
              className={`${!slim ? 'w-mr-4' : ''}
                button
                sidebar__collapse-toggle
                w-flex
                w-justify-center
                w-items-center
                hover:w-bg-surface-menu-item-active
                hover:text-white
                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-w-kbd-target={!isMobile ? 'element' : undefined}
            >
              <Icon
                name="expand-right"
                className={!collapsed ? '-w-rotate-180' : ''}
              />
            </button>
          </div>

          {renderedModules}
        </div>
      </div>
    </>
  );
};
Repository: wagtail/wagtail
File: wagtail/admin/panels/model_utils.py (Python)

Code before:
    """
    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 = ObjectList(panels)

    return panel.bind_to_model(model)


def expand_panel_list(model, panels):
    """
    Given a list which may be a mixture of Panel instances and strings (representing field/relation names),
    expand it into a flat list of Panel instances
    """
    result = []
    for panel in panels:
        if isinstance(panel, Panel):
            result.append(panel)

        elif isinstance(panel, PanelPlaceholder):
            real_panel = panel.construct()
            if real_panel:
                result.append(real_panel)

        elif isinstance(panel, str):
            field = model._meta.get_field(panel)
            if isinstance(field, ManyToOneRel):
                from .inline_panel import InlinePanel

                result.append(InlinePanel(panel))
            else:
                result.append(FieldPanel(panel))

        else:
            raise ImproperlyConfigured(
                "Invalid panel definition %r - expected Panel or string, got %r"
                % (panel, type(panel))
            )

    return result


Review comment (suggestion):
Good opportunity to use a walrus operator :=)

```suggestion
            if real_panel := panel.construct()
                result.append(real_panel)
```

Code after:
    """
    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 = ObjectList(panels)

    return panel.bind_to_model(model)


def expand_panel_list(model, panels):
    """
    Given a list which may be a mixture of Panel instances and strings (representing field/relation names),
    expand it into a flat list of Panel instances
    """
    result = []
    for panel in panels:
        if isinstance(panel, Panel):
            result.append(panel)

        elif isinstance(panel, PanelPlaceholder):
            if real_panel := panel.construct():
                result.append(real_panel)

        elif isinstance(panel, str):
            field = model._meta.get_field(panel)
            if isinstance(field, ManyToOneRel):
                from .inline_panel import InlinePanel

                result.append(InlinePanel(panel))
            else:
                result.append(FieldPanel(panel))

        else:
            raise ImproperlyConfigured(
                "Invalid panel definition %r - expected Panel or string, got %r"
                % (panel, type(panel))
            )

    return result
Repository: wagtail/wagtail
File: client/src/components/ComboBox/ComboBox.tsx (TypeScript)

Code before:
            isOpen: state.isOpen,
            highlightedIndex: state.highlightedIndex,
            inputValue: state.inputValue,
          };
        default:
          return changes;
      }
    },

    onInputValueChange: (changes) => {
      const { inputValue: val } = changes;
      if (!val) {
        setInputItems(flatItems);
        return;
      }

      const filtered = findMatches<ComboBoxOption>(
        flatItems,
        getSearchFields,
        val,
      );
      setInputItems(filtered);
      // Always reset the first item to highlighted on filtering, to speed up selection.
      setHighlightedIndex(0);
    },
  });

  const [lastHighlightedIndex, setLastHighlightedIndex] =
    useState(highlightedIndex);

  useEffect(() => {
    if (inputValue) {
      openMenu();
      setInputValue(inputValue);
      const filtered = findMatches<ComboBoxOption>(
        flatItems,
        getSearchFields,
        inputValue,
      );
      setInputItems(filtered);
      // Always reset the first item to highlighted on filtering, to speed up selection.
      setHighlightedIndex(0);
    } else {
      setInputValue('');
      setInputItems(flatItems);
      setHighlightedIndex(-1);
    }
  }, [inputValue]);

  if (
    inputItems[highlightedIndex] &&

Review comment (bug):
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.

Code after:
            isOpen: state.isOpen,
            highlightedIndex: state.highlightedIndex,
            inputValue: state.inputValue,
          };
        default:
          return changes;
      }
    },

    onInputValueChange: (changes) => {
      const { inputValue: val } = changes;
      if (!val) {
        setInputItems(flatItems);
        return;
      }

      const filtered = findMatches<ComboBoxOption>(
        flatItems,
        getSearchFields,
        val,
      );
      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.
      setPreviewedIndex(-1);
    },
  });

  useEffect(() => {
    if (inputValue) {
      openMenu();
      setInputValue(inputValue);
      const filtered = findMatches<ComboBoxOption>(
        flatItems,
        getSearchFields,
        inputValue,
      );
      setInputItems(filtered);
      // Always reset the first item to highlighted on filtering, to speed up selection.
      setHighlightedIndex(0);
    } else {
      setInputValue('');
      setInputItems(flatItems);
      setHighlightedIndex(-1);
    }
  }, [inputValue]);

  const previewedBlock =
    previewedIndex >= 0 ? inputItems[previewedIndex] : null;
Repository: wagtail/wagtail
File: wagtail/contrib/search_promotions/views/reports.py (Python)

Code before:
        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 = ["query_string"]
    filterset_class = SearchTermsReportFilterSet
    default_ordering = "-_hits"
    index_url_name = "wagtailsearchpromotions:search_terms"
    index_results_url_name = "wagtailsearchpromotions:search_terms_results"
    columns = [
        Column("query_string", label=_("Search term(s)"), sort_key="query_string"),
        NumberColumn(
            "_hits",
            label=_("Views"),
            sort_key="_hits",
        ),
    ]
    export_headings = {
        "query_string": _("Search term(s)"),
        "_hits": _("Views"),
    }
    list_export = [
        "query_string",
        "_hits",
    ]

    def get_filterset_kwargs(self):
        kwargs = super().get_filterset_kwargs()
        kwargs["queryset"] = self.get_base_queryset()
        return kwargs

    def get_base_queryset(self):
        return Query.get_most_popular()

    def dispatch(self, request, *args, **kwargs):
        if not self.request.user.is_superuser:
            return permission_denied(request)
        return super().dispatch(request, *args, **kwargs)


Review comment (suggestion):
To keep the diff minimal

```suggestion
        NumberColumn("_hits", label=_("Views"), sort_key="_hits"),
```

Code after:
        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 = ["query_string"]
    filterset_class = SearchTermsReportFilterSet
    default_ordering = "-_hits"
    index_url_name = "wagtailsearchpromotions:search_terms"
    index_results_url_name = "wagtailsearchpromotions:search_terms_results"
    columns = [
        Column("query_string", label=_("Search term(s)"), sort_key="query_string"),
        NumberColumn("_hits", label=_("Views"), sort_key="_hits"),
    ]
    export_headings = {
        "query_string": _("Search term(s)"),
        "_hits": _("Views"),
    }
    list_export = [
        "query_string",
        "_hits",
    ]

    def get_filterset_kwargs(self):
        kwargs = super().get_filterset_kwargs()
        kwargs["queryset"] = self.get_base_queryset()
        return kwargs

    def get_base_queryset(self):
        return Query.get_most_popular()

    def dispatch(self, request, *args, **kwargs):
        if not self.request.user.is_superuser:
            return permission_denied(request)
        return super().dispatch(request, *args, **kwargs)
Repository: wagtail/wagtail
File: client/tailwind.config.js (JavaScript)

Code before:
    },
    fontFamily: {
      sans: 'var(--w-font-sans)',
      mono: 'var(--w-font-mono)',
    },
    fontSize,
    fontWeight,
    lineHeight,
    listStyleType,
    letterSpacing,
    borderRadius,
    borderWidth,
    boxShadow: {
      ...boxShadow,
      none: 'none',
    },
    spacing: {
      ...spacing,
      'slim-header': '50px',
    },
    extend: {
      textAlign: {
        end: 'end',
        left: 'left',
        right: 'right',
      },
      outlineOffset: {
        inside: '-3px',
      },
      transitionProperty: {
        sidebar:
          'inset-inline-start, padding-inline-start, width, transform, margin-top, min-height',
      },
      zIndex: {
        'minimap': '80',
        'header': '100',
        'sidebar': '110',
        'sidebar-toggle': '120',
        'dialog': '130',
      },
      keyframes: {
        'fade-in': {
          '0%': { opacity: 0 },
          '100%': { opacity: 1 },
        },
      },
      animation: {
        'fade-in': 'fade-in 150ms both',
      },
    },
  },

Review comment (suggestion):
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`.

Code after:
    },
    fontFamily: {
      sans: 'var(--w-font-sans)',
      mono: 'var(--w-font-mono)',
    },
    fontSize,
    fontWeight,
    lineHeight,
    listStyleType,
    letterSpacing,
    borderRadius,
    borderWidth,
    boxShadow: {
      ...boxShadow,
      none: 'none',
    },
    spacing: {
      ...spacing,
      'slim-header': '50px',
    },
    extend: {
      outlineOffset: {
        inside: '-3px',
      },
      transitionProperty: {
        sidebar:
          'inset-inline-start, padding-inline-start, width, transform, margin-top, min-height',
      },
      zIndex: {
        'minimap': '80',
        'header': '100',
        'sidebar': '110',
        'sidebar-toggle': '120',
        'dialog': '130',
      },
      keyframes: {
        'fade-in': {
          '0%': { opacity: 0 },
          '100%': { opacity: 1 },
        },
      },
      animation: {
        'fade-in': 'fade-in 150ms both',
      },
    },
  },
  plugins: [
    typeScale,
    vanillaRTL,
    scrollbarThin,
    /**
Repository: wagtail/wagtail
File: wagtail/admin/templatetags/wagtailadmin_tags.py (Python)

Code before:
        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
        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 admin_theme_color_scheme(context):
    """
    Retrives the color-scheme of the active theme for current user.
    """
    user = context["request"].user
    # print('userdwa',user)
    # user.wagtail_userprofile.theme = "light"
    theme_name = (
        user.wagtail_userprofile.theme
        if hasattr(user, "wagtail_userprofile")
        else "light"
    )

    # print("themename:",theme_name)
    if theme_name == "light":
        return "light dark"

    else:
        return "dark light"


@register.simple_tag
def js_translation_strings():
    warn(
        "The `js_translation_strings` template tag will be removed in a future release.",
        category=RemovedInWagtail70Warning,
    )
    return mark_safe(json.dumps(get_js_translation_strings()))


@register.simple_tag
def notification_static(path):

Review comment (suggestion):
```suggestion
```

Let's remove the commented out code in this line and above. 

Code after:
        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
        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 admin_theme_color_scheme(context):
    """
    Retrieves the color-scheme of the active theme for current user.
    """
    user = context["request"].user
    profile = getattr(user, "wagtail_userprofile", None)
    theme_name = profile.theme if profile else "system"
    if theme_name == "system":
        return "dark light"
    return theme_name


@register.simple_tag
def js_translation_strings():
    warn(
        "The `js_translation_strings` template tag will be removed in a future release.",
        category=RemovedInWagtail70Warning,
    )
    return mark_safe(json.dumps(get_js_translation_strings()))


@register.simple_tag
def notification_static(path):
    """
    Variant of the {% static %}` tag for use in notification emails - tries to form
    a full URL using WAGTAILADMIN_BASE_URL if the static URL isn't already a full URL.
    """
    return urljoin(base_url_setting(), static(path))


@register.simple_tag
def versioned_static(path):
Repository: wagtail/wagtail
File: wagtail/admin/tests/test_templatetags.py (Python)

Code before:
        self.profile.save()

        template = """
            {% load wagtailadmin_tags %}
            <body class="{% admin_theme_color_scheme %}">
                {% page_breadcrumbs page 'wagtailadmin_explore' %}
            </body>
        """
        page = Page.objects.get(id=1)
        rendered = Template(template).render(
            Context({"page": page, "request": self.request})
        )

        soup = self.get_soup(rendered)
        body = soup.select_one("body")
        self.assertIsNotNone(body)
        self.assertIn("dark", body["class"])

    def test_light_mode(self):
        self.profile.theme = "light"
        self.profile.save()

        template = """
            {% load wagtailadmin_tags %}
            <body class="{% admin_theme_color_scheme %}">
                {% page_breadcrumbs page 'wagtailadmin_explore' %}
            </body>
        """
        page = Page.objects.get(id=1)
        rendered = Template(template).render(
            Context({"page": page, "request": self.request})
        )

        soup = self.get_soup(rendered)
        body = soup.select_one("body")
        self.assertIsNotNone(body)
        self.assertIn("light", body["class"])


Review comment (suggestion):
```suggestion
```

As above, no need to include the breadcrumbs template tag. 

Code after:
        rendered = Template(template).render(Context({"request": self.request}))

        soup = self.get_soup(rendered)
        meta_tag = soup.find("meta", {"name": "color-scheme"})
        self.assertIsNotNone(meta_tag)
        self.assertEqual(meta_tag["content"], "dark light")

    def test_dark_mode(self):
        self.profile.theme = "dark"
        self.profile.save()

        template = """
            {% load wagtailadmin_tags %}
            <meta name="color-scheme" content="{% admin_theme_color_scheme %}">
        """
        rendered = Template(template).render(Context({"request": self.request}))

        soup = self.get_soup(rendered)
        meta_tag = soup.find("meta", {"name": "color-scheme"})
        self.assertIsNotNone(meta_tag)
        self.assertEqual(meta_tag["content"], "dark")

    def test_light_mode(self):
        self.profile.theme = "light"
        self.profile.save()

        template = """
            {% load wagtailadmin_tags %}
            <meta name="color-scheme" content="{% admin_theme_color_scheme %}">
        """
        rendered = Template(template).render(Context({"request": self.request}))

        soup = self.get_soup(rendered)
        meta_tag = soup.find("meta", {"name": "color-scheme"})
        self.assertIsNotNone(meta_tag)
        self.assertEqual(meta_tag["content"], "light")
Repository: wagtail/wagtail
File: wagtail/admin/tests/test_templatetags.py (Python)

Code before:
            Context({"page": page, "request": self.request})
        )

        soup = self.get_soup(rendered)
        meta_tag = soup.find("meta", {"name": "color-scheme"})
        self.assertIsNotNone(meta_tag)
        self.assertIn("dark", meta_tag["content"])
        self.assertIn("light", meta_tag["content"])

    def test_dark_mode(self):
        self.profile.theme = "dark"
        self.profile.save()

        template = """
            {% load wagtailadmin_tags %}
            <meta name="color-scheme" content="{% admin_theme_color_scheme %}">
        """
        page = Page.objects.get(id=1)
        rendered = Template(template).render(
            Context({"page": page, "request": self.request})
        )

        soup = self.get_soup(rendered)
        meta_tag = soup.find("meta", {"name": "color-scheme"})
        self.assertIsNotNone(meta_tag)
        self.assertIn("dark", meta_tag["content"])

    def test_light_mode(self):
        self.profile.theme = "light"
        self.profile.save()

        template = """
            {% load wagtailadmin_tags %}
            <meta name="color-scheme" content="{% admin_theme_color_scheme %}">
        """
        page = Page.objects.get(id=1)
        rendered = Template(template).render(
            Context({"page": page, "request": self.request})
        )

        soup = self.get_soup(rendered)
        meta_tag = soup.find("meta", {"name": "color-scheme"})
        self.assertIsNotNone(meta_tag)
        self.assertIn("light", meta_tag["content"])


Review comment (suggestion):
```suggestion
        self.assertEqual(meta_tag["content"], "dark")
```

Code after:
        self.assertEqual(meta_tag["content"], "dark light")

    def test_dark_mode(self):
        self.profile.theme = "dark"
        self.profile.save()

        template = """
            {% load wagtailadmin_tags %}
            <meta name="color-scheme" content="{% admin_theme_color_scheme %}">
        """
        rendered = Template(template).render(Context({"request": self.request}))

        soup = self.get_soup(rendered)
        meta_tag = soup.find("meta", {"name": "color-scheme"})
        self.assertIsNotNone(meta_tag)
        self.assertEqual(meta_tag["content"], "dark")

    def test_light_mode(self):
        self.profile.theme = "light"
        self.profile.save()

        template = """
            {% load wagtailadmin_tags %}
            <meta name="color-scheme" content="{% admin_theme_color_scheme %}">
        """
        rendered = Template(template).render(Context({"request": self.request}))

        soup = self.get_soup(rendered)
        meta_tag = soup.find("meta", {"name": "color-scheme"})
        self.assertIsNotNone(meta_tag)
        self.assertEqual(meta_tag["content"], "light")