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 # Defensive: don't break table rendering if introspection fails
pass 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 # By default render the row selection controls above the table so
# templates don't need to include `{{ table.row_selection_controls }}`. # templates don't need to include `{{ table.row_selection_controls }}`.
try: try:
@@ -75,7 +91,7 @@ class SelectionTable(tables.Table):
The control IDs are suffixed with a small per-instance token to The control IDs are suffixed with a small per-instance token to
avoid collisions when multiple tables are present on the same page. 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 = ( html = (
"<div class=\"d-flex justify-content-between align-items-center mb-2\">" "<div class=\"d-flex justify-content-between align-items-center mb-2\">"
@@ -91,10 +107,41 @@ class SelectionTable(tables.Table):
" </div>" " </div>"
"</div>" "</div>"
).format(token, token, token, token, token) ).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 return mark_safe(html + script)
# controls by selection name if they prefer.
return mark_safe(html)
class SingleImageColumn(tables.Column): class SingleImageColumn(tables.Column):
def render(self, value): def render(self, value):
+2 -103
View File
@@ -346,109 +346,8 @@
return any || null; return any || null;
} }
// Helper to build id with optional token // Selection wiring has been moved into per-table initializers
function suffixed(idBase, token) { // emitted by `SelectionTable.row_selection_controls`.
return token ? idBase + '-' + token : idBase;
}
// Injector removed: selection controls are rendered server-side
// by `SelectionTable.row_selection_controls` (now set as `caption`).
// For every toggle button (supports both unsuffixed and suffixed IDs)
document.querySelectorAll('button[id^="toggle-row-selection"]').forEach(function(toggleBtn) {
// derive token (empty for unsuffixed)
var token = '';
if (toggleBtn.id !== 'toggle-row-selection') token = toggleBtn.id.replace('toggle-row-selection-', '');
var controlsEl = document.getElementById(suffixed('selection-controls', token));
var selectAllBtn = document.getElementById(suffixed('select-all', token));
var clearBtn = document.getElementById(suffixed('clear-selection', token));
var selectedCountSpan = document.getElementById(suffixed('selected-count', token));
var table = findTableForControl(toggleBtn);
if (!table) return; // nothing to do
var selectionEnabled = false;
function findRowCheckboxes() {
if (!table) return [];
// prefer named selection inputs but fall back to any checkbox
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() {
if (!table) return;
table.querySelectorAll('th, td').forEach(function(cell){ if (cell.querySelector && cell.querySelector('input[type="checkbox"][name="selection"]')) cell.style.display = 'none'; });
}
function showSelectionColumn() {
if (!table) return;
table.querySelectorAll('th, td').forEach(function(cell){ if (cell.querySelector && cell.querySelector('input[type="checkbox"][name="selection"]')) cell.style.display = ''; });
}
// initialise state
setCheckboxesDisabled(true);
hideSelectionColumn();
// row click toggling (attach to table to avoid global handlers)
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);
// listen for changes within the table to keep counts in sync
table.addEventListener('change', function(e){ if (e.target && e.target.matches && e.target.matches('input[type="checkbox"]')) updateSelectedCount(); }, true);
// wire controls
if (toggleBtn) {
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(); });
}
// initial count
updateSelectedCount();
});
}); });
</script> </script>
</body> </body>