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):
+4
View File
@@ -15,6 +15,10 @@
"/^source \\.venv/bin/activate\\.fish && python manage\\.py check$/": {
"approve": true,
"matchCommandLine": true
},
"/^python -m py_compile /home/ross/penracourses/rad/generic/tables\\.py$/": {
"approve": true,
"matchCommandLine": true
}
}
}
+10
View File
@@ -348,6 +348,16 @@
// Selection wiring has been moved into per-table initializers
// emitted by `SelectionTable.row_selection_controls`.
try {
if (window.__selection_inits) {
Object.keys(window.__selection_inits).forEach(function(k){
try { window.__selection_inits[k](); } catch (e) { console.error('selection init failed', k, e); }
try { delete window.__selection_inits[k]; } catch (e) {}
});
}
} catch (err) {
console.error('Error running selection initializers', err);
}
});
</script>
</body>
+100
View File
@@ -0,0 +1,100 @@
{% load django_tables2 %}
{% load i18n l10n %}
{% block table-wrapper %}
<div class="table-container">
{% if table.caption %}
{{ table.caption|safe }}
{% endif %}
{% block table %}
<table {% render_attrs table.attrs class="table" %}>
{% block table.thead %}
{% if table.show_header %}
<thead {{ table.attrs.thead.as_html }}>
<tr>
{% for column in table.columns %}
<th {{ column.attrs.th.as_html }}>
{% if column.orderable %}
<a href="{% querystring table.prefixed_order_by_field=column.order_by_alias.next %}">{{ column.header }}</a>
{% else %}
{{ column.header }}
{% endif %}
</th>
{% endfor %}
</tr>
</thead>
{% endif %}
{% endblock table.thead %}
{% block table.tbody %}
<tbody {{ table.attrs.tbody.as_html }}>
{% for row in table.paginated_rows %}
{% block table.tbody.row %}
<tr {{ row.attrs.as_html }}>
{% for column, cell in row.items %}
<td {{ column.attrs.td.as_html }}>{% if column.localize == None %}{{ cell }}{% else %}{% if column.localize %}{{ cell|localize }}{% else %}{{ cell|unlocalize }}{% endif %}{% endif %}</td>
{% endfor %}
</tr>
{% endblock table.tbody.row %}
{% empty %}
{% if table.empty_text %}
{% block table.tbody.empty_text %}
<tr><td colspan="{{ table.columns|length }}">{{ table.empty_text }}</td></tr>
{% endblock table.tbody.empty_text %}
{% endif %}
{% endfor %}
</tbody>
{% endblock table.tbody %}
{% block table.tfoot %}
{% if table.has_footer %}
<tfoot {{ table.attrs.tfoot.as_html }}>
<tr>
{% for column in table.columns %}
<td {{ column.attrs.tf.as_html }}>{{ column.footer }}</td>
{% endfor %}
</tr>
</tfoot>
{% endif %}
{% endblock table.tfoot %}
</table>
{% endblock table %}
{% block pagination %}
{% if table.page and table.paginator.num_pages > 1 %}
<nav aria-label="Table navigation">
<ul class="pagination justify-content-center">
{% if table.page.has_previous %}
{% block pagination.previous %}
<li class="previous page-item">
<a href="{% querystring table.prefixed_page_field=table.page.previous_page_number %}" class="page-link">
<span aria-hidden="true">&laquo;</span>
{% trans 'previous' %}
</a>
</li>
{% endblock pagination.previous %}
{% endif %}
{% if table.page.has_previous or table.page.has_next %}
{% block pagination.range %}
{% for p in table.page|table_page_range:table.paginator %}
<li class="page-item{% if table.page.number == p %} active{% endif %}">
<a class="page-link" {% if p != '...' %}href="{% querystring table.prefixed_page_field=p %}"{% endif %}>
{{ p }}
</a>
</li>
{% endfor %}
{% endblock pagination.range %}
{% endif %}
{% if table.page.has_next %}
{% block pagination.next %}
<li class="next page-item">
<a href="{% querystring table.prefixed_page_field=table.page.next_page_number %}" class="page-link">
{% trans 'next' %}
<span aria-hidden="true">&raquo;</span>
</a>
</li>
{% endblock pagination.next %}
{% endif %}
</ul>
</nav>
{% endif %}
{% endblock pagination %}
</div>
{% endblock table-wrapper %}