Refactor SelectionTable to use per-table initializers for row selection controls and improve JavaScript handling in templates

This commit is contained in:
Ross
2026-03-25 22:05:19 +00:00
parent ffb730e9c8
commit 7b52cab180
4 changed files with 199 additions and 78 deletions
+85 -78
View File
@@ -18,8 +18,6 @@ from django.contrib.auth.models import User
# column (input name="selection") and table attrs that client-side
# scripts can use to find selectable tables.
class SelectionTable(tables.Table):
# Provide a default selection checkbox column. Subclasses that wish to
# customise can override this attribute.
selection = tables.CheckBoxColumn(
accessor="pk",
orderable=False,
@@ -32,16 +30,9 @@ class SelectionTable(tables.Table):
)
class Meta:
# Defaults: add js-row-selectable class so client-side code can
# locate tables that support row selection.
attrs = {"class": "table js-row-selectable", "data-selection-name": "selection"}
def __init__(self, *args, **kwargs):
# Ensure selection column is always placed last in the column order
# so that table actions/controls appear to the right. We attempt to
# reorder columns after initialization; if django-tables2 provides
# `reorder_columns`, use it, otherwise fall back to setting
# `self.sequence`.
super().__init__(*args, **kwargs)
try:
cols = list(self.columns.names())
@@ -49,19 +40,12 @@ class SelectionTable(tables.Table):
cols.remove('selection')
cols.append('selection')
try:
# Preferred API when available
self.reorder_columns(cols)
except Exception:
# Fallback: set sequence attribute
self.sequence = tuple(cols)
except Exception:
# 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 {}
@@ -71,77 +55,100 @@ class SelectionTable(tables.Table):
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:
# `row_selection_controls` is already marked safe HTML.
self.caption = self.row_selection_controls
except Exception:
pass
self.caption = self.row_selection_controls
@property
def row_selection_controls(self):
"""Return HTML for the row-selection control bar.
token = (self.attrs or {}).get('data-selection-token', format(id(self), 'x'))
Usage: render in template with `{{ table.row_selection_controls|safe }}`
html = (
f"<div class=\"d-flex justify-content-between align-items-center mb-2\">"
f" <div>"
f" <button class=\"btn btn-outline-secondary btn-sm\" id=\"toggle-row-selection-{token}\" type=\"button\">Enable row selection</button>"
f" <div id=\"selection-controls-{token}\" class=\"btn-group ms-2\" role=\"group\" style=\"display:none;\">"
f" <button type=\"button\" class=\"btn btn-sm btn-outline-primary\" id=\"select-all-{token}\">Select all</button>"
f" <button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"clear-selection-{token}\">Clear</button>"
f" </div>"
f" </div>"
f" <div>"
f" <small class=\"text-muted\">Selected: <span id=\"selected-count-{token}\">0</span></small>"
f" </div>"
f"</div>"
)
The control IDs are suffixed with a small per-instance token to
avoid collisions when multiple tables are present on the same page.
"""
token = (self.attrs or {}).get('data-selection-token', format(id(self), 'x'))
script = """
<script>
(function(){
var token = '__TOKEN__';
window.__selection_inits = window.__selection_inits || {};
window.__selection_inits[token] = function(){
try { console.log && console.log('selection init registered', token); } catch (e) {}
var toggleBtn = document.getElementById('toggle-row-selection-' + token);
try { console.log && console.log('selection init running', token, 'table?', !!table); } catch (e) {}
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;
html = (
"<div class=\"d-flex justify-content-between align-items-center mb-2\">"
" <div>"
" <button class=\"btn btn-outline-secondary btn-sm\" id=\"toggle-row-selection-{}\" type=\"button\">Enable row selection</button>"
" <div id=\"selection-controls-{}\" class=\"btn-group ms-2\" role=\"group\" style=\"display:none;\">"
" <button type=\"button\" class=\"btn btn-sm btn-outline-primary\" id=\"select-all-{}\">Select all</button>"
" <button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"clear-selection-{}\">Clear</button>"
" </div>"
" </div>"
" <div>"
" <small class=\"text-muted\">Selected: <span id=\"selected-count-{}\">0</span></small>"
" </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)
var selectionEnabled = false;
var lastChecked = null;
return mark_safe(html + script)
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; }); lastChecked = null; }
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 (['a','button','select','textarea','label'].indexOf(tag) !== -1) return;
if (e.target && e.target.matches && e.target.matches('input[type="checkbox"]')){
var cb = e.target;
if (e.shiftKey && lastChecked && lastChecked !== cb){
var checks = findRowCheckboxes();
var start = checks.indexOf(lastChecked);
var end = checks.indexOf(cb);
if (start > -1 && end > -1){
if (start > end){ var tmp = start; start = end; end = tmp; }
for (var i = start; i <= end; i++){ if (!checks[i].disabled) checks[i].checked = cb.checked; }
updateSelectedCount();
}
}
lastChecked = cb;
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(); lastChecked = cb; }
}, 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(); lastChecked = null; } });
if (selectAllBtn) selectAllBtn.addEventListener('click', function(){ findRowCheckboxes().forEach(function(cb){ if (!cb.disabled) cb.checked = true; }); updateSelectedCount(); lastChecked = null; });
if (clearBtn) clearBtn.addEventListener('click', function(){ findRowCheckboxes().forEach(function(cb){ if (!cb.disabled) cb.checked = false; }); updateSelectedCount(); lastChecked = null; });
updateSelectedCount();
};
})();
</script>
"""
# Replace the simple placeholder with the runtime token. Using
# a plain triple-quoted string avoids f-string brace parsing errors
# from the JavaScript code which contains many `{`/`}` characters.
script = script.replace('__TOKEN__', token)
return mark_safe(html + script)
class SingleImageColumn(tables.Column):
def render(self, value):