fix(grid): add transpose column-name sorting
This commit is contained in:
2 files changed
+57
-134
No files matched your search
@@ -5197,11 +5197,14 @@ function scrollToCurrentMatch() {
|
||||
}
|
||||
|
||||
function scrollTransposeFieldIntoView(visibleFieldIndex: number) {
|
||||
const actualColumnIndex = visibleColumnIndexes.value[visibleFieldIndex];
|
||||
const sortedIndex = transposeRows.value.findIndex((item) => item.columnIndex === actualColumnIndex);
|
||||
if (sortedIndex < 0) return;
|
||||
const scroller = transposeScrollRef.value;
|
||||
if (scroller && !(scroller instanceof HTMLElement)) {
|
||||
(scroller as { scrollToItem?: (index: number) => void }).scrollToItem?.(visibleFieldIndex);
|
||||
(scroller as { scrollToItem?: (index: number) => void }).scrollToItem?.(sortedIndex);
|
||||
} else if (scroller instanceof HTMLElement) {
|
||||
scroller.scrollTop = visibleFieldIndex * transposeRowHeight.value;
|
||||
scroller.scrollTop = sortedIndex * transposeRowHeight.value;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10190,8 +10193,9 @@ const activeTransposeRecordIndexes = computed(() =>
|
||||
);
|
||||
const transposeBeforeSpacerWidth = computed(() => (multiRowTranspose.value ? transposeRecordWindow.value.beforeWidth : 0));
|
||||
const transposeAfterSpacerWidth = computed(() => (multiRowTranspose.value ? transposeRecordWindow.value.afterWidth + transposeEndSpacerWidth.value : 0));
|
||||
const transposeColumnSortDirection = ref<"asc" | "desc" | null>(null);
|
||||
const transposeRows = computed(() => {
|
||||
return buildVisibleTransposeRows({
|
||||
const rows = buildVisibleTransposeRows({
|
||||
columns: visibleColumns.value,
|
||||
records: displayRowRefs.value.map((_, index) => displayItemAt(index)?.data ?? []),
|
||||
recordIndexes: activeTransposeRecordIndexes.value,
|
||||
@@ -10199,6 +10203,11 @@ const transposeRows = computed(() => {
|
||||
types: visibleColumnTypes.value.map((type) => (type ? shortTypeName(compactHeaderColumnType(type)) : "")),
|
||||
comments: visibleColumnComments.value,
|
||||
displayValue: (value, _column, index) => formatCellCached(value, visibleColumnIndexes.value[index]),
|
||||
}).map((row, index) => ({ ...row, columnIndex: visibleColumnIndexes.value[index] }));
|
||||
if (!transposeColumnSortDirection.value) return rows;
|
||||
return [...rows].sort((left, right) => {
|
||||
const result = left.column.localeCompare(right.column, undefined, { sensitivity: "base" });
|
||||
return transposeColumnSortDirection.value === "asc" ? result : -result;
|
||||
});
|
||||
});
|
||||
const transposeReserveTypeLine = computed(() => showTransposeFieldMetadata.value && showColumnTypesInHeader.value && transposeRows.value.some((row) => row.type));
|
||||
@@ -10223,6 +10232,10 @@ function transposeFieldTitle(item: { column: string; type: string; comment?: str
|
||||
return details.join("\n");
|
||||
}
|
||||
|
||||
function toggleTransposeColumnSort() {
|
||||
transposeColumnSortDirection.value = transposeColumnSortDirection.value === "asc" ? "desc" : "asc";
|
||||
}
|
||||
|
||||
function transposeColumnIndexKind(column: string): ColumnIndexKind | undefined {
|
||||
if (!showIndexIndicatorsInHeader.value) return undefined;
|
||||
const kind = columnIndexMap.value.get(columnIndexNameKey(column));
|
||||
@@ -13005,8 +13018,21 @@ useUpdateBlocker(() => (hasPendingChanges.value || hasPendingDataEditorDraft.val
|
||||
>
|
||||
<template #before>
|
||||
<div class="data-grid-transpose-header data-grid-header-shell sticky top-0 z-20 flex h-7 border-b border-border font-semibold text-muted-foreground" :style="{ width: `${transposeTotalWidth}px` }">
|
||||
<div class="data-grid-header-cell sticky left-0 z-30 shrink-0 border-r border-border px-3 py-1.5 truncate relative" :style="{ width: `${transposePinnedWidth}px` }">
|
||||
{{ t("grid.columnName") }}
|
||||
<div class="data-grid-header-cell sticky left-0 z-30 flex shrink-0 items-center border-r border-border px-3 py-1.5 truncate relative" :style="{ width: `${transposePinnedWidth}px` }">
|
||||
<span class="min-w-0 flex-1 truncate">{{ t("grid.columnName") }}</span>
|
||||
<button
|
||||
data-grid-transpose-column-sort
|
||||
type="button"
|
||||
class="ml-1 flex h-4 w-4 shrink-0 items-center justify-center rounded text-muted-foreground hover:bg-accent hover:text-foreground"
|
||||
:title="t('grid.sort')"
|
||||
:aria-label="t('grid.sort')"
|
||||
@mousedown.stop
|
||||
@click.stop="toggleTransposeColumnSort"
|
||||
>
|
||||
<ArrowUp v-if="transposeColumnSortDirection === 'asc'" class="h-3 w-3" />
|
||||
<ArrowDown v-else-if="transposeColumnSortDirection === 'desc'" class="h-3 w-3" />
|
||||
<ArrowUpDown v-else class="h-3 w-3" />
|
||||
</button>
|
||||
<div class="absolute right-0 top-0 bottom-0 w-1.5 cursor-col-resize hover:bg-primary/30" @mousedown.stop="onTransposePinnedResizeStart" />
|
||||
</div>
|
||||
<div class="shrink-0" :style="{ width: `${transposeBeforeSpacerWidth}px` }" />
|
||||
@@ -13034,7 +13060,7 @@ useUpdateBlocker(() => (hasPendingChanges.value || hasPendingDataEditorDraft.val
|
||||
<div class="shrink-0" :style="{ width: `${transposeAfterSpacerWidth}px` }" />
|
||||
</div>
|
||||
</template>
|
||||
<template #default="{ item, index }">
|
||||
<template #default="{ item }">
|
||||
<div
|
||||
class="data-grid-transpose-row flex border-b border-border/60"
|
||||
:style="{
|
||||
@@ -13045,12 +13071,12 @@ useUpdateBlocker(() => (hasPendingChanges.value || hasPendingDataEditorDraft.val
|
||||
<LightTooltip :text="transposeFieldTitle(item)" side="right" :side-offset="6" :delay="250" :open-on-focus="false" surface="popover">
|
||||
<div
|
||||
data-native-clipboard
|
||||
:data-grid-transpose-column-index="visibleColumnIndexes[index]"
|
||||
:data-grid-transpose-column-index="item.columnIndex"
|
||||
class="sticky left-0 z-10 flex shrink-0 flex-col items-start justify-center overflow-hidden border-r border-border bg-background px-3 py-0"
|
||||
:class="{
|
||||
'ring-2 ring-inset ring-primary': highlightedColumnIndex === visibleColumnIndexes[index],
|
||||
'bg-yellow-200/60 dark:bg-yellow-500/20': transposeHeaderIsSearchMatch(visibleColumnIndexes[index]),
|
||||
'ring-2 ring-inset ring-yellow-500 bg-yellow-300/60 dark:bg-yellow-500/40': transposeHeaderIsCurrentMatch(visibleColumnIndexes[index]),
|
||||
'ring-2 ring-inset ring-primary': highlightedColumnIndex === item.columnIndex,
|
||||
'bg-yellow-200/60 dark:bg-yellow-500/20': transposeHeaderIsSearchMatch(item.columnIndex),
|
||||
'ring-2 ring-inset ring-yellow-500 bg-yellow-300/60 dark:bg-yellow-500/40': transposeHeaderIsCurrentMatch(item.columnIndex),
|
||||
}"
|
||||
:style="{ width: `${transposePinnedWidth}px` }"
|
||||
>
|
||||
@@ -13059,38 +13085,6 @@ useUpdateBlocker(() => (hasPendingChanges.value || hasPendingDataEditorDraft.val
|
||||
<Hash v-else-if="transposeColumnIndexKind(item.column)" data-grid-transpose-index-indicator class="h-3 w-3 shrink-0" :class="columnIndexColorClass(transposeColumnIndexKind(item.column)!)" :title="transposeColumnIndexText(transposeColumnIndexKind(item.column)!)" />
|
||||
<span class="min-w-0 flex-1 truncate font-medium leading-4">{{ item.column }}</span>
|
||||
</span>
|
||||
<LightDropdownMenu
|
||||
v-if="headerColumnSortable(visibleColumnIndexes[index])"
|
||||
:items="sortMenuItems(item.column, visibleColumnIndexes[index])"
|
||||
:open="headerSortMenuOpenColumn === visibleColumnIndexes[index]"
|
||||
:selected-value="selectedSortMenuValue(item.column, visibleColumnIndexes[index])"
|
||||
check-position="none"
|
||||
align="end"
|
||||
content-class="w-max min-w-28 p-0.5"
|
||||
item-class="gap-1 rounded-none px-1.5 py-0.5 text-xs"
|
||||
item-icon-class="h-3 w-3"
|
||||
:match-trigger-width="false"
|
||||
@update:open="(value: boolean) => (headerSortMenuOpenColumn = value ? visibleColumnIndexes[index] : null)"
|
||||
@select="(value: string) => selectHeaderSort(value, item.column, visibleColumnIndexes[index])"
|
||||
>
|
||||
<template #trigger="{ open, toggle }">
|
||||
<button
|
||||
data-grid-transpose-sort
|
||||
type="button"
|
||||
class="absolute right-1 top-1 flex h-4 w-4 shrink-0 items-center justify-center rounded"
|
||||
:class="columnIsSorted(item.column, visibleColumnIndexes[index]) ? 'bg-primary text-primary-foreground opacity-100 shadow-sm hover:bg-primary/90' : 'text-muted-foreground opacity-80 hover:bg-accent hover:text-foreground'"
|
||||
:title="t('grid.sort')"
|
||||
:aria-label="`${t('grid.sort')}: ${item.column}`"
|
||||
:aria-expanded="open"
|
||||
@mousedown.stop
|
||||
@click.stop="toggle"
|
||||
>
|
||||
<ArrowUp v-if="columnIsSorted(item.column, visibleColumnIndexes[index]) && sortDir === 'asc'" class="h-3 w-3 shrink-0" />
|
||||
<ArrowDown v-else-if="columnIsSorted(item.column, visibleColumnIndexes[index]) && sortDir === 'desc'" class="h-3 w-3 shrink-0" />
|
||||
<ArrowUpDown v-else class="h-3 w-3 shrink-0" />
|
||||
</button>
|
||||
</template>
|
||||
</LightDropdownMenu>
|
||||
<template v-if="showTransposeFieldMetadata && showColumnTypesInHeader && item.type">
|
||||
<span data-grid-transpose-type-line class="h-3 min-w-0 truncate text-[10px] font-normal leading-3 select-none" :class="typeColorClass(item.type)" :title="item.type">
|
||||
{{ item.type }}
|
||||
|
||||
@@ -6,7 +6,6 @@ import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import i18n from "@/i18n";
|
||||
import type { QueryResult } from "@/types/database";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { sortDataGridRowIndexes, type DataGridSortDirection, type DataGridSortMode } from "@/lib/dataGrid/dataGridSort";
|
||||
|
||||
vi.mock("vue-virtual-scroller", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
@@ -53,29 +52,11 @@ async function settle() {
|
||||
await nextTick();
|
||||
}
|
||||
|
||||
function menuAction(label: string): HTMLButtonElement {
|
||||
const button = [...document.querySelectorAll<HTMLButtonElement>('[role="menuitem"]')].find((candidate) => candidate.textContent?.trim() === label);
|
||||
if (!button) throw new Error(`Sort menu action not found: ${label}`);
|
||||
return button;
|
||||
function transposeFieldNames(host: HTMLElement): string[] {
|
||||
return [...host.querySelectorAll<HTMLElement>("[data-grid-transpose-column-index]")].map((field) => field.textContent?.trim().split("\n")[0] ?? "");
|
||||
}
|
||||
|
||||
function transposeField(host: HTMLElement, columnIndex: number): HTMLElement {
|
||||
const field = host.querySelector<HTMLElement>(`[data-grid-transpose-column-index="${columnIndex}"]`);
|
||||
if (!field) throw new Error(`Transpose field not found: ${columnIndex}`);
|
||||
return field.closest<HTMLElement>(".data-grid-transpose-row")!;
|
||||
}
|
||||
|
||||
function transposeValues(host: HTMLElement, columnIndex: number): string[] {
|
||||
return [...transposeField(host, columnIndex).querySelectorAll<HTMLElement>("[data-grid-transpose-cell]")].map((cell) => cell.textContent?.trim() ?? "");
|
||||
}
|
||||
|
||||
function transposeRecordHeader(host: HTMLElement, recordIndex: number): HTMLElement {
|
||||
const header = host.querySelector<HTMLElement>(`[data-grid-transpose-record-header][data-grid-transpose-record-index="${recordIndex}"]`);
|
||||
if (!header) throw new Error(`Transpose record header not found: ${recordIndex}`);
|
||||
return header;
|
||||
}
|
||||
|
||||
function mountGrid(databaseSortEnabled?: boolean) {
|
||||
function mountGrid() {
|
||||
const pinia = createPinia();
|
||||
setActivePinia(pinia);
|
||||
const settingsStore = useSettingsStore();
|
||||
@@ -88,25 +69,13 @@ function mountGrid(databaseSortEnabled?: boolean) {
|
||||
];
|
||||
const result = ref<QueryResult>(
|
||||
markRaw({
|
||||
columns: ["name", "score"],
|
||||
columns: ["zeta", "alpha"],
|
||||
column_types: ["varchar", "bigint"],
|
||||
rows: originalRows,
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 0,
|
||||
}),
|
||||
);
|
||||
const sortColumn = ref<string>();
|
||||
const sortColumnIndex = ref<number>();
|
||||
const sortDirection = ref<DataGridSortDirection>();
|
||||
const sortMode = ref<DataGridSortMode>();
|
||||
const onSort = vi.fn((column: string, columnIndex: number, direction: DataGridSortDirection | null, _whereInput?: string, mode: DataGridSortMode = "database") => {
|
||||
const indexes = direction ? sortDataGridRowIndexes(originalRows, columnIndex, direction, result.value.column_types?.[columnIndex]) : originalRows.map((_, index) => index);
|
||||
result.value = markRaw({ ...result.value, rows: indexes.map((index) => originalRows[index]!) });
|
||||
sortColumn.value = direction ? column : undefined;
|
||||
sortColumnIndex.value = direction ? columnIndex : undefined;
|
||||
sortDirection.value = direction ?? undefined;
|
||||
sortMode.value = direction ? mode : undefined;
|
||||
});
|
||||
|
||||
const host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
@@ -121,21 +90,15 @@ function mountGrid(databaseSortEnabled?: boolean) {
|
||||
h(DataGrid, {
|
||||
result: result.value,
|
||||
databaseType: "mysql",
|
||||
databaseSortEnabled,
|
||||
context: "table-data",
|
||||
sortColumn: sortColumn.value,
|
||||
sortColumnIndex: sortColumnIndex.value,
|
||||
sortDirection: sortDirection.value,
|
||||
sortMode: sortMode.value,
|
||||
tableMeta: {
|
||||
tableName: "scores",
|
||||
columns: [
|
||||
{ name: "name", data_type: "varchar", is_nullable: false, column_default: null, is_primary_key: true, extra: null },
|
||||
{ name: "score", data_type: "bigint", is_nullable: true, column_default: null, is_primary_key: false, extra: null },
|
||||
{ name: "zeta", data_type: "varchar", is_nullable: false, column_default: null, is_primary_key: true, extra: null },
|
||||
{ name: "alpha", data_type: "bigint", is_nullable: true, column_default: null, is_primary_key: false, extra: null },
|
||||
],
|
||||
primaryKeys: ["name"],
|
||||
primaryKeys: ["zeta"],
|
||||
},
|
||||
onSort,
|
||||
}),
|
||||
},
|
||||
);
|
||||
@@ -146,7 +109,7 @@ function mountGrid(databaseSortEnabled?: boolean) {
|
||||
app.use(i18n);
|
||||
app.mount(host);
|
||||
mountedApps.push({ app, host });
|
||||
return { host, onSort };
|
||||
return { host };
|
||||
}
|
||||
|
||||
async function openTranspose(host: HTMLElement) {
|
||||
@@ -158,15 +121,6 @@ async function openTranspose(host: HTMLElement) {
|
||||
await settle();
|
||||
}
|
||||
|
||||
async function selectTransposeSort(host: HTMLElement, columnIndex: number, labelKey: string) {
|
||||
const trigger = transposeField(host, columnIndex).querySelector<HTMLButtonElement>("[data-grid-transpose-sort]");
|
||||
if (!trigger) throw new Error(`Transpose sort trigger not found: ${columnIndex}`);
|
||||
trigger.click();
|
||||
await settle();
|
||||
menuAction(i18n.global.t(labelKey)).click();
|
||||
await settle();
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const { app, host } of mountedApps.splice(0)) {
|
||||
app.unmount();
|
||||
@@ -175,51 +129,26 @@ afterEach(() => {
|
||||
});
|
||||
|
||||
describe("DataGrid transpose sorting", () => {
|
||||
it("retains local sorting when database sorting is explicitly disabled", async () => {
|
||||
const { host, onSort } = mountGrid(false);
|
||||
it("sorts transpose field rows from the column-name header", async () => {
|
||||
const { host } = mountGrid();
|
||||
await settle();
|
||||
await openTranspose(host);
|
||||
transposeField(host, 1).querySelector<HTMLButtonElement>("[data-grid-transpose-sort]")!.click();
|
||||
expect(transposeFieldNames(host)).toEqual(["zeta", "alpha"]);
|
||||
host.querySelector<HTMLButtonElement>("[data-grid-transpose-column-sort]")!.click();
|
||||
await settle();
|
||||
const labels = [...document.querySelectorAll('[role="menuitem"]')].map((item) => item.textContent?.trim());
|
||||
expect(labels).toContain(i18n.global.t("grid.sortCurrentPageAscending"));
|
||||
expect(labels).not.toContain(i18n.global.t("grid.sortDatabaseDescending"));
|
||||
menuAction(i18n.global.t("grid.sortCurrentPageAscending")).click();
|
||||
await settle();
|
||||
expect(onSort).toHaveBeenLastCalledWith("score", 1, "asc", undefined, "local");
|
||||
expect(transposeValues(host, 1)).toEqual(["2", "10", "NULL"]);
|
||||
expect(transposeFieldNames(host)).toEqual(["alpha", "zeta"]);
|
||||
});
|
||||
|
||||
it("uses the shared local/database sort actions and keeps the active record and row selection", async () => {
|
||||
const { host, onSort } = mountGrid();
|
||||
it("toggles descending field-name order from the same header button", async () => {
|
||||
const { host } = mountGrid();
|
||||
await settle();
|
||||
await openTranspose(host);
|
||||
|
||||
expect(transposeValues(host, 1)).toEqual(["10", "NULL", "2"]);
|
||||
const nextRecordButton = host.querySelector(".lucide-chevron-right")?.closest<HTMLButtonElement>("button");
|
||||
if (!nextRecordButton) throw new Error("Next transpose record button not found");
|
||||
nextRecordButton.click();
|
||||
const trigger = host.querySelector<HTMLButtonElement>("[data-grid-transpose-column-sort]");
|
||||
if (!trigger) throw new Error("Transpose column sort trigger not found");
|
||||
trigger.click();
|
||||
await settle();
|
||||
expect(transposeRecordHeader(host, 0).classList.contains("transpose-record-header-selected")).toBe(true);
|
||||
expect(transposeRecordHeader(host, 1).classList.contains("transpose-record-header-active")).toBe(true);
|
||||
|
||||
await selectTransposeSort(host, 1, "grid.sortCurrentPageAscending");
|
||||
expect(onSort).toHaveBeenLastCalledWith("score", 1, "asc", undefined, "local");
|
||||
expect(transposeValues(host, 1)).toEqual(["2", "10", "NULL"]);
|
||||
expect(transposeRecordHeader(host, 1).classList.contains("transpose-record-header-selected")).toBe(true);
|
||||
expect(transposeRecordHeader(host, 2).classList.contains("transpose-record-header-active")).toBe(true);
|
||||
|
||||
await selectTransposeSort(host, 1, "grid.sortDatabaseDescending");
|
||||
expect(onSort).toHaveBeenLastCalledWith("score", 1, "desc", undefined, "database", "`score` DESC");
|
||||
expect(transposeValues(host, 1)).toEqual(["10", "2", "NULL"]);
|
||||
expect(transposeRecordHeader(host, 0).classList.contains("transpose-record-header-selected")).toBe(true);
|
||||
expect(transposeRecordHeader(host, 2).classList.contains("transpose-record-header-active")).toBe(true);
|
||||
|
||||
await selectTransposeSort(host, 1, "grid.clearSort");
|
||||
expect(onSort).toHaveBeenLastCalledWith("score", 1, null, undefined, "database", undefined);
|
||||
expect(transposeValues(host, 1)).toEqual(["10", "NULL", "2"]);
|
||||
expect(transposeRecordHeader(host, 0).classList.contains("transpose-record-header-selected")).toBe(true);
|
||||
expect(transposeRecordHeader(host, 1).classList.contains("transpose-record-header-active")).toBe(true);
|
||||
expect(host.querySelector(".transpose-grid-scroller")).not.toBeNull();
|
||||
trigger.click();
|
||||
await settle();
|
||||
expect(transposeFieldNames(host)).toEqual(["zeta", "alpha"]);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user