Procházet zdrojové kódy

Merge pull request #23689 from netbox-community/23608-tag-custom-color

Fixes #23608: Preserve custom colors in the color select widget
bctiemann před 17 hodinami
rodič
revize
c164b82fde

+ 35 - 2
netbox/extras/tests/test_forms.py

@@ -9,15 +9,25 @@ from core.choices import ManagedFileRootPathChoices
 from core.events import OBJECT_CREATED
 from core.models import DataSource, ObjectType
 from dcim.forms import SiteForm
+from dcim.forms.filtersets import PowerOutletFilterForm
 from dcim.models import Site
 from extras.choices import CustomFieldTypeChoices, EventRuleActionChoices
 from extras.forms import SavedFilterForm, TableConfigBulkEditForm, TableConfigForm
 from extras.forms.bulk_edit import EventRuleBulkEditForm
 from extras.forms.bulk_import import EventRuleImportForm
 from extras.forms.filtersets import EventRuleFilterForm
-from extras.forms.model_forms import CustomFieldChoiceSetForm, EventRuleForm
+from extras.forms.model_forms import CustomFieldChoiceSetForm, EventRuleForm, TagForm
 from extras.forms.scripts import ScriptFileForm
-from extras.models import CustomField, CustomFieldChoiceSet, EventRule, NotificationGroup, Script, ScriptModule, Webhook
+from extras.models import (
+    CustomField,
+    CustomFieldChoiceSet,
+    EventRule,
+    NotificationGroup,
+    Script,
+    ScriptModule,
+    Tag,
+    Webhook,
+)
 from netbox.event_rules import EventRuleAction, register_event_rule_action
 from netbox.events import EventType
 from netbox.registry import registry
@@ -730,3 +740,26 @@ class EventRuleImportFormTestCase(TestCase):
         self.assertFalse(form.is_valid())
         self.assertIn(NON_FIELD_ERRORS, form.errors)
         self.assertIn('Bad action_data for test', form.errors[NON_FIELD_ERRORS])
+
+
+class TagFormTestCase(TestCase):
+
+    def test_edit_tag_with_custom_color(self):
+        """
+        A Tag with a color outside the predefined ColorChoices can be edited without losing its color.
+        """
+        tag = Tag.objects.create(name='Tag 1', slug='tag-1', color='e20074')
+
+        # The current color must be rendered as the selected option
+        form = TagForm(instance=tag)
+        self.assertInHTML(
+            '<option value="e20074" selected>e20074</option>',
+            str(form['color'])
+        )
+
+    def test_filter_form_ignores_invalid_color(self):
+        """
+        A non-hex color passed to a filter form must not be rendered as an option.
+        """
+        form = PowerOutletFilterForm(data={'color': 'ff0000;background:url(x)'})
+        self.assertNotIn('background:url', str(form['color']))

Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 0
netbox/project-static/dist/netbox.js


Rozdílová data souboru nebyla zobrazena, protože soubor je příliš velký
+ 0 - 0
netbox/project-static/dist/netbox.js.map


+ 3 - 1
netbox/project-static/src/select/static.ts

@@ -35,8 +35,10 @@ export function initStaticSelects(): void {
 // Initialize color selection fields
 export function initColorSelects(): void {
   function renderColor(item: TomOption, escape: typeof escape_html) {
+    // Only hex RGB values are safe to inject into the inline style
+    const color = /^[0-9a-f]{6}$/i.test(item.value) ? item.value : '';
     return `<div><span class="dropdown-item-indicator color-label" style="background-color: #${escape(
-      item.value,
+      color,
     )}"></span> ${escape(item.text)}</div>`;
   }
 

+ 11 - 0
netbox/utilities/forms/widgets/select.py

@@ -1,6 +1,7 @@
 from django import forms
 
 from netbox.choices import ColorChoices
+from utilities.validators import ColorValidator
 
 from ..utils import add_blank_choice
 
@@ -94,6 +95,16 @@ class ColorSelect(forms.Select):
         super().__init__(*args, **kwargs)
         self.attrs['class'] = 'color-select'
 
+    def optgroups(self, name, value, attrs=None):
+        groups = super().optgroups(name, value, attrs)
+        # Render a valid custom (non-predefined) color as a selected option so it isn't lost on submission
+        color = value[0] if value else None
+        if color and ColorValidator.regex.fullmatch(color):
+            if not any(option['selected'] for _, options, _ in groups for option in options):
+                index = len(groups)
+                groups.append((None, [self.create_option(name, color, color, True, index)], index))
+        return groups
+
 
 class HTMXSelect(Select):
     """

+ 25 - 2
netbox/utilities/tests/test_forms.py

@@ -8,7 +8,7 @@ from django.test import TestCase, override_settings
 from django.utils.html import escape
 
 from dcim.models import Rack, Site
-from netbox.choices import ImportFormatChoices
+from netbox.choices import ColorChoices, ImportFormatChoices
 from utilities.choices import Choice, ChoiceSet
 from utilities.forms.bulk_import import BulkImportForm
 from utilities.forms.fields import ChoiceField, MultipleChoiceField, TypedChoiceField
@@ -31,7 +31,7 @@ from utilities.forms.utils import (
     get_field_value,
     parse_numeric_range,
 )
-from utilities.forms.widgets.select import AvailableOptions, HTMXSelect, Select, SelectedOptions
+from utilities.forms.widgets.select import AvailableOptions, ColorSelect, HTMXSelect, Select, SelectedOptions
 
 
 class ExpandIPNetworkTestCase(TestCase):
@@ -1217,3 +1217,26 @@ class DescriptionSelectTestCase(TestCase):
         self.assertTrue(calls)
         # And descriptions are still collected as normal
         self.assertEqual(field.widget.descriptions, {self.ExampleChoices.FOO: 'Description of foo'})
+
+
+class ColorSelectTestCase(TestCase):
+
+    def test_predefined_color_selected(self):
+        html = ColorSelect().render('color', ColorChoices.COLOR_RED)
+        self.assertInHTML(f'<option value="{ColorChoices.COLOR_RED}" selected>Red</option>', html)
+        self.assertEqual(html.count(f'value="{ColorChoices.COLOR_RED}"'), 1)
+
+    def test_custom_color_rendered_as_selected_option(self):
+        html = ColorSelect().render('color', 'e20074')
+        self.assertInHTML('<option value="e20074" selected>e20074</option>', html)
+
+    def test_empty_value_adds_no_option(self):
+        widget = ColorSelect()
+        html = widget.render('color', None)
+        self.assertEqual(html.count('<option'), len(widget.choices))
+
+    def test_invalid_color_adds_no_option(self):
+        widget = ColorSelect()
+        html = widget.render('color', 'ff0000;background:url(x)')
+        self.assertNotIn('background:url', html)
+        self.assertEqual(html.count('<option'), len(widget.choices))

Některé soubory nejsou zobrazeny, neboť je v těchto rozdílových datech změněno mnoho souborů