Skip to content

Commit f1a00f3

Browse files
Merge pull request #10 from refactorfirst/show-ascending-arrow-by-default
Rendering tables with ascending priority sort direction showing by default
2 parents 18caef0 + 99c2cbb commit f1a00f3

9 files changed

Lines changed: 355 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: 25 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -142,35 +142,50 @@ 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+
/**
159+
* Reads the visible class relationship priorities in their current row order.
160+
* @returns {Promise<number[]>} Priorities on the currently rendered page.
161+
*/
162+
const priorities = () => table.locator('tbody tr td:nth-child(2)').allInnerTexts()
163+
.then(texts => texts.map(Number));
154164

155165
await priorityHeader.getByRole('button').click();
156166
await expect(priorityHeader).toHaveAttribute('aria-sort', 'descending');
157167
const desc = await priorities();
158168
expect(desc[0]).toBe(5);
159169
expect([...desc].reverse()).toEqual([...desc].sort((a, b) => a - b));
170+
171+
await priorityHeader.getByRole('button').click();
172+
await expect(priorityHeader).toHaveAttribute('aria-sort', 'ascending');
173+
expect(await priorities()).toEqual([1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3]);
160174
});
161175

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

168183
const nav = page.locator('[data-rf-pagination="class-relationships"]');
169184
await nav.getByRole('button', { name: 'Next' }).click();
170185
await expect(nav).toContainText('Page 2 of 3');
171-
await expect(priorityHeader).toHaveAttribute('aria-sort', 'ascending');
186+
await expect(priorityHeader).toHaveAttribute('aria-sort', 'descending');
172187
const priorities = await table.locator('tbody tr td:nth-child(2)').allInnerTexts();
173-
expect(Number(priorities[0])).toBeGreaterThanOrEqual(3);
188+
expect(Number(priorities[0])).toBe(3);
174189
});
175190

176191
test('column headers are keyboard operable', async ({ page }) => {
@@ -224,7 +239,6 @@ test.describe('search and filter', () => {
224239
const table = page.locator('table[data-rf-table="class-relationships"]');
225240
const priorityHeader = table.locator('thead th', { has: page.getByRole('button', { name: /Priority/ }) });
226241
await priorityHeader.getByRole('button').click();
227-
await priorityHeader.getByRole('button').click();
228242
await expect(priorityHeader).toHaveAttribute('aria-sort', 'descending');
229243
await page.locator('input[data-rf-search="class-relationships"]').fill('target1');
230244
await expect(page.locator('[data-rf-match="class-relationships"]'))
@@ -247,6 +261,8 @@ test.describe('csv export', () => {
247261
const lines = csv.trim().split('\n');
248262
expect(lines[0]).toBe('Class Relationship,Priority,In Class Cycles,Relationship Strength,Also Removes Pkg Cycle Relationship,In Package Cycles');
249263
expect(lines.length).toBe(CLASS_ROW_COUNT + 1);
264+
// The export honours the default sort (priority ascending): the first
265+
// priority-1 row is Source0, the last priority-5 row is Source44.
250266
expect(lines[1]).toContain('Source0 to Target0');
251267
expect(lines[CLASS_ROW_COUNT]).toContain(`Source${CLASS_ROW_COUNT - 1} to Target${CLASS_ROW_COUNT - 1}`);
252268
});

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

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

416+
/**
417+
* Finds all header cells in a rendered report table, in column order.
418+
* @param {object} utils - React Testing Library render result.
419+
* @param {string} tableId - Report table identifier.
420+
* @returns {Array<HTMLTableCellElement>} Matching table header cells.
421+
*/
422+
function headerCells(utils, tableId) {
423+
return [...utils.container.querySelectorAll(
424+
`table[data-rf-table="${tableId}"] thead th`)];
425+
}
426+
416427
async function waitForPage(utils, tableId, statusText) {
417428
await waitFor(() => {
418429
expect(paginationNav(utils, tableId)?.textContent ?? '').toContain(statusText);
@@ -462,21 +473,58 @@ describe('enhanced report tables: pagination', () => {
462473
});
463474

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

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

503+
test('clicking the default-sorted Priority column flips it to descending', async () => {
504+
respondJsonFor(sampleJson);
505+
const utils = await renderReport();
506+
const { fireEvent } = await import('@testing-library/react');
507+
508+
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort'))
509+
.toBe('ascending');
473510
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
474511
await waitFor(() => {
475-
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('ascending');
512+
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort'))
513+
.toBe('descending');
476514
});
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('▲');
515+
}, SLOW_TEST_MS);
516+
517+
test('clicking Priority flips the default to descending, then back to ascending', async () => {
518+
respondJsonFor(sampleJson);
519+
const utils = await renderReport();
520+
const { fireEvent } = await import('@testing-library/react');
521+
522+
/**
523+
* Reads the visible class relationship priorities in their current row order.
524+
* @returns {number[]} Priorities on the currently rendered page.
525+
*/
526+
const prioritiesOf = () => tableRows(utils, 'class-relationships')
527+
.map(row => Number(row.children[1].textContent.trim()));
480528

481529
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
482530
await waitFor(() => {
@@ -485,17 +533,21 @@ describe('enhanced report tables: sorting', () => {
485533
expect(prioritiesOf()).toEqual([...Array(20).keys()].map(i => 47 - i));
486534
expect(headerCell(utils, 'class-relationships', 'priority')
487535
.querySelector('.rf-sort-indicator').textContent).toBe('▼');
536+
537+
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
538+
await waitFor(() => {
539+
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('ascending');
540+
});
541+
expect(prioritiesOf()).toEqual([...Array(20).keys()].map(i => i + 1));
542+
expect(headerCell(utils, 'class-relationships', 'priority')
543+
.querySelector('.rf-sort-indicator').textContent).toBe('▲');
488544
}, SLOW_TEST_MS);
489545

490546
test('applies the sort across the whole dataset and keeps it while paging', async () => {
491547
respondJsonFor(sampleJson);
492548
const utils = await renderReport();
493549
const { fireEvent } = await import('@testing-library/react');
494550

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-
});
499551
fireEvent.click(headerCell(utils, 'class-relationships', 'priority').querySelector('button'));
500552
await waitFor(() => {
501553
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('descending');
@@ -660,10 +712,6 @@ describe('enhanced report tables: CSV export', () => {
660712

661713
// Sort by priority descending so the export order is observable.
662714
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'));
667715
await waitFor(() => {
668716
expect(headerCell(utils, 'class-relationships', 'priority').getAttribute('aria-sort')).toBe('descending');
669717
});

0 commit comments

Comments
 (0)