Skip to content

Commit 7983d61

Browse files
Rendering tables with ascending priority sort direction showing by default
1 parent 18caef0 commit 7983d61

9 files changed

Lines changed: 326 additions & 43 deletions

‎AGENTS.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,13 @@ coverage there when introducing new markup patterns.
141141
sortable th buttons with `aria-sort`, pagination below 20+ row tables, and
142142
click/Enter/Space cell copy with toast feedback. The filter's clear control
143143
is an × button (accessible name "Clear the … table filter").
144+
- Tables open sorted by their Priority column ascending (▲, priority 1
145+
first), signalling both the report's priority ordering and that headers are
146+
sortable (`TABLE_CONFIG.sorting` defaults in lib/table-operations.js);
147+
`resolveSortKey` maps the semantic `priority` key onto disharmony tables'
148+
dynamic `col<n>` keys via a label match, tables without a Priority column
149+
keep the original report ordering, and clicking the default-sorted column
150+
flips it to descending (sort toggling starts from the effective default).
144151
- Horizontal scrollbar: tables wider than the viewport get `overflow-x: auto`
145152
via the `rf-scroll-x-enabled` class, toggled by `lib/table-enhancer.js`
146153
after measuring `wrapper.scrollWidth > clientWidth` (re-measured on each

‎lib/renderer.js‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
paginateTableData,
1414
pageCount,
1515
sortTableData,
16+
resolveSortKey,
1617
filterTableData
1718
} from './table-operations.js';
1819

