From 9e81f032a3b00b9bc53c6394d7fe2407137c0d49 Mon Sep 17 00:00:00 2001 From: Jacob Olson Date: Wed, 11 Nov 2026 11:02:14 -0700 Subject: [PATCH 1/2] Fix box page N+1 queries; type-to-filter for the box assign list and storage and consumables forms; singular filter Closes #207. Closes #209. Co-Authored-By: Claude Sonnet 5.5 --- krill/consumables/forms.py | 24 ++ krill/sample/templatetags/sample_tags.py | 31 +++ krill/sample/tests/test_combobox.py | 7 + krill/static/krill/js/combobox.js | 3 +- krill/static/krill/style.css | 6 + krill/storage/forms.py | 22 ++ krill/storage/tests/test_box_page.py | 294 +++++++++++++++++++++++ krill/storage/views/detail.py | 47 ++-- krill/templates/consumables/list.html | 9 +- krill/templates/sample/list.html | 9 +- krill/templates/storage/detail.html | 42 ++-- krill/templates/storage/list.html | 9 +- 12 files changed, 449 insertions(+), 54 deletions(-) create mode 100644 krill/storage/tests/test_box_page.py diff --git a/krill/consumables/forms.py b/krill/consumables/forms.py index ed0710a..5b3754a 100644 --- a/krill/consumables/forms.py +++ b/krill/consumables/forms.py @@ -3,6 +3,8 @@ from .models.consumable_type import ConsumableType from .models.location import ConsumableRoom, ConsumableLocation from .models.vendor import Vendor +from sample.widgets import mark_comboboxes +from sample.widgets import mark_comboboxes class ConsumableForm(forms.ModelForm): @@ -37,6 +39,12 @@ def __init__(self, *args, **kwargs): self.fields['access_level'].required = False self.fields['vendor'].required = False self.fields['location'].required = False + # A location is named "Room / Name"; load the room with it instead of one query per option + self.fields['location'].queryset = ConsumableLocation.objects.select_related('room') + mark_comboboxes(self) + # A location is named "Room / Name"; load the room with it instead of one query per option + self.fields['location'].queryset = ConsumableLocation.objects.select_related('room') + mark_comboboxes(self) ctype = self._resolve_type(args, kwargs) self.spec_field_names = [] @@ -124,6 +132,14 @@ class Meta: 'icon': 'Material icon name (e.g. biotech, science)', } + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + mark_comboboxes(self) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + mark_comboboxes(self) + class VendorForm(forms.ModelForm): class Meta: @@ -164,3 +180,11 @@ class Meta: 'name': 'Location name (e.g. Cabinet B, Shelf 3)', 'kind': 'Type of storage location', } + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + mark_comboboxes(self) + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + mark_comboboxes(self) diff --git a/krill/sample/templatetags/sample_tags.py b/krill/sample/templatetags/sample_tags.py index c2999fb..7544ff9 100644 --- a/krill/sample/templatetags/sample_tags.py +++ b/krill/sample/templatetags/sample_tags.py @@ -27,3 +27,34 @@ def is_samples_list_active(context): if 'detail/sample/' in path: return True return False + + +_IRREGULAR_SINGULARS = {'shelves': 'shelf'} + + +@register.filter +def singular(value): + """'Boxes' -> 'Box', 'Shelves' -> 'Shelf', 'Aliquot Types' -> 'Aliquot Type', 'Categories' -> 'Category'. + + Only the last word changes. Chopping the final letter turns 'Boxes' into 'Boxe', so use this instead. + """ + text = str(value or '').strip() + if not text: + return '' + head, _, word = text.rpartition(' ') + lower = word.lower() + if lower in _IRREGULAR_SINGULARS: + result = _IRREGULAR_SINGULARS[lower] + elif lower.endswith('ies') and len(lower) > 3: + result = lower[:-3] + 'y' + elif lower.endswith(('xes', 'ches', 'shes', 'sses', 'zes')): + result = lower[:-2] + elif lower.endswith('s') and not lower.endswith(('ss', 'us', 'is')): + result = lower[:-1] + else: + result = lower + if word.isupper() and len(word) > 1: + result = result.upper() + elif word[:1].isupper(): + result = result.capitalize() + return f'{head} {result}' if head else result diff --git a/krill/sample/tests/test_combobox.py b/krill/sample/tests/test_combobox.py index ff427fc..a2f26b3 100644 --- a/krill/sample/tests/test_combobox.py +++ b/krill/sample/tests/test_combobox.py @@ -223,3 +223,10 @@ def test_the_layout_loads_the_script_and_the_file_exists(self): def test_the_box_clearing_script_notifies_the_combobox(self): html = self.client.get(reverse('sample:sample_create'), {'type': 'aliquot'}).content.decode() self.assertIn("field.dispatchEvent(new Event('change'", html) + + def test_the_text_box_takes_the_selects_classes_and_modals_do_not_clip_the_list(self): + source = open(finders.find('js/combobox.js')).read() + self.assertIn('var originalClasses = select.className;', source) + self.assertIn("input.className = ('combobox-input ' + originalClasses).trim();", source) + css = open(finders.find('style.css') or finders.find('krill/style.css')).read() + self.assertIn('.modal-body:has(.combobox)', css) diff --git a/krill/static/krill/js/combobox.js b/krill/static/krill/js/combobox.js index cf5cab5..fec2dd2 100644 --- a/krill/static/krill/js/combobox.js +++ b/krill/static/krill/js/combobox.js @@ -53,6 +53,7 @@ var searchUrl = select.getAttribute('data-search-url'); if (!searchUrl && select.options.length - 1 < MIN_OPTIONS) { return; } select.dataset.comboboxReady = '1'; + var originalClasses = select.className; // the text box takes the select's look (for example form-control) var id = 'combobox-' + (++counter); var wrapper = document.createElement('div'); @@ -66,7 +67,7 @@ var input = document.createElement('input'); input.type = 'text'; input.id = id + '-input'; - input.className = 'combobox-input'; + input.className = ('combobox-input ' + originalClasses).trim(); input.autocomplete = 'off'; input.spellcheck = false; input.disabled = select.disabled; diff --git a/krill/static/krill/style.css b/krill/static/krill/style.css index 086c2b5..efc0192 100644 --- a/krill/static/krill/style.css +++ b/krill/static/krill/style.css @@ -2677,6 +2677,12 @@ main table tbody tr:last-child td{ position: relative; } +/* A modal body scrolls and would clip the open list, so let it show in full */ +.modal-body:has(.combobox) { + max-height: none; + overflow: visible; +} + /* Keep the real ', start)] + self.assertIn('data-combobox="1"', select) + self.assertIn(f'data-search-url="{reverse("sample:aliquot_options")}"', select) + self.assertEqual(select.count('', html.index('.modal-header {'))] + for hardcoded in ('#f8f9fa', '#dee2e6', '#ced4da', '#6c757d', 'color: #000'): + with self.subTest(hardcoded=hardcoded): + self.assertNotIn(hardcoded, style) + + def test_the_modal_body_does_not_scroll_or_clip_the_picker_list(self): + html = self.page(self.box()).content.decode() + rule = html[html.index('.modal-body {'):] + rule = rule[:rule.index('}')] + self.assertIn('overflow: visible', rule) + self.assertIn('max-height: none', rule) + + def test_assigning_still_takes_the_chosen_aliquot_id(self): + box = self.box() + sample = Sample.objects.create(name='Chosen', source=self.source) + aliquot = Aliquot.objects.create(sample=sample, aliquot_type=self.types[0], disposition=self.stored) + response = self.client.post( + reverse('storage:assign_aliquot', kwargs={'box_id': box.pk, 'row': 2, 'column': 3}), + {'aliquot_id': aliquot.pk}) + self.assertEqual(response.status_code, 302) + location = AliquotLocation.objects.get(aliquot=aliquot) + self.assertEqual((location.box, location.row, location.column), (box, 2, 3)) + + +class StorageFormsTest(BoxFixture): + def test_dropdowns_are_marked_for_type_to_filter(self): + self.assertIn('data-combobox', str(DeviceForm()['site'])) + self.assertIn('data-combobox', str(ShelfForm()['device'])) + self.assertIn('data-combobox', str(RackForm()['shelf'])) + self.assertIn('data-combobox', str(BoxForm()['rack'])) + + def test_shelves_and_racks_are_named_with_their_parents(self): + other_device = Device.objects.create(name='Freezer B', site=self.site) + Shelf.objects.create(name='Shelf 1', device=other_device) # same name on another device + shelf_labels = [label for value, label in RackForm().fields['shelf'].choices if str(value)] + self.assertCountEqual(shelf_labels, ['Freezer A › Shelf 1', 'Freezer B › Shelf 1']) + rack_labels = [label for value, label in BoxForm().fields['rack'].choices if str(value)] + self.assertEqual(rack_labels, ['Freezer A › Shelf 1 › Rack 1']) + + def test_rendering_the_forms_does_not_query_per_option(self): + with CaptureQueriesContext(connection) as few: + str(BoxForm()['rack']), str(RackForm()['shelf']) + for i in range(12): + shelf = Shelf.objects.create(name=f'S{i}', device=self.device) + Rack.objects.create(name=f'R{i}', shelf=shelf) + with CaptureQueriesContext(connection) as many: + str(BoxForm()['rack']), str(RackForm()['shelf']) + self.assertEqual(len(few), len(many)) + + def test_a_chosen_parent_is_still_accepted_when_posted(self): + form = BoxForm({'name': 'New', 'rack': self.rack.pk, 'rows': 5, 'columns': 5}) + self.assertTrue(form.is_valid(), form.errors) + + +class ConsumablesFormsTest(BoxFixture): + def test_dropdowns_are_marked_for_type_to_filter(self): + self.assertIn('data-combobox', str(ConsumableForm()['consumable_type'])) + self.assertIn('data-combobox', str(ConsumableForm()['vendor'])) + self.assertIn('data-combobox', str(ConsumableForm()['location'])) + self.assertIn('data-combobox', str(ConsumableLocationForm()['room'])) + self.assertIn('data-combobox', str(ConsumableTypeForm()['category'])) + + def test_locations_are_named_with_their_room_without_a_query_per_option(self): + room = ConsumableRoom.objects.create(name='Cold Room') + ConsumableLocation.objects.create(room=room, name='Cabinet B') + def labels(): + return [label for value, label in ConsumableForm().fields['location'].choices if str(value)] + with CaptureQueriesContext(connection) as few: + first = labels() + self.assertEqual(first, ['Cold Room / Cabinet B']) + for i in range(12): + ConsumableLocation.objects.create(room=ConsumableRoom.objects.create(name=f'Room {i}'), name='Shelf') + with CaptureQueriesContext(connection) as many: + self.assertEqual(len(labels()), 13) + self.assertEqual(len(few), len(many)) + + +class SingularFilterTest(BoxFixture): + def test_regular_and_irregular_plurals(self): + expected = { + 'Boxes': 'Box', 'Shelves': 'Shelf', 'Sites': 'Site', 'Devices': 'Device', 'Racks': 'Rack', + 'Aliquots': 'Aliquot', 'Aliquot Types': 'Aliquot Type', 'Sources': 'Source', 'Samples': 'Sample', + 'Consumables': 'Consumable', 'Consumable Types': 'Consumable Type', 'Vendors': 'Vendor', + 'Locations': 'Location', 'Rooms': 'Room', 'Categories': 'Category', 'Batches': 'Batch', + } + for plural, single in expected.items(): + with self.subTest(plural=plural): + self.assertEqual(singular(plural), single) + + def test_case_is_kept_and_odd_input_is_safe(self): + self.assertEqual(singular('boxes'), 'box') + self.assertEqual(singular('BOXES'), 'BOX') + self.assertEqual(singular(''), '') + self.assertEqual(singular(None), '') + self.assertEqual(singular('Status'), 'Status') # already singular, not 'Statu' + self.assertEqual(singular('Glass'), 'Glass') + + def _storage(self, type_, **params): + return self.client.get(reverse('storage:storage_list'), {'type': type_, **params}) + + def test_storage_lists_name_one_item_correctly(self): + for type_, single in (('box', 'Box'), ('shelf', 'Shelf'), ('device', 'Device'), ('site', 'Site')): + with self.subTest(type=type_): + response = self._storage(type_) + self.assertContains(response, f'Create New {single}') + self.assertNotContains(response, 'Boxe<') + self.assertNotContains(response, 'Shelve<') + + def test_no_result_text_uses_the_same_singular(self): + for type_, single in (('box', 'box'), ('shelf', 'shelf'), ('device', 'device')): + with self.subTest(type=type_): + self.assertContains(self._storage(type_, q='zzzz-no-match'), f'create a new {single}.') + + def test_sample_and_consumables_lists_still_read_well(self): + from person.models import SiteConfiguration + config = SiteConfiguration.load() + config.consumables_enabled = True + config.save() + sample_page = self.client.get(reverse('sample:sample_list'), {'type': 'aliquot-type'}) + self.assertContains(sample_page, 'Create New Aliquot Type') + for type_, button in (('consumable', 'Add Consumable'), ('type', 'Add Consumable Type'), + ('vendor', 'Add Vendor'), ('location', 'Add Location')): + with self.subTest(type=type_): + page = self.client.get(reverse('consumables:list'), {'type': type_}) + self.assertContains(page, button) + + def test_the_count_text_uses_the_singular_for_one_result(self): + self.box() + self.assertContains(self._storage('box'), '1 box found') + self.assertContains(self._storage('shelf'), '1 shelf found') + + def test_the_consumables_count_text_uses_the_singular_for_one_result(self): + from consumables.models.consumable import Consumable + from consumables.models.consumable_type import ConsumableType + from person.models import SiteConfiguration + config = SiteConfiguration.load() + config.consumables_enabled = True + config.save() + Consumable.objects.create(name='Anti-GFP', consumable_type=ConsumableType.objects.create(name='Antibody', category='antibody')) + page = self.client.get(reverse('consumables:list'), {'type': 'consumable'}) + self.assertContains(page, '1 consumable found') diff --git a/krill/storage/views/detail.py b/krill/storage/views/detail.py index 969c5d4..18f1aff 100644 --- a/krill/storage/views/detail.py +++ b/krill/storage/views/detail.py @@ -39,44 +39,37 @@ def get_context_data(self, **kwargs): # Add storage information for boxes if self.kwargs.get('type') == 'box': box = self.object - # Only show tubes that are currently stored (disposition is "Stored") - locations = AliquotLocation.objects.filter( - box=box - ).select_related('aliquot__sample') + # One query for every position in the box, with what the page shows about each aliquot. + # The grid is then built from this list; it must not query per slot (an N+1). + locations = list( + AliquotLocation.objects.filter(box=box) + .select_related('aliquot__sample', 'aliquot__aliquot_type', 'aliquot__disposition') + .order_by('row', 'column') + ) + by_position = {(loc.row, loc.column): loc for loc in locations} # Create a grid representation of the box box_grid = [] for row in range(1, box.rows + 1): row_data = [] for col in range(1, box.columns + 1): - try: - location = locations.get(row=row, column=col) - row_data.append({ - 'row': row, - 'column': col, - 'occupied': True, - 'aliquot': location.aliquot, - 'sample': location.aliquot.sample, - 'tube_number': None - }) - except AliquotLocation.DoesNotExist: - row_data.append({ - 'row': row, - 'column': col, - 'occupied': False, - 'aliquot': None, - 'sample': None, - 'tube_number': None - }) + location = by_position.get((row, col)) + row_data.append({ + 'row': row, + 'column': col, + 'occupied': location is not None, + 'aliquot': location.aliquot if location else None, + 'sample': location.aliquot.sample if location else None, + 'tube_number': None + }) box_grid.append(row_data) context['box_grid'] = box_grid context['total_slots'] = box.rows * box.columns - context['used_slots'] = locations.count() + context['used_slots'] = len(locations) context['available_slots'] = context['total_slots'] - context['used_slots'] context['storage_percentage'] = (context['used_slots'] / context['total_slots']) * 100 if context['total_slots'] > 0 else 0 context['locations'] = locations - # Add available aliquots for assignment - from sample.models.aliquot import Aliquot - context['available_aliquots'] = Aliquot.objects.all().select_related('sample', 'aliquot_type').order_by('sample__name') + # The "assign aliquot" picker searches the server as you type (sample:aliquot_options), + # so the page no longer carries every aliquot in the database return context def post(self, request, *args, **kwargs): diff --git a/krill/templates/consumables/list.html b/krill/templates/consumables/list.html index b85183c..e2e8fd2 100644 --- a/krill/templates/consumables/list.html +++ b/krill/templates/consumables/list.html @@ -1,4 +1,5 @@ {% extends 'base/layout.html' %} +{% load sample_tags %} {% load static %} {% block content %} @@ -61,7 +62,7 @@

