Refactor SelectionTable to use per-table initializers for row selection controls and improve JavaScript handling in templates
This commit is contained in:
+83
-76
@@ -18,8 +18,6 @@ from django.contrib.auth.models import User
|
|||||||
# column (input name="selection") and table attrs that client-side
|
# column (input name="selection") and table attrs that client-side
|
||||||
# scripts can use to find selectable tables.
|
# scripts can use to find selectable tables.
|
||||||
class SelectionTable(tables.Table):
|
class SelectionTable(tables.Table):
|
||||||
# Provide a default selection checkbox column. Subclasses that wish to
|
|
||||||
# customise can override this attribute.
|
|
||||||
selection = tables.CheckBoxColumn(
|
selection = tables.CheckBoxColumn(
|
||||||
accessor="pk",
|
accessor="pk",
|
||||||
orderable=False,
|
orderable=False,
|
||||||
@@ -32,16 +30,9 @@ class SelectionTable(tables.Table):
|
|||||||
)
|
)
|
||||||
|
|
||||||
class Meta:
|
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"}
|
attrs = {"class": "table js-row-selectable", "data-selection-name": "selection"}
|
||||||
|
|
||||||
def __init__(self, *args, **kwargs):
|
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)
|
super().__init__(*args, **kwargs)
|
||||||
try:
|
try:
|
||||||
cols = list(self.columns.names())
|
cols = list(self.columns.names())
|
||||||
@@ -49,19 +40,12 @@ class SelectionTable(tables.Table):
|
|||||||
cols.remove('selection')
|
cols.remove('selection')
|
||||||
cols.append('selection')
|
cols.append('selection')
|
||||||
try:
|
try:
|
||||||
# Preferred API when available
|
|
||||||
self.reorder_columns(cols)
|
self.reorder_columns(cols)
|
||||||
except Exception:
|
except Exception:
|
||||||
# Fallback: set sequence attribute
|
|
||||||
self.sequence = tuple(cols)
|
self.sequence = tuple(cols)
|
||||||
except Exception:
|
except Exception:
|
||||||
# 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:
|
try:
|
||||||
token = format(id(self), 'x')
|
token = format(id(self), 'x')
|
||||||
attrs = getattr(self, 'attrs', None) or {}
|
attrs = getattr(self, 'attrs', None) or {}
|
||||||
@@ -71,75 +55,98 @@ class SelectionTable(tables.Table):
|
|||||||
attrs['data-selection-token'] = token
|
attrs['data-selection-token'] = token
|
||||||
self.attrs = attrs
|
self.attrs = attrs
|
||||||
except Exception:
|
except Exception:
|
||||||
# non-fatal
|
|
||||||
pass
|
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
|
self.caption = self.row_selection_controls
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def row_selection_controls(self):
|
def row_selection_controls(self):
|
||||||
"""Return HTML for the row-selection control bar.
|
|
||||||
|
|
||||||
Usage: render in template with `{{ table.row_selection_controls|safe }}`
|
|
||||||
|
|
||||||
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'))
|
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\">"
|
f"<div class=\"d-flex justify-content-between align-items-center mb-2\">"
|
||||||
" <div>"
|
f" <div>"
|
||||||
" <button class=\"btn btn-outline-secondary btn-sm\" id=\"toggle-row-selection-{}\" type=\"button\">Enable row selection</button>"
|
f" <button class=\"btn btn-outline-secondary btn-sm\" id=\"toggle-row-selection-{token}\" type=\"button\">Enable row selection</button>"
|
||||||
" <div id=\"selection-controls-{}\" class=\"btn-group ms-2\" role=\"group\" style=\"display:none;\">"
|
f" <div id=\"selection-controls-{token}\" 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>"
|
f" <button type=\"button\" class=\"btn btn-sm btn-outline-primary\" id=\"select-all-{token}\">Select all</button>"
|
||||||
" <button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"clear-selection-{}\">Clear</button>"
|
f" <button type=\"button\" class=\"btn btn-sm btn-outline-secondary\" id=\"clear-selection-{token}\">Clear</button>"
|
||||||
" </div>"
|
f" </div>"
|
||||||
" </div>"
|
f" </div>"
|
||||||
" <div>"
|
f" <div>"
|
||||||
" <small class=\"text-muted\">Selected: <span id=\"selected-count-{}\">0</span></small>"
|
f" <small class=\"text-muted\">Selected: <span id=\"selected-count-{token}\">0</span></small>"
|
||||||
" </div>"
|
f" </div>"
|
||||||
"</div>"
|
f"</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
|
script = """
|
||||||
# side table class so pages don't need global wiring.
|
<script>
|
||||||
script = (
|
(function(){
|
||||||
"<script>(function(){"
|
var token = '__TOKEN__';
|
||||||
"var token='{t}';"
|
window.__selection_inits = window.__selection_inits || {};
|
||||||
"var toggleBtn=document.getElementById('toggle-row-selection-'+token);"
|
window.__selection_inits[token] = function(){
|
||||||
"if(!toggleBtn) return;"
|
try { console.log && console.log('selection init registered', token); } catch (e) {}
|
||||||
"var controlsEl=document.getElementById('selection-controls-'+token);"
|
var toggleBtn = document.getElementById('toggle-row-selection-' + token);
|
||||||
"var selectAllBtn=document.getElementById('select-all-'+token);"
|
try { console.log && console.log('selection init running', token, 'table?', !!table); } catch (e) {}
|
||||||
"var clearBtn=document.getElementById('clear-selection-'+token);"
|
if (!toggleBtn) return;
|
||||||
"var selectedCountSpan=document.getElementById('selected-count-'+token);"
|
var controlsEl = document.getElementById('selection-controls-' + token);
|
||||||
"var table=document.querySelector('table.js-row-selectable[data-selection-token=\"'+token+'\"]');"
|
var selectAllBtn = document.getElementById('select-all-' + token);
|
||||||
"if(!table) return;"
|
var clearBtn = document.getElementById('clear-selection-' + token);
|
||||||
"var selectionEnabled=false;"
|
var selectedCountSpan = document.getElementById('selected-count-' + token);
|
||||||
"function findRowCheckboxes(){"
|
var table = document.querySelector('table.js-row-selectable[data-selection-token="' + token + '"]');
|
||||||
" var checks=Array.from(table.querySelectorAll('input[type=\"checkbox\"][name=\"selection\"]'));"
|
if (!table) return;
|
||||||
" if(!checks.length) checks=Array.from(table.querySelectorAll('input[type=\"checkbox\"]'));"
|
|
||||||
" return checks;"
|
var selectionEnabled = false;
|
||||||
"}"
|
var lastChecked = null;
|
||||||
"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 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 hideSelectionColumn(){ table.querySelectorAll('th, td').forEach(function(cell){ if(cell.querySelector && cell.querySelector('input[type=\"checkbox\"][name=\"selection\"]')) cell.style.display='none'; }); }"
|
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 showSelectionColumn(){ table.querySelectorAll('th, td').forEach(function(cell){ if(cell.querySelector && cell.querySelector('input[type=\"checkbox\"][name=\"selection\"]')) cell.style.display=''; }); }"
|
function setCheckboxesDisabled(disabled) { findRowCheckboxes().forEach(function(cb){ cb.disabled = disabled; }); lastChecked = null; }
|
||||||
"setCheckboxesDisabled(true); hideSelectionColumn();"
|
function hideSelectionColumn() { table.querySelectorAll('th, td').forEach(function(cell){ if (cell.querySelector && cell.querySelector('input[type="checkbox"][name="selection"]')) cell.style.display = 'none'; }); }
|
||||||
"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);"
|
function showSelectionColumn() { table.querySelectorAll('th, td').forEach(function(cell){ if (cell.querySelector && cell.querySelector('input[type="checkbox"][name="selection"]')) cell.style.display = ''; }); }
|
||||||
"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(); } });"
|
setCheckboxesDisabled(true); hideSelectionColumn();
|
||||||
"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(); });"
|
table.addEventListener('click', function(e){
|
||||||
"updateSelectedCount();"
|
if (!selectionEnabled) return;
|
||||||
"})();</script>"
|
var tag = (e.target.tagName || '').toLowerCase();
|
||||||
).format(t=token)
|
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)
|
return mark_safe(html + script)
|
||||||
|
|
||||||
|
|||||||
@@ -15,6 +15,10 @@
|
|||||||
"/^source \\.venv/bin/activate\\.fish && python manage\\.py check$/": {
|
"/^source \\.venv/bin/activate\\.fish && python manage\\.py check$/": {
|
||||||
"approve": true,
|
"approve": true,
|
||||||
"matchCommandLine": true
|
"matchCommandLine": true
|
||||||
|
},
|
||||||
|
"/^python -m py_compile /home/ross/penracourses/rad/generic/tables\\.py$/": {
|
||||||
|
"approve": true,
|
||||||
|
"matchCommandLine": true
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -348,6 +348,16 @@
|
|||||||
|
|
||||||
// Selection wiring has been moved into per-table initializers
|
// Selection wiring has been moved into per-table initializers
|
||||||
// emitted by `SelectionTable.row_selection_controls`.
|
// 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>
|
</script>
|
||||||
</body>
|
</body>
|
||||||
|
|||||||
@@ -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">«</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">»</span>
|
||||||
|
</a>
|
||||||
|
</li>
|
||||||
|
{% endblock pagination.next %}
|
||||||
|
{% endif %}
|
||||||
|
</ul>
|
||||||
|
</nav>
|
||||||
|
{% endif %}
|
||||||
|
{% endblock pagination %}
|
||||||
|
</div>
|
||||||
|
{% endblock table-wrapper %}
|
||||||
Reference in New Issue
Block a user