@@ -93,8 +94,8 @@ function buildTableSlice(descriptor, allRows, rawState, config) {
9394
? filterTableData(allRows, state.search, filterText)
9495
: allRows;
9596

96-
const knownSort = state.sortKey && columns.some(col => col.key === state.sortKey)
97-
? state.sortKey
97+
const knownSort = config.sorting.enabled
98+
? resolveSortKey(columns, state.sortKey)
9899
: null;
99100
const sorted = config.sorting.enabled
100101
? sortTableData(

‎lib/table-enhancer.js‎

Lines changed: 28 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
columnValue,
1414
filterTableData,
1515
sortTableData,
16+
resolveSortKey,
1617
exportTableToCsv,
1718
copyCellContent
1819
} from './table-operations.js';
@@ -74,14 +75,22 @@ function buildSearchControl(slot, tableId, caption, currentTerm, debounceMs, onT
7475
}
7576

7677
/** Binds sort buttons for a table to state updates. */
77-
function bindSortButtons(root, tableId, state, onTableAction) {
78+
function bindSortButtons(root, tableId, descriptor, state, onTableAction, config = TABLE_CONFIG) {
79+
// The renderer applies the configured default sort when no state exists;
80+
// toggling must start from that effective sort, not the empty state, so
81+
// clicking the default-sorted column flips its direction immediately.
82+
const effectiveSortKey = resolveSortKey(
83+
descriptor.columns, state.sortKey ?? config.sorting.defaultSortColumn);
84+
const effectiveSortDir = state.sortDir === 'desc' || state.sortDir === 'asc'
85+
? state.sortDir
86+
: config.sorting.defaultSortDirection;
7887
root.querySelectorAll(`[data-rf-sort="${tableId}"]`).forEach(button => {
7988
button.addEventListener('click', () => {
8089
const sortKey = button.dataset.sortKey;
81-
const sameColumn = state.sortKey === sortKey;
90+
const sameColumn = effectiveSortKey === sortKey;
8291
onTableAction(tableId, {
8392
sortKey,
84-
sortDir: sameColumn && state.sortDir === 'asc' ? 'desc' : 'asc',
93+
sortDir: sameColumn && effectiveSortDir === 'asc' ? 'desc' : 'asc',
8594
page: 1
8695
});
8796
});
@@ -103,17 +112,28 @@ function bindPagination(root, tableId, state, onTableAction) {
103112
}
104113

105114
/** Binds CSV export controls using the table's current filter and sort state. */
106-
function bindExport(root, tableId, descriptor, state, data) {
115+
function bindExport(root, tableId, descriptor, state, data, config = TABLE_CONFIG) {
107116
root.querySelectorAll(`[data-rf-export="${tableId}"]`).forEach(button => {
108117
button.addEventListener('click', () => {
109118
const rows = descriptor.getRows(data);
110119
const filterText = row =>
111120
descriptor.columns.map(col => String(columnValue(col, row))).join(' ');
112121
const filtered = filterTableData(rows, state.search, filterText);
122+
// No explicit sort state means the table displays the config default
123+
// (priority ascending); the export must match what is on screen. With
124+
// sorting disabled the renderer keeps the report order, so the export
125+
// must not sort either.
126+
const sortKey = config.sorting.enabled
127+
? resolveSortKey(
128+
descriptor.columns, state.sortKey ?? config.sorting.defaultSortColumn)
129+
: null;
130+
const sortDir = state.sortDir === 'desc' || state.sortDir === 'asc'
131+
? state.sortDir
132+
: config.sorting.defaultSortDirection;
113133
const sorted = sortTableData(
114134
filtered,
115-
state.sortKey,
116-
state.sortDir || 'asc',
135+
sortKey,
136+
sortDir,
117137
(row, key) => columnValue(descriptor.columns.find(col => col.key === key), row)
118138
);
119139
exportTableToCsv(
@@ -248,9 +268,9 @@ export function enhanceTables(root, options = {}) {
248268
const match = root.querySelector(`[data-rf-match="${tableId}"]`);
249269
if (match && !match.id) match.id = `rf-match-${tableId}`;
250270
}
251-
if (config.sorting.enabled) bindSortButtons(root, tableId, state, onTableAction);
271+
if (config.sorting.enabled) bindSortButtons(root, tableId, descriptor, state, onTableAction, config);
252272
bindPagination(root, tableId, state, onTableAction);
253-
if (config.export.enabled) bindExport(root, tableId, descriptor, state, data);
273+
if (config.export.enabled) bindExport(root, tableId, descriptor, state, data, config);
254274
if (config.copy.enabled) bindCopyableCells(table, onCopy);
255275
});
256276

‎lib/table-operations.js‎

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,11 @@ export const TABLE_CONFIG = {
1313
},
1414
sorting: {
1515
enabled: true,
16-
defaultSortColumn: null, // null keeps the original report ordering
16+
// Every table opens sorted by its Priority column, ascending (priority 1
17+
// first), so the report's built-in priority ordering is visible and the
18+
// up arrow signals that headers are sortable. Tables without a priority
19+
// column keep the original report ordering (see resolveSortKey).
20+
defaultSortColumn: 'priority',
1721
defaultSortDirection: 'asc'
1822
},
1923
search: {
@@ -125,6 +129,27 @@ export function sortTableData(data, sortColumn, sortDirection, accessor) {
125129
return annotated.map(entry => entry.row);
126130
}
127131

132+
/**
133+
* Resolves a requested sort column against a descriptor's columns. An exact
134+
* column key match wins; when there is none (dynamic disharmony tables use
135+
* positional `col<n>` keys), a case-insensitive label match is attempted so
136+
* a semantic key like "priority" hits the Priority-labelled column. Returns
137+
* null when nothing matches, leaving the original row order untouched.
138+
*
139+
* @param {Array<{key: string, label?: string}>} columns - Table columns.
140+
* @param {string|null|undefined} sortKey - Requested sort key.
141+
* @returns {string|null} Effective column key, or null.
142+
*/
143+
export function resolveSortKey(columns, sortKey) {
144+
if (!sortKey) return null;
145+
const cols = Array.isArray(columns) ? columns : [];
146+
if (cols.some(col => col.key === sortKey)) return sortKey;
147+
const wanted = String(sortKey).trim().toLowerCase();
148+
const byLabel = cols.find(col =>
149+
String(col.label ?? '').trim().toLowerCase() === wanted);
150+
return byLabel?.key ?? null;
151+
}
152+
128153
// ---------------------------------------------------------------------------
129154
// Filtering
130155
// ---------------------------------------------------------------------------

‎tests/e2e/report-pagination.spec.js‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -142,35 +142,46 @@ test.describe('pagination', () => {
142142
});
143143

144144
test.describe('sorting', () => {
145-
test('clicking a column header sorts ascending, then descending, with aria-sort', async ({ page }) => {
145+
test('initializes the Priority column sorted ascending with a visible up arrow', async ({ page }) => {
146146
const table = page.locator('table[data-rf-table="class-relationships"]');
147147
const priorityHeader = table.locator('thead th', { has: page.getByRole('button', { name: /Priority/ }) });
148-
const priorities = () => table.locator('tbody tr td:nth-child(2)').allInnerTexts()
148+
await expect(priorityHeader).toHaveAttribute('aria-sort', 'ascending');
149+
await expect(priorityHeader.locator('.rf-sort-indicator')).toHaveText('▲');
150+
const priorities = await table.locator('tbody tr td:nth-child(2)').allInnerTexts()
149151
.then(texts => texts.map(Number));
152+
expect(priorities).toEqual([1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3]);
153+
});
150154

151-
await priorityHeader.getByRole('button').click();
152-
await expect(priorityHeader).toHaveAttribute('aria-sort', 'ascending');
153-
expect(await priorities()).toEqual([1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3]);
155+
test('clicking Priority flips the default to descending, then back to ascending', async ({ page }) => {
156+
const table = page.locator('table[data-rf-table="class-relationships"]');
157+
const priorityHeader = table.locator('thead th', { has: page.getByRole('button', { name: /Priority/ }) });
158+
const priorities = () => table.locator('tbody tr td:nth-child(2)').allInnerTexts()
159+
.then(texts => texts.map(Number));
154160

155161
await priorityHeader.getByRole('button').click();
156162
await expect(priorityHeader).toHaveAttribute('aria-sort', 'descending');
157163
const desc = await priorities();
158164
expect(desc[0]).toBe(5);
159165
expect([...desc].reverse()).toEqual([...desc].sort((a, b) => a - b));
166+
167+
await priorityHeader.getByRole('button').click();
168+
await expect(priorityHeader).toHaveAttribute('aria-sort', 'ascending');
169+
expect(await priorities()).toEqual([1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3]);
160170
});
161171

162172
test('sorting is kept while paging through the result set', async ({ page }) => {
163173
const table = page.locator('table[data-rf-table="class-relationships"]');
164174
const priorityHeader = table.locator('thead th', { has: page.getByRole('button', { name: /Priority/ }) });
175+
// Flipping the ascending default gives a descending order.
165176
await priorityHeader.getByRole('button').click();
166-
await expect(priorityHeader).toHaveAttribute('aria-sort', 'ascending');
177+
await expect(priorityHeader).toHaveAttribute('aria-sort', 'descending');
167178

168179
const nav = page.locator('[data-rf-pagination="class-relationships"]');
169180
await nav.getByRole('button', { name: 'Next' }).click();
170181
await expect(nav).toContainText('Page 2 of 3');
171-
await expect(priorityHeader).toHaveAttribute('aria-sort', 'ascending');
182+
await expect(priorityHeader).toHaveAttribute('aria-sort', 'descending');
172183
const priorities = await table.locator('tbody tr td:nth-child(2)').allInnerTexts();
173-
expect(Number(priorities[0])).toBeGreaterThanOrEqual(3);
184+
expect(Number(priorities[0])).toBe(3);
174185
});
175186

176187
test('column headers are keyboard operable', async ({ page }) => {
@@ -224,7 +235,6 @@ test.describe('search and filter', () => {
224235
const table = page.locator('table[data-rf-table="class-relationships"]');
225236
const priorityHeader = table.locator('thead th', { has: page.getByRole('button', { name: /Priority/ }) });
226237
await priorityHeader.getByRole('button').click();
227-
await priorityHeader.getByRole('button').click();
228238
await expect(priorityHeader).toHaveAttribute('aria-sort', 'descending');
229239
await page.locator('input[data-rf-search="class-relationships"]').fill('target1');
230240
await expect(page.locator('[data-rf-match="class-relationships"]'))
@@ -247,6 +257,8 @@ test.describe('csv export', () => {
247257
const lines = csv.trim().split('\n');
248258
expect(lines[0]).toBe('Class Relationship,Priority,In Class Cycles,Relationship Strength,Also Removes Pkg Cycle Relationship,In Package Cycles');
249259
expect(lines.length).toBe(CLASS_ROW_COUNT + 1);
260+
// The export honours the default sort (priority ascending): the first
261+
// priority-1 row is Source0, the last priority-5 row is Source44.
250262
expect(lines[1]).toContain('Source0 to Target0');
251263
expect(lines[CLASS_ROW_COUNT]).toContain(`Source${CLASS_ROW_COUNT - 1} to Target${CLASS_ROW_COUNT - 1}`);
252264
});

‎tests/integration/report-view.test.jsx‎

Lines changed: 53 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,11 @@ function headerCell(utils, tableId, sortKey) {
413413
.find(th => th.querySelector(`[data-sort-key="${sortKey}"]`));
414414
}
415415

416+
function headerCells(utils, tableId) {
417+
return [...utils.container.querySelectorAll(
418+
`table[data-rf-table="${tableId}"] thead th`)];
419+
}
420+
416421
async function waitForPage(utils, tableId, statusText) {
417422
await waitFor(() => {
418423
expect(paginationNav(utils, tableId)?.textContent ?? '').toContain(statusText);
@@ -462,21 +467,54 @@ describe('enhanced report tables: pagination', () => {
462467
});
463468

464469
describe('enhanced report tables: sorting', () => {
465-
test('sorts ascending on first click, descending on second, updating aria-sort', async () => {
470+
test('initializes every Priority column sorted ascending with a visible up arrow', async () => {
466471
respondJsonFor(sampleJson);
467472
const utils = await renderReport();
468-
const { fireEvent } = await import('@testing-library/react');
469473

470-
const prioritiesOf = () => tableRows(utils, 'class-relationships')
474+
// Static tables: sorted by priority asc out of the box (priority 1 first),
475+
// arrow signalling both the active sort and that headers are sortable.
476+
for (const tableId of ['class-relationships', 'package-relationships', 'class-cycles-summary']) {
477+
const th = headerCell(utils, tableId, 'priority');
478+
expect(th.getAttribute('aria-sort')).toBe('ascending');
479+
expect(th.querySelector('.rf-sort-indicator').textContent).toBe('▲');
480+
}
481+
// Rows are actually sorted: priority 1 first.
482+
const priorities = tableRows(utils, 'class-relationships')
471483
.map(row => Number(row.children[1].textContent.trim()));
484+
expect(priorities[0]).toBe(1);
485+
expect(priorities[19]).toBe(20);
486+
// Disharmony tables carry the arrow on their Priority-labelled column.
487+
const godThs = headerCells(utils, 'disharmony-GOD');
488+
const godPriority = godThs.find(th => th.querySelector('button')?.textContent.includes('Priority'));
489+
expect(godPriority.getAttribute('aria-sort')).toBe('ascending');
490+
expect(godPriority.querySelector('.rf-sort-indicator').textContent).toBe('▲');
491+
// Tables without a Priority column keep their original order untouched.
492+
for (const th of headerCells(utils, 'largest-cycle-breakdown')) {
493+
expect(th.getAttribute('aria-sort')).toBe('none');
494+
}
495+
}, SLOW_TEST_MS);
472496

497+
test('clicking the default-sorted Priority column flips it to descending', async () => {
498+
respondJsonFor(sampleJson);
499+
const utils = await renderReport();
500+
const { fireEvent } = await import('@testing-library/react');
501+
502+
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort'))
503+
.toBe('ascending');
473504
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
474505
await waitFor(() => {
475-
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('ascending');
506+
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort'))
507+
.toBe('descending');
476508
});
477-
expect(prioritiesOf()).toEqual([...Array(20).keys()].map(i => i + 1));
478-
expect(headerCell(utils, 'class-relationships', 'priority')
479-
.querySelector('.rf-sort-indicator').textContent).toBe('▲');
509+
}, SLOW_TEST_MS);
510+
511+
test('clicking Priority flips the default to descending, then back to ascending', async () => {
512+
respondJsonFor(sampleJson);
513+
const utils = await renderReport();
514+
const { fireEvent } = await import('@testing-library/react');
515+
516+
const prioritiesOf = () => tableRows(utils, 'class-relationships')
517+
.map(row => Number(row.children[1].textContent.trim()));
480518

481519
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
482520
await waitFor(() => {
@@ -485,17 +523,21 @@ describe('enhanced report tables: sorting', () => {
485523
expect(prioritiesOf()).toEqual([...Array(20).keys()].map(i => 47 - i));
486524
expect(headerCell(utils, 'class-relationships', 'priority')
487525
.querySelector('.rf-sort-indicator').textContent).toBe('▼');
526+
527+
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
528+
await waitFor(() => {
529+
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('ascending');
530+
});
531+
expect(prioritiesOf()).toEqual([...Array(20).keys()].map(i => i + 1));
532+
expect(headerCell(utils, 'class-relationships', 'priority')
533+
.querySelector('.rf-sort-indicator').textContent).toBe('▲');
488534
}, SLOW_TEST_MS);
489535

490536
test('applies the sort across the whole dataset and keeps it while paging', async () => {
491537
respondJsonFor(sampleJson);
492538
const utils = await renderReport();
493539
const { fireEvent } = await import('@testing-library/react');
494540

495-
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
496-
await waitFor(() => {
497-
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('ascending');
498-
});
499541
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
500542
await waitFor(() => {
501543
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('descending');
@@ -660,10 +702,6 @@ describe('enhanced report tables: CSV export', () => {
660702

661703
// Sort by priority descending so the export order is observable.
662704
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
663-
await waitFor(() => {
664-
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('ascending');
665-
});
666-
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
667705
await waitFor(() => {
668706
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('descending');
669707
});

0 commit comments

Comments
 (0)