{{ model_name }}

@@ -102,7 +103,7 @@

{{ model_name }}

{{ model_name }}

- {{ paginator.count }} {{ model_name|lower }} found + {{ paginator.count }} {% if paginator.count == 1 %}{{ model_name|singular|lower }}{% else %}{{ model_name|lower }}{% endif %} found {% if search_query %} (filtered by "{{ search_query }}") {% endif %} @@ -273,9 +274,9 @@

{{ model_name }}

search_off

No {{ model_name|lower }} found

-

Try adjusting your search or add a new {{ model_name|slice:":-1"|lower }}.

+

Try adjusting your search or add a new {{ model_name|singular|lower }}.

{% endif %} diff --git a/krill/templates/sample/list.html b/krill/templates/sample/list.html index 89ae77c..4b9ff62 100644 --- a/krill/templates/sample/list.html +++ b/krill/templates/sample/list.html @@ -1,4 +1,5 @@ {% extends 'base/layout.html' %} +{% load sample_tags %} {% load static %} {% block content %} @@ -144,7 +145,7 @@

{{ model_name }}

@@ -165,7 +166,7 @@

{{ model_name }}

{{ model_name }}

- {{ paginator.count }} {% if paginator.count == 1 %}{{ model_name|lower|slice:":-1" }}{% else %}{{ model_name|lower }}{% endif %} found + {{ paginator.count }} {% if paginator.count == 1 %}{{ model_name|singular|lower }}{% else %}{{ model_name|lower }}{% endif %} found {% if search_query %} (filtered by "{{ search_query }}") {% endif %} @@ -433,10 +434,10 @@

