Refactor row selection handling in SelectionTable to server-side rendering and per-table initializers for improved maintainability

This commit is contained in:
Ross
2026-03-25 21:37:43 +00:00
parent bf7f88ac6e
commit 1b199150e5
2 changed files with 53 additions and 107 deletions
+51 -4
View File
@@ -58,6 +58,22 @@ class SelectionTable(tables.Table):
# Defensive: don't break table rendering if introspection fails
pass
# Expose a per-instance selection token and ensure the table has the
# `js-row-selectable` class so client-side scripts (or the inline
# initializer below) can find the correct table without extra markup
# in templates.
try:
token = format(id(self), 'x')
attrs = getattr(self, 'attrs', None) or {}
classes = attrs.get('class', '')
if 'js-row-selectable' not in classes:
attrs['class'] = (classes + ' js-row-selectable').strip()
attrs['data-selection-token'] = token
self.attrs = attrs
except Exception:
# non-fatal
pass
# By default render the row selection controls above the table so
# templates don't need to include `{{ table.row_selection_controls }}`.
try:
@@ -75,7 +91,7 @@ class SelectionTable(tables.Table):
The control IDs are suffixed with a small per-instance token to
avoid collisions when multiple tables are present on the same page.
"""
token = format(id(self), 'x')
token = (self.attrs or {}).get('data-selection-token', format(id(self), 'x'))
html = (
"<div class=\"d-flex justify-content-between align-items-center mb-2\">"
@@ -91,10 +107,41 @@ class SelectionTable(tables.Table):
" </div>"
"</div>"
).format(token, token, token, token, token)
# Append a small inline initializer that wires the controls to the
# specific table instance. This moves the behaviour into the server
# side table class so pages don't need global wiring.
script = (
"<script>(function(){"
"var token='{t}';"
"var toggleBtn=document.getElementById('toggle-row-selection-'+token);"
"if(!toggleBtn) return;"
"var controlsEl=document.getElementById('selection-controls-'+token);"
"var selectAllBtn=document.getElementById('select-all-'+token);"
"var clearBtn=document.getElementById('clear-selection-'+token);"
"var selectedCountSpan=document.getElementById('selected-count-'+token);"
"var table=document.querySelector('table.js-row-selectable[data-selection-token=\"'+token+'\"]');"
"if(!table) return;"
"var selectionEnabled=false;"
"function findRowCheckboxes(){"
" var checks=Array.from(table.querySelectorAll('input[type=\"checkbox\"][name=\"selection\"]'));"
" if(!checks.length) checks=Array.from(table.querySelectorAll('input[type=\"checkbox\"]'));"
" return checks;"
"}"
"function updateSelectedCount(){ if(!selectedCountSpan) return; var checks=findRowCheckboxes(); var count=checks.filter(function(c){return c.checked;}).length; selectedCountSpan.textContent=count; checks.forEach(function(cb){var tr=cb.closest('tr'); if(tr) tr.classList.toggle('table-active', cb.checked);}); }"
"function setCheckboxesDisabled(disabled){ findRowCheckboxes().forEach(function(cb){ cb.disabled=disabled; }); }"
"function hideSelectionColumn(){ table.querySelectorAll('th, td').forEach(function(cell){ if(cell.querySelector && cell.querySelector('input[type=\"checkbox\"][name=\"selection\"]')) cell.style.display='none'; }); }"
"function showSelectionColumn(){ table.querySelectorAll('th, td').forEach(function(cell){ if(cell.querySelector && cell.querySelector('input[type=\"checkbox\"][name=\"selection\"]')) cell.style.display=''; }); }"
"setCheckboxesDisabled(true); hideSelectionColumn();"
"table.addEventListener('click', function(e){ if(!selectionEnabled) return; var tag=(e.target.tagName||'').toLowerCase(); if(['input','a','button','select','textarea','label'].indexOf(tag)!==-1) return; var tr=e.target.closest('tr'); if(!tr||!table.contains(tr)) return; var cb=tr.querySelector('input[type=\"checkbox\"][name=\"selection\"]')||tr.querySelector('input[type=\"checkbox\"]'); if(cb && !cb.disabled){ cb.checked=!cb.checked; tr.classList.toggle('table-active', cb.checked); updateSelectedCount(); } }, true);"
"table.addEventListener('change', function(e){ if(e.target && e.target.matches && e.target.matches('input[type=\"checkbox\"]')) updateSelectedCount(); }, true);"
"toggleBtn.addEventListener('click', function(){ selectionEnabled=!selectionEnabled; if(selectionEnabled){ toggleBtn.textContent='Disable row selection'; if(controlsEl) controlsEl.style.display=''; setCheckboxesDisabled(false); showSelectionColumn(); } else { toggleBtn.textContent='Enable row selection'; if(controlsEl) controlsEl.style.display='none'; setCheckboxesDisabled(true); hideSelectionColumn(); findRowCheckboxes().forEach(function(cb){ cb.checked=false; }); updateSelectedCount(); } });"
"if(selectAllBtn) selectAllBtn.addEventListener('click', function(){ findRowCheckboxes().forEach(function(cb){ if(!cb.disabled) cb.checked=true; }); updateSelectedCount(); });"
"if(clearBtn) clearBtn.addEventListener('click', function(){ findRowCheckboxes().forEach(function(cb){ if(!cb.disabled) cb.checked=false; }); updateSelectedCount(); });"
"updateSelectedCount();"
"})();</script>"
).format(t=token)
# Also include a small data attribute so client scripts can locate the
# controls by selection name if they prefer.
return mark_safe(html)
return mark_safe(html + script)
class SingleImageColumn(tables.Column):
def render(self, value):