No {{ model_name|lower }} found

{% if low_count_on and not search_query %}

No samples are running low.

{% else %} -

Try adjusting your search criteria or create a new {{ model_name|slice:":-1"|lower }}.

+

Try adjusting your search criteria or create a new {{ model_name|singular|lower }}.

{% endif %}
{% endif %} diff --git a/krill/templates/storage/detail.html b/krill/templates/storage/detail.html index ff2ef85..16e00d6 100644 --- a/krill/templates/storage/detail.html +++ b/krill/templates/storage/detail.html @@ -327,6 +327,14 @@

list Stored Aliquots

currentColumn = column; document.getElementById('assignModal').style.display = 'block'; document.getElementById('assignPosition').textContent = `Position (${row}, ${column})`; + // Start each assignment with an empty picker, and put the cursor in it + const select = document.getElementById('aliquotSelect'); + while (select.options.length > 1) { select.remove(1); } + select.value = ''; + select.dispatchEvent(new Event('change', { bubbles: true })); + const box = select.closest('.combobox'); + const input = box && box.querySelector('input'); + if (input) { input.focus(); } } function closeAssignModal() { @@ -385,11 +393,9 @@

Assign Aliquot to Box

Assign an aliquot to position:

- - {% for aliquot in available_aliquots %} - - {% endfor %}
@@ -429,10 +435,11 @@

Assign Aliquot to Box

} .modal-content { - background-color: #fefefe; + background-color: var(--color-white); + color: var(--color-dark); margin: 15% auto; padding: 0; - border: 1px solid #888; + border: 1px solid var(--color-light); width: 90%; max-width: 500px; border-radius: 8px; @@ -441,8 +448,9 @@

Assign Aliquot to Box

.modal-header { padding: 20px; - background-color: #f8f9fa; - border-bottom: 1px solid #dee2e6; + background-color: var(--color-white); + color: var(--color-dark); + border-bottom: 1px solid var(--color-light); border-radius: 8px 8px 0 0; display: flex; justify-content: space-between; @@ -452,10 +460,11 @@

Assign Aliquot to Box

.modal-header h2 { margin: 0; font-size: 1.5rem; + color: var(--color-dark); } .close { - color: #aaa; + color: var(--color-dark-variant); font-size: 28px; font-weight: bold; cursor: pointer; @@ -463,17 +472,20 @@

Assign Aliquot to Box

.close:hover, .close:focus { - color: #000; + color: var(--color-dark); } .modal-body { padding: 20px; + /* This modal is short; the global 60vh scroll box would only clip the open picker list */ + max-height: none; + overflow: visible; } .modal-footer { padding: 20px; - background-color: #f8f9fa; - border-top: 1px solid #dee2e6; + background-color: var(--color-white); + border-top: 1px solid var(--color-light); border-radius: 0 0 8px 8px; display: flex; justify-content: flex-end; @@ -493,16 +505,18 @@

Assign Aliquot to Box

.form-control { width: 100%; padding: 8px 12px; - border: 1px solid #ced4da; + border: 1px solid var(--color-gray-border); border-radius: 4px; font-size: 14px; + background: var(--color-white); + color: var(--color-dark); } .help-text { display: block; margin-top: 5px; font-size: 12px; - color: #6c757d; + color: var(--color-dark-variant); } {% endblock %} diff --git a/krill/templates/storage/list.html b/krill/templates/storage/list.html index 050fb6b..9d992a8 100644 --- a/krill/templates/storage/list.html +++ b/krill/templates/storage/list.html @@ -1,4 +1,5 @@ {% extends 'base/layout.html' %} +{% load sample_tags %} {% load static %} {% block content %} @@ -51,7 +52,7 @@

{{ model_name }}

@@ -62,7 +63,7 @@

{{ model_name }}

{{ model_name }}

- {{ paginator.count }} {{ model_name|lower }} found + {{ paginator.count }} {% if paginator.count == 1 %}{{ model_name|singular|lower }}{% else %}{{ model_name|lower }}{% endif %} found {% if search_query %} (filtered by "{{ search_query }}") {% endif %} @@ -287,9 +288,9 @@

{{ item.name }}

search_off

No {{ model_name|lower }} found

-

Try adjusting your search criteria or create a new {{ model_name|slice:":-1"|lower }}.

+

Try adjusting your search criteria or create a new {{ model_name|singular|lower }}.

{% endif %} From 7ee5f502b4ebc1610dad03bfef76100eaf438d35 Mon Sep 17 00:00:00 2001 From: Jacob Olson Date: Wed, 11 Nov 2026 11:09:10 -0700 Subject: [PATCH 2/2] Aliquots list: move the pills into the results bar Co-Authored-By: Claude Sonnet 5.5 --- krill/sample/tests/test_checked_out.py | 4 +- krill/sample/tests/test_results_bar.py | 145 +++++++++++++++++++++++++ krill/sample/views/list.py | 14 ++- krill/static/krill/style.css | 6 + krill/templates/sample/list.html | 45 ++++---- 5 files changed, 185 insertions(+), 29 deletions(-) create mode 100644 krill/sample/tests/test_results_bar.py diff --git a/krill/sample/tests/test_checked_out.py b/krill/sample/tests/test_checked_out.py index 01af8cf..1f92b2e 100644 --- a/krill/sample/tests/test_checked_out.py +++ b/krill/sample/tests/test_checked_out.py @@ -124,7 +124,7 @@ def _list(self, **params): def test_pills_start_off_with_aria_state(self): response = self._list() - self.assertContains(response, 'aria-label="Checked out by me, off. Select to turn on"') + self.assertContains(response, 'aria-label="Checked out by me, 0 aliquots, off. Select to turn on"') self.assertContains(response, 'aria-label="Hide exhausted, off. Select to turn on"') self.assertNotContains(response, 'toggle-pill on') @@ -163,7 +163,7 @@ def test_checked_out_pill_counts_my_in_use_aliquots_only(self): checked_out_by=owner, checked_out_at=timezone.now()) response = self._list() self.assertEqual(response.context['checked_out_count'], 2) - self.assertContains(response, 'Checked out by me · 2') + self.assertContains(response, 'Checked out by me · 2') def test_search_button_has_aria_label_and_singular_count(self): response = self._list(q='Test Sample') diff --git a/krill/sample/tests/test_results_bar.py b/krill/sample/tests/test_results_bar.py new file mode 100644 index 0000000..823c307 --- /dev/null +++ b/krill/sample/tests/test_results_bar.py @@ -0,0 +1,145 @@ +import re + +from django.contrib.auth import get_user_model +from django.contrib.staticfiles import finders +from django.urls import reverse +from django.utils import timezone + +from ..models.aliquot import Aliquot, AliquotDisposition +from .test_views import SampleViewTest + +User = get_user_model() + + +class ResultsBarTest(SampleViewTest): + """The pills live in the bar directly above the table, with the count and view toggle at the right.""" + + def setUp(self): + super().setUp() + self.client.force_login(self.user) + self.url = reverse('sample:sample_list') + self.in_use = AliquotDisposition.objects.get_or_create(name='In Use', defaults={'disposition_type': 'in_use'})[0] + + def html(self, **params): + return self.client.get(self.url, {'type': 'aliquot', **params}).content.decode() + + @staticmethod + def bar_of(html): + """The results bar: from its id to the table, or to the empty-state block when nothing matches.""" + start = html.index('id="results-bar"') + ends = [html.index(marker, start) for marker in ('', 'class="no-results"') if marker in html[start:]] + return html[start:min(ends)] + + def bar(self, **params): + return self.bar_of(self.html(**params)) + + def checked_out(self, n=2): + for _ in range(n): + Aliquot.objects.create(sample=self.sample, disposition=self.in_use, + checked_out_by=self.user, checked_out_at=timezone.now()) + + def test_the_results_bar_has_an_id(self): + self.assertEqual(self.html().count('id="results-bar"'), 1) + + def test_the_pills_are_in_the_results_bar_not_the_toolbar(self): + html = self.html() + bar_start = html.index('id="results-bar"') + toolbar = html[html.index('class="toolbar-row"'):bar_start] + self.assertNotIn('toggle-pill', toolbar) + bar = self.bar_of(html) + self.assertEqual(len(re.findall(r'class="toggle-pill(?: on)?"', bar)), 2) + self.assertIn('Hide exhausted', bar) + self.assertIn('Checked out by me', bar) + + def test_pills_come_first_then_the_count_and_the_view_toggle(self): + bar = self.bar() + order = ['toggle-pills', 'result-count', 'view-toggle'] + positions = [bar.index(token) for token in order] + self.assertEqual(positions, sorted(positions)) + + def test_the_toggle_links_keep_the_page_in_place_with_an_anchor(self): + response = self.client.get(self.url, {'type': 'aliquot', 'q': 'x', 'sort': 'passage', 'page': '1'}) + for key in ('checked_out_toggle_url', 'hide_finished_toggle_url'): + with self.subTest(link=key): + url = response.context[key] + self.assertTrue(url.endswith('#results-bar'), url) + self.assertIn('q=x', url) # still keeps the other parameters + self.assertIn('sort=passage', url) + self.assertNotIn('page=', url) # and still goes back to page 1 + html = response.content.decode() + self.assertRegex(html, r'href="\?[^"]*checked_out_by=me[^"]*#results-bar"') + self.assertRegex(html, r'href="\?[^"]*hide_finished=1[^"]*#results-bar"') + + def test_turning_a_pill_off_keeps_the_list_type_and_the_anchor(self): + response = self.client.get(self.url, {'type': 'aliquot', 'hide_finished': '1'}) + self.assertEqual(response.context['hide_finished_toggle_url'], '?type=aliquot#results-bar') + + def test_the_count_shows_in_the_checked_out_pill_only_while_it_is_off(self): + self.checked_out(2) + off = self.bar() + self.assertRegex(off, r'Checked out by me · 2') + on = self.bar(checked_out_by='me') + pill = on[on.index('Checked out by me'):] + pill = pill[:pill.index('')] + self.assertNotIn('·', pill) + self.assertNotRegex(pill, r'\d') + + def test_the_hidden_count_is_still_in_the_accessible_label(self): + self.checked_out(1) + self.assertIn('aria-label="Checked out by me, 1 aliquot, off. Select to turn on"', self.bar()) + self.checked_out(1) + self.assertIn('aria-label="Checked out by me, 2 aliquots, off. Select to turn on"', self.bar()) + self.assertIn('aria-label="Checked out by me, on. Select to turn off"', self.bar(checked_out_by='me')) + + def test_chips_sit_between_the_toolbar_and_the_results_bar_and_only_when_active(self): + html = self.html(f_sample='test', f_passage='p8') + positions = [html.index('class="toolbar-row"'), html.index('class="filter-chips"'), + html.index('id="results-bar"')] + self.assertEqual(positions, sorted(positions)) + self.assertNotIn('class="filter-chips"', self.html()) + + def test_clear_all_is_in_the_chips_row_not_the_results_bar(self): + html = self.html(f_sample='test', f_passage='p8') # matches nothing, so no table is rendered + chips = html[html.index('class="filter-chips"'):html.index('id="results-bar"')] + self.assertIn('Clear all', chips) + self.assertNotIn('Clear all', self.bar_of(html)) + + def test_the_samples_list_keeps_its_own_pill_where_it_was(self): + html = self.client.get(self.url).content.decode() + self.assertNotIn('toggle-pill', self.bar_of(html)) # no pills in the Samples results bar + self.assertIn('Low count ·', html) # the Low count pill is still on the page + + def test_the_bar_exists_on_every_list_for_the_anchor_and_count(self): + for params in ({}, {'type': 'source'}, {'type': 'aliquot-type'}): + with self.subTest(params=params): + html = self.client.get(self.url, params).content.decode() + self.assertIn('id="results-bar"', html) + self.assertIn('result-count', html) + + +class ResultsBarStyleTest(SampleViewTest): + def setUp(self): + super().setUp() + self.client.force_login(self.user) + + def test_pills_are_at_least_32px_tall(self): + css = open(finders.find('style.css') or finders.find('krill/style.css')).read() + rule = css[css.index('.toggle-pill {'):] + rule = rule[:rule.index('}')] + self.assertIn('min-height: 32px', rule) + + def test_the_bar_is_a_wrapping_row_centred_with_pills_left_and_info_right(self): + html = self.client.get(reverse('sample:sample_list'), {'type': 'aliquot'}).content.decode() + rule = html[html.index('.results-header {'):] + rule = rule[:rule.index('}')] + for needed in ('display: flex', 'justify-content: space-between', 'align-items: center', 'flex-wrap: wrap'): + with self.subTest(declaration=needed): + self.assertIn(needed, rule) + info = html[html.index('.results-info {'):] + self.assertIn('margin-left: auto', info[:info.index('}')]) + + def test_narrow_screens_wrap_instead_of_stacking_into_a_column(self): + html = self.client.get(reverse('sample:sample_list'), {'type': 'aliquot'}).content.decode() + media = html[html.index('@media (max-width: 768px)'):] + media = media[:media.index('\n}\n')] + self.assertNotRegex(media, r'\.results-header\s*\{[^}]*flex-direction:\s*column') diff --git a/krill/sample/views/list.py b/krill/sample/views/list.py index e05e764..b23c98b 100644 --- a/krill/sample/views/list.py +++ b/krill/sample/views/list.py @@ -168,8 +168,11 @@ def _checked_out_by_everyone(self): return False return UserRole.get_or_create_for_user(self.request.user).role in ('lab_manager', 'lab_admin') - def _toggle_url(self, param, value): - """Link that flips one yes/no filter, keeps every other parameter, and goes back to page 1.""" + def _toggle_url(self, param, value, anchor=''): + """Link that flips one yes/no filter, keeps every other parameter, and goes back to page 1. + + With an anchor the link ends in #anchor, so the page keeps its place after the toggle. + """ params = self.request.GET.copy() params.pop('page', None) if params.get(param) == value: @@ -177,7 +180,8 @@ def _toggle_url(self, param, value): else: params[param] = value query = params.urlencode() - return f'?{query}' if query else self.request.path + url = f'?{query}' if query else self.request.path + return f'{url}#{anchor}' if anchor else url def get_paginate_by(self, queryset): if self.request.GET.get('page_size') == '20': @@ -225,8 +229,8 @@ def get_context_data(self, **kwargs): context['hide_finished'] = self.request.GET.get('hide_finished') == '1' context['checked_out_by_me'] = self.request.GET.get('checked_out_by') == 'me' context['checked_out_all'] = self._checked_out_by_everyone() - context['checked_out_toggle_url'] = self._toggle_url('checked_out_by', 'me') - context['hide_finished_toggle_url'] = self._toggle_url('hide_finished', '1') + context['checked_out_toggle_url'] = self._toggle_url('checked_out_by', 'me', anchor='results-bar') + context['hide_finished_toggle_url'] = self._toggle_url('hide_finished', '1', anchor='results-bar') context['checked_out_count'] = Aliquot.objects.filter( checked_out_by=self.request.user, disposition__disposition_type='in_use', diff --git a/krill/static/krill/style.css b/krill/static/krill/style.css index a744ffa..5c86d72 100644 --- a/krill/static/krill/style.css +++ b/krill/static/krill/style.css @@ -2832,6 +2832,8 @@ main table tbody tr:last-child td{ .toggle-pill { display: inline-flex; align-items: center; + box-sizing: border-box; + min-height: 32px; gap: 0.25rem; padding: 0.3rem 0.8rem; border: 1px solid var(--color-gray-border); @@ -2845,6 +2847,10 @@ main table tbody tr:last-child td{ white-space: nowrap; } +.results-header .toggle-pills { + margin-top: 0; +} + .toggle-pill:hover { border-color: var(--color-primary); } diff --git a/krill/templates/sample/list.html b/krill/templates/sample/list.html index 2f88edc..065a18e 100644 --- a/krill/templates/sample/list.html +++ b/krill/templates/sample/list.html @@ -46,18 +46,6 @@

{{ model_name }}

{% include 'sample/_filter_fields.html' with fields=filter_bar.more variant='panel' %}
- {% include 'sample/_filter_chips.html' %}
{% else %} @@ -131,7 +119,21 @@

{{ model_name }}

-
+
+ {% if model_type == 'aliquot' %} + + {% endif %}
{{ paginator.count }} {% if paginator.count == 1 %}{{ model_name|singular|lower }}{% else %}{{ model_name|lower }}{% endif %} found {% if search_query %} @@ -614,8 +616,11 @@

No {{ model_name|lower }} found

padding: 20px; border-bottom: 1px solid var(--color-light); display: flex; - justify-content: flex-end; /* the page heading above already names the list */ - align-items: center; + justify-content: space-between; + align-items: center; /* pills, count and the view toggle share one centre line */ + flex-wrap: wrap; + gap: 12px 20px; + scroll-margin-top: 1rem; /* the toggle links jump here; leave a little room above */ } .results-header h2 { @@ -625,7 +630,9 @@

No {{ model_name|lower }} found

.results-info { display: flex; - gap: 20px; + flex-wrap: wrap; + gap: 8px 20px; + margin-left: auto; /* always at the right, with or without pills on the left */ color: var(--color-dark-variant); font-size: 0.9rem; align-items: center; @@ -753,12 +760,6 @@

No {{ model_name|lower }} found

grid-template-columns: 1fr; } - .results-header { - flex-direction: column; - gap: 15px; - align-items: flex-start; - } - .form-actions { flex-direction: column; }