feat(structure): copy selected field columns

This commit is contained in:
二丫讲梵 authored and GitHub committed 2026-10-01 22:55:13 +08:00
1 parent 51b8342f5d
commit 8091054d28
2 files changed
+660 -15

No files matched your search

@@ -35,7 +35,8 @@ import { type SqlHighlighter, createShikiSqlHighlighter } from "@/lib/sql/sqlHig
import { joinSqlStatementsForScript } from "@/lib/sql/sqlBatchScript";
import { applyDdlDatabaseQualifier, formatDdlForDisplay, formatGeneratedDdlIdentifierQuotes } from "@/lib/sql/ddlDisplay";
import { splitSqlStatementRanges } from "@/lib/sql/sqlStatementRanges";
import { copyToClipboard } from "@/lib/common/clipboard";
import { copyToClipboard, eventTargetUsesNativeClipboard, isPlainClipboardShortcut } from "@/lib/common/clipboard";
import { formatTsv } from "@/lib/export/exportFormats";
import DataGridCopyColumnNamesDialog from "@/components/grid/DataGridCopyColumnNamesDialog.vue";
import { sqlFormatDialectForDbType, type SqlFormatDialect } from "@/lib/sql/sqlFormatter";
import { queryTimeoutSecsForConcurrentIndex, queryTimeoutSecsForConnection } from "@/lib/sql/queryTimeout";
@@ -1234,6 +1235,11 @@ const selectedColumnId = ref<string | null>(null);
// new rows are inserted and which row copy/add operations anchor to.
const selectedColumnIds = ref<Set<string>>(new Set());
const columnSelectionAnchorId = ref<string | null>(null);
// The editable field rows have their own selection state for batch structure
// operations. Header selection is a separate mode so clipboard actions do not
// accidentally apply row copy/drop operations to the field rows.
const selectedStructureColumnKeys = ref<Set<string>>(new Set());
const structureColumnSelectionAnchorKey = ref<string | null>(null);
const highlightedColumnId = ref<string | null>(null);
const indexSearchInputRef = ref<InstanceType<typeof Input>>();
const indexSearchText = ref("");
@@ -1506,6 +1512,123 @@ const colLabels = computed(() => {
}
return labels;
});
const copyableStructureColumnLabels = computed(() => colLabels.value.filter((label) => label.key !== "actions"));
function structureColumnSelectionClass(key: string): string {
return key !== "actions" && selectedStructureColumnKeys.value.has(key) ? "structure-grid-column-selected" : "";
}
function structureColumnClipboardValue(column: EditableStructureColumn, key: string): string {
switch (key) {
case "name":
return column.name;
case "type":
return gaussdbMDataTypeDisplayName(dataTypeBaseInputValue(databaseType.value, column.dataType));
case "length": {
if (isMysqlEnumDataType(databaseType.value, column.dataType)) return (column.enumValues ?? []).join(", ");
if (isPostgresGeometryDataType(databaseType.value, column.dataType)) {
return [postgresGeometryTypeValue(column.dataType), postgresGeometrySridValue(column.dataType)].filter(Boolean).join(", ");
}
return [dataTypeLengthInputValue(databaseType.value, column.dataType), dataTypeLengthUnitValue(databaseType.value, column.dataType)].filter(Boolean).join(" ");
}
case "nullable":
return column.isNullable ? t("structureEditor.yes") : t("structureEditor.no");
case "primaryKey":
return column.isPrimaryKey ? t("structureEditor.yes") : t("structureEditor.no");
case "defaultValue":
return column.defaultValue;
case "comment":
return column.comment;
case "characterSet":
return columnCharset(column);
case "collation":
return columnCollation(column);
case "extendedProperties":
return Object.entries(column.extra)
.filter(([, value]) => value !== undefined && value !== false && value !== "")
.map(([name, value]) => `${name}: ${typeof value === "object" ? JSON.stringify(value) : String(value)}`)
.join("; ");
default:
return "";
}
}
function structureColumnClipboardText(): string {
const labels = copyableStructureColumnLabels.value.filter((label) => selectedStructureColumnKeys.value.has(label.key));
if (labels.length === 0) return "";
const rows = columns.value.filter((column) => !column.markedForDrop).map((column) => labels.map((label) => structureColumnClipboardValue(column, label.key)));
return formatTsv(
labels.map((label) => label.label),
rows,
"",
);
}
function setStructureColumnSelection(keys: Iterable<string>, anchorKey: string | null) {
// Clears first: setColumnSelection also resets the header-column keys.
clearColumnSelection();
selectedStructureColumnKeys.value = new Set(keys);
structureColumnSelectionAnchorKey.value = anchorKey;
}
function selectStructureColumnKey(key: string, event: MouseEvent) {
if (key === "actions") return;
const labels = copyableStructureColumnLabels.value;
const index = labels.findIndex((label) => label.key === key);
if (index < 0) return;
if (event.shiftKey && structureColumnSelectionAnchorKey.value) {
const anchorIndex = labels.findIndex((label) => label.key === structureColumnSelectionAnchorKey.value);
if (anchorIndex >= 0) {
const start = Math.min(anchorIndex, index);
const end = Math.max(anchorIndex, index);
setStructureColumnSelection(
labels.slice(start, end + 1).map((label) => label.key),
structureColumnSelectionAnchorKey.value,
);
return;
}
}
if (event.metaKey || event.ctrlKey) {
const next = new Set(selectedStructureColumnKeys.value);
if (next.has(key)) next.delete(key);
else next.add(key);
setStructureColumnSelection(next, key);
return;
}
setStructureColumnSelection([key], key);
}
function selectAllStructureColumns() {
const keys = copyableStructureColumnLabels.value.map((label) => label.key);
if (keys.length > 0) setStructureColumnSelection(keys, keys[0] ?? null);
}
async function copySelectedStructureColumns() {
const text = structureColumnClipboardText();
if (!text) return;
try {
await copyToClipboard(text);
toast(t("grid.copied"));
} catch (e: any) {
toast(t("grid.copyFailed", { message: e?.message || String(e) }), 5000);
}
}
watch(
copyableStructureColumnLabels,
(labels) => {
const allowed = new Set(labels.map((label) => label.key));
const next = [...selectedStructureColumnKeys.value].filter((key) => allowed.has(key));
if (next.length !== selectedStructureColumnKeys.value.size) selectedStructureColumnKeys.value = new Set(next);
if (structureColumnSelectionAnchorKey.value && !allowed.has(structureColumnSelectionAnchorKey.value)) structureColumnSelectionAnchorKey.value = next[0] ?? null;
},
{ flush: "sync" },
);
const structureColumnRowHeight = computed(() => structureDensityMetric.value.controlHeight + structureDensityMetric.value.cellPaddingY * 2 + 1);
const columnTableWidth = computed(() => visibleColWidths.value.reduce((total, width) => total + width, 0));
function columnNeedsVariableGeometryHeight(column: EditableStructureColumn): boolean {
@@ -3013,11 +3136,18 @@ function columnIsSelectable(column: EditableStructureColumn): boolean {
return !column.markedForDrop && columns.value.some((item) => item.id === column.id);
}
/** Replace the whole selection state (set + active + shift anchor) atomically. */
/**
* Replace the whole selection state (set + active + shift anchor) atomically.
* Header-column selection and row selection are exclusive modes, so any row
* selection also clears the header-column keys, mirroring how
* `setStructureColumnSelection` clears the row selection.
*/
function setColumnSelection(ids: Iterable<string>, activeId: string | null, anchorId: string | null) {
selectedColumnIds.value = new Set(ids);
selectedColumnId.value = activeId;
columnSelectionAnchorId.value = anchorId;
selectedStructureColumnKeys.value = new Set();
structureColumnSelectionAnchorKey.value = null;
}
function clearColumnSelection() {
@@ -4560,6 +4690,20 @@ function isPlainModDeleteShortcut(event: KeyboardEvent): boolean {
function onStructureEditorKeydown(event: KeyboardEvent) {
if (event.defaultPrevented) return;
if (activeTab.value === "columns" && !eventTargetUsesNativeClipboard(event)) {
if (isPlainClipboardShortcut(event, "a")) {
event.preventDefault();
event.stopPropagation();
selectAllStructureColumns();
return;
}
if (isPlainClipboardShortcut(event, "c") && selectedStructureColumnKeys.value.size > 0) {
event.preventDefault();
event.stopPropagation();
void copySelectedStructureColumns();
return;
}
}
const focusedColumn = activeTab.value === "columns" ? focusedEditableColumn(event.target) : undefined;
if (focusedColumn && isShiftEnterShortcut(event) && canAddColumn.value) {
event.preventDefault();
@@ -5210,11 +5354,13 @@ watch(
<th
v-for="(columnLabel, i) in colLabels"
:key="columnLabel.key"
:class="[structureHeaderCellClass, { 'text-center': columnLabel.key === 'primaryKey' }]"
:class="[structureHeaderCellClass, 'bg-background select-none', { 'text-center': columnLabel.key === 'primaryKey' }]"
:data-column-selected="columnLabel.key === 'actions' ? undefined : selectedStructureColumnKeys.has(columnLabel.key)"
:style="{
width: visibleColWidths[i] + 'px',
minWidth: visibleColWidths[i] + 'px',
}"
@click="selectStructureColumnKey(columnLabel.key, $event)"
>
<template v-if="columnLabel.key === 'actions'">
<div class="flex min-w-0 items-center">
@@ -5223,7 +5369,13 @@ watch(
</div>
</template>
<template v-else>{{ columnLabel.label }}</template>
<div v-if="columnLabel.key !== 'actions' && i < colLabels.length - 1" class="absolute right-0 top-0 z-20 h-full w-1 cursor-col-resize hover:bg-primary/30" :class="colResizing?.col === columnWidthIndex(i) ? 'bg-primary/30' : ''" @mousedown="onColResize($event, i)" />
<div
v-if="columnLabel.key !== 'actions' && i < colLabels.length - 1"
class="absolute right-0 top-0 z-20 h-full w-1 cursor-col-resize hover:bg-primary/30"
:class="colResizing?.col === columnWidthIndex(i) ? 'bg-primary/30' : ''"
@mousedown="onColResize($event, i)"
@click.stop
/>
</th>
</tr>
</thead>
@@ -5248,7 +5400,7 @@ watch(
@dragover="onColumnDragOver(index, $event)"
@drop="onColumnDrop(index, $event)"
>
<td :class="structureCellClass">
<td :class="[structureCellClass, structureColumnSelectionClass('actions')]">
<div class="flex min-w-0 items-center">
<div class="flex shrink-0 items-center justify-center gap-1 border-r pr-0.5 text-muted-foreground" :style="{ width: columnOrdinalIndicatorWidth + 'px' }">
<span class="tabular-nums">{{ index + 1 }}</span>
@@ -5315,10 +5467,10 @@ watch(
</div>
</div>
</td>
<td :class="structureCellClass">
<td :class="[structureCellClass, structureColumnSelectionClass('name')]">
<Input v-model="column.name" :class="[structureControlClass, columnSearchFieldClass(column, column.name)]" :disabled="isColumnNameDisabled(column)" data-column-name-input @blur="commitColumnNameInput(column)" />
</td>
<td :class="structureCellClass">
<td :class="[structureCellClass, structureColumnSelectionClass('type')]">
<SearchableSelect
v-if="!isColumnTypeDisabled(column)"
:model-value="dataTypeBaseInputValue(databaseType, column.dataType)"
@@ -5335,7 +5487,7 @@ watch(
/>
<Input v-else :model-value="gaussdbMDataTypeDisplayName(dataTypeBaseInputValue(databaseType, column.dataType))" :class="[structureMonoControlClass, 'w-full']" disabled />
</td>
<td v-if="columnEditorControls.length" :class="structureCellClass">
<td v-if="columnEditorControls.length" :class="[structureCellClass, structureColumnSelectionClass('length')]">
<Popover v-if="isMysqlEnumDataType(databaseType, column.dataType)">
<PopoverTrigger as-child>
<Button variant="outline" size="sm" :class="[structureMonoControlClass, 'w-full justify-between px-2']" :disabled="isColumnTypeDisabled(column)">
@@ -5407,13 +5559,13 @@ watch(
</Select>
</div>
</td>
<td v-if="columnEditorControls.nullable" :class="structureCellClass">
<td v-if="columnEditorControls.nullable" :class="[structureCellClass, structureColumnSelectionClass('nullable')]">
<label class="flex items-center gap-1.5">
<input v-model="column.isNullable" type="checkbox" :class="structureCheckboxClass" :disabled="isColumnNullableDisabled(column)" />
<span>{{ column.isNullable ? t("structureEditor.yes") : t("structureEditor.no") }}</span>
</label>
</td>
<td v-if="columnEditorControls.primaryKey" :class="[structureCellClass, 'text-center']">
<td v-if="columnEditorControls.primaryKey" :class="[structureCellClass, 'text-center', structureColumnSelectionClass('primaryKey')]">
<input
v-model="column.isPrimaryKey"
type="checkbox"
@@ -5426,7 +5578,7 @@ watch(
"
/>
</td>
<td v-if="columnEditorControls.defaultValue" :class="structureCellClass">
<td v-if="columnEditorControls.defaultValue" :class="[structureCellClass, structureColumnSelectionClass('defaultValue')]">
<div class="flex min-w-0 items-center gap-1">
<Input v-model="column.defaultValue" :class="[structureMonoControlClass, 'flex-1']" :disabled="isColumnDefaultDisabled(column)" />
<DropdownMenu>
@@ -5443,7 +5595,7 @@ watch(
</DropdownMenu>
</div>
</td>
<td v-if="columnEditorControls.comment" :class="structureCellClass">
<td v-if="columnEditorControls.comment" :class="[structureCellClass, structureColumnSelectionClass('comment')]">
<div class="flex min-w-0 items-center gap-1">
<Input v-model="column.comment" :class="[structureControlClass, 'flex-1', columnSearchFieldClass(column, column.comment)]" :disabled="isColumnCommentDisabled(column)" />
<Popover>
@@ -5471,7 +5623,7 @@ watch(
</Popover>
</div>
</td>
<td v-if="showCharacterSet" :class="structureCellClass">
<td v-if="showCharacterSet" :class="[structureCellClass, structureColumnSelectionClass('characterSet')]">
<SearchableSelect
:model-value="columnCharset(column)"
:options="mysqlCharsetOptions"
@@ -5484,7 +5636,7 @@ watch(
@update:model-value="(v: string) => onCharsetChange(column, v)"
/>
</td>
<td v-if="showCharacterSet" :class="structureCellClass">
<td v-if="showCharacterSet" :class="[structureCellClass, structureColumnSelectionClass('collation')]">
<SearchableSelect
:model-value="columnCollation(column)"
:options="collationOptionsForCharset(columnCharset(column))"
@@ -5497,7 +5649,7 @@ watch(
@update:model-value="(v: string) => (column.collation = v)"
/>
</td>
<td v-if="showExtendedProperties" :class="structureCellClass">
<td v-if="showExtendedProperties" :class="[structureCellClass, structureColumnSelectionClass('extendedProperties')]">
<div :class="structurePropertyListClass">
<!-- Manticore Search: character data type properties -->
<template v-if="databaseType === 'manticoresearch'">
@@ -6422,6 +6574,15 @@ watch(
</template>
<style scoped>
.structure-grid-column-selected {
background-color: color-mix(in oklab, var(--primary) 14%, transparent) !important;
}
.structure-grid-column-selected :deep(input),
.structure-grid-column-selected :deep(button) {
background-color: color-mix(in oklab, var(--primary) 10%, var(--background)) !important;
}
.structure-ddl-editor :deep(.cm-editor) {
min-height: 100%;
background: transparent;
@@ -0,0 +1,484 @@
// @vitest-environment happy-dom
import { createApp, nextTick, type App } from "vue";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
connection: {
id: "structure-column-copy-test",
name: "MySQL",
db_type: "mysql",
driver_profile: "mysql",
driver_label: "MySQL",
},
copyToClipboard: vi.fn(),
ensureConnected: vi.fn(),
executeQuery: vi.fn(),
listDataTypes: vi.fn(),
buildTableStructureChangeSql: vi.fn(),
buildMysqlAutoIncrementSql: vi.fn(),
getMysqlTableAutoIncrement: vi.fn(),
executeBatch: vi.fn(),
updateEditorSettings: vi.fn(),
loadObjectDdl: vi.fn(),
invalidateObjectDdl: vi.fn(),
loadObjectMetadataFacet: vi.fn(),
invalidateObjectMetadataCache: vi.fn(),
invalidateTableMetadataCache: vi.fn(),
toast: vi.fn(),
}));
vi.mock("vue-i18n", () => ({ useI18n: () => ({ t: (key: string) => key }) }));
vi.mock("@lucide/vue", async () => {
const { defineComponent, h } = await import("vue");
const Icon = defineComponent({ name: "Icon", setup: () => () => h("span") });
return {
AlertTriangle: Icon,
Check: Icon,
ChevronDown: Icon,
ChevronUp: Icon,
ClipboardList: Icon,
Copy: Icon,
Database: Icon,
Info: Icon,
Keyboard: Icon,
KeyRound: Icon,
ListChevronsUpDown: Icon,
Loader2: Icon,
Maximize2: Icon,
Pencil: Icon,
Plus: Icon,
RefreshCw: Icon,
Rows3: Icon,
Save: Icon,
Search: Icon,
Settings: Icon,
SlidersHorizontal: Icon,
Trash2: Icon,
UserRound: Icon,
X: Icon,
};
});
vi.mock("@/components/ui/button", async () => {
const { defineComponent, h } = await import("vue");
return {
Button: defineComponent({
name: "Button",
inheritAttrs: false,
setup:
(_props, { attrs, slots }) =>
() =>
h("button", attrs, slots.default?.()),
}),
};
});
vi.mock("@/components/ui/input", async () => {
const { defineComponent, h } = await import("vue");
return {
Input: defineComponent({
name: "Input",
inheritAttrs: false,
props: { modelValue: { type: [String, Number], default: "" } },
emits: ["update:modelValue"],
setup:
(props, { attrs, emit }) =>
() =>
h("input", {
...attrs,
value: props.modelValue,
onInput: (event: Event) => emit("update:modelValue", (event.target as HTMLInputElement).value),
}),
}),
};
});
vi.mock("@/components/ui/badge", async () => {
const { defineComponent, h } = await import("vue");
return {
Badge: defineComponent({
name: "Badge",
inheritAttrs: false,
setup:
(_props, { attrs, slots }) =>
() =>
h("span", attrs, slots.default?.()),
}),
};
});
vi.mock("@/components/ui/tabs", async () => {
const { defineComponent, h } = await import("vue");
const Div = defineComponent({
inheritAttrs: false,
setup:
(_props, { attrs, slots }) =>
() =>
h("div", attrs, slots.default?.()),
});
const Button = defineComponent({
inheritAttrs: false,
setup:
(_props, { attrs, slots }) =>
() =>
h("button", attrs, slots.default?.()),
});
return { Tabs: Div, TabsContent: Div, TabsList: Div, TabsTrigger: Button };
});
vi.mock("@/components/ui/dropdown-menu", async () => {
const { defineComponent, h } = await import("vue");
const Div = defineComponent({
inheritAttrs: false,
setup:
(_props, { attrs, slots }) =>
() =>
h("div", attrs, slots.default?.()),
});
const Button = defineComponent({
inheritAttrs: false,
setup:
(_props, { attrs, slots }) =>
() =>
h("button", attrs, slots.default?.()),
});
return { DropdownMenu: Div, DropdownMenuCheckboxItem: Div, DropdownMenuContent: Div, DropdownMenuItem: Button, DropdownMenuTrigger: Div };
});
vi.mock("@/components/ui/popover", async () => {
const { defineComponent, h } = await import("vue");
const Div = defineComponent({
inheritAttrs: false,
setup:
(_props, { attrs, slots }) =>
() =>
h("div", attrs, slots.default?.()),
});
return { Popover: Div, PopoverContent: Div, PopoverTrigger: Div };
});
vi.mock("@/components/ui/tooltip", async () => {
const { defineComponent, h } = await import("vue");
const Div = defineComponent({
inheritAttrs: false,
setup:
(_props, { attrs, slots }) =>
() =>
h("div", attrs, slots.default?.()),
});
return { Tooltip: Div, TooltipContent: Div, TooltipTrigger: Div };
});
vi.mock("@/components/ui/searchable-select", async () => {
const { defineComponent, h } = await import("vue");
return {
SearchableSelect: defineComponent({
name: "SearchableSelect",
inheritAttrs: false,
props: {
modelValue: { type: String, default: "" },
options: { type: Array, default: () => [] },
allowCustom: { type: Boolean, default: false },
},
emits: ["update:modelValue"],
setup:
(props, { attrs }) =>
() =>
h("button", {
...attrs,
type: "button",
"data-searchable-select": "true",
"data-model-value": props.modelValue,
"data-options": JSON.stringify(props.options),
"data-allow-custom": String(props.allowCustom),
}),
}),
};
});
vi.mock("@/components/ui/select", async () => {
const { defineComponent, h } = await import("vue");
const Div = defineComponent({
inheritAttrs: false,
setup:
(_props, { attrs, slots }) =>
() =>
h("div", attrs, slots.default?.()),
});
return { Select: Div, SelectContent: Div, SelectItem: Div, SelectTrigger: Div, SelectValue: Div };
});
vi.mock("@/stores/connectionStore", () => ({
useConnectionStore: () => ({
ensureConnected: mocks.ensureConnected,
getConfig: (connectionId: string) => (connectionId === mocks.connection.id ? mocks.connection : undefined),
}),
}));
vi.mock("@/stores/productionSafetyStore", () => ({ useProductionSafetyStore: () => ({ requestConfirmation: vi.fn() }) }));
vi.mock("@/stores/queryStore", () => ({ useQueryStore: () => ({ tableStructureRefreshVersion: () => 0 }) }));
vi.mock("@/stores/historyStore", () => ({ useHistoryStore: () => ({ add: vi.fn() }) }));
vi.mock("@/stores/settingsStore", () => ({
useSettingsStore: () => ({
editorSettings: { structureEditorDensity: "compact", sqlFormatter: {}, tableColumnTemplateFields: [], generateSqlQuoteIdentifiers: true },
updateEditorSettings: mocks.updateEditorSettings,
}),
}));
vi.mock("@/composables/useTheme", () => ({ useTheme: () => ({ isDark: { value: false } }) }));
vi.mock("@/composables/useToast", () => ({ useToast: () => ({ toast: mocks.toast }) }));
vi.mock("@/lib/sql/sqlHighlighter", () => ({ createShikiSqlHighlighter: vi.fn(async () => (sql: string) => sql) }));
vi.mock("@/lib/metadata/objectDdlCache", () => ({
loadObjectDdl: mocks.loadObjectDdl,
invalidateObjectDdl: mocks.invalidateObjectDdl,
}));
vi.mock("@/lib/metadata/objectMetadataCache", () => ({ loadObjectMetadataFacet: mocks.loadObjectMetadataFacet, invalidateObjectMetadataCache: mocks.invalidateObjectMetadataCache }));
vi.mock("@/lib/metadata/tableMetadataCache", () => ({ invalidateTableMetadataCache: mocks.invalidateTableMetadataCache }));
vi.mock("@/lib/backend/api", () => ({
executeQuery: mocks.executeQuery,
listDataTypes: mocks.listDataTypes,
buildTableStructureChangeSql: mocks.buildTableStructureChangeSql,
buildMysqlAutoIncrementSql: mocks.buildMysqlAutoIncrementSql,
getMysqlTableAutoIncrement: mocks.getMysqlTableAutoIncrement,
executeBatch: mocks.executeBatch,
}));
// Keep the real shortcut guards (native-clipboard detection) and only stub the
// write side, so tests observe exactly what the editor would copy.
vi.mock("@/lib/common/clipboard", async (importOriginal) => ({
...((await importOriginal()) as object),
copyToClipboard: mocks.copyToClipboard,
}));
import TableStructureEditor from "@/components/structure/TableStructureEditor.vue";
const mountedApps: App[] = [];
type SeedColumn = {
name: string;
dataType: string;
isNullable: boolean;
isPrimaryKey?: boolean;
comment?: string;
markedForDrop?: boolean;
};
function draftWithColumns(seed: SeedColumn[]) {
return {
initialized: true,
activeTab: "columns" as const,
newTableName: "",
tableComment: "",
originalTableComment: "",
columns: seed.map((column, index) => ({
id: `existing:${column.name}`,
name: column.name,
dataType: column.dataType,
isNullable: column.isNullable,
defaultValue: "",
comment: column.comment ?? "",
isPrimaryKey: column.isPrimaryKey ?? false,
characterSet: "",
collation: "",
extra: {},
original: {
name: column.name,
data_type: column.dataType,
is_nullable: column.isNullable,
column_default: null,
is_primary_key: column.isPrimaryKey ?? false,
extra: null,
comment: null,
},
originalPosition: index,
markedForDrop: column.markedForDrop ?? false,
})),
indexes: [],
foreignKeys: [],
triggers: [],
};
}
/** id/name stay, "legacy" is drop-marked so copy output must exclude it. */
function defaultSeed(): SeedColumn[] {
return [
{ name: "id", dataType: "int", isNullable: false, isPrimaryKey: true },
{ name: "name", dataType: "varchar(64)", isNullable: true, comment: "user name" },
{ name: "legacy", dataType: "int", isNullable: true, markedForDrop: true },
];
}
async function mountEditor(draft: ReturnType<typeof draftWithColumns>) {
mocks.ensureConnected.mockResolvedValue(undefined);
mocks.listDataTypes.mockResolvedValue([]);
mocks.buildTableStructureChangeSql.mockResolvedValue({ statements: [], warnings: [] });
mocks.copyToClipboard.mockResolvedValue(undefined);
const root = document.createElement("div");
document.body.append(root);
const app = createApp(TableStructureEditor, {
connectionId: mocks.connection.id,
database: "test",
schema: "test",
tableName: "user",
draft,
});
mountedApps.push(app);
app.mount(root);
await nextTick();
await Promise.resolve();
await nextTick();
await vi.waitFor(() => expect(root.querySelector("[data-column-name-input]")).not.toBeNull(), { timeout: 3000 });
return root;
}
/** Header cells of the editable columns grid (its header table is separate from the per-row body tables). */
function headerCells(root: HTMLElement): HTMLTableCellElement[] {
return [...root.querySelectorAll<HTMLTableCellElement>(".structure-column-virtual-header-table thead th")];
}
function headerCell(root: HTMLElement, label: string): HTMLTableCellElement {
// The actions header renders buttons around its label, so match by inclusion.
const cell = headerCells(root).find((th) => (th.textContent ?? "").includes(label));
expect(cell, `missing header cell ${label}`).toBeDefined();
return cell!;
}
function clickHeader(root: HTMLElement, label: string, modifiers: { ctrl?: boolean; shift?: boolean } = {}) {
headerCell(root, label).dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true, ctrlKey: !!modifiers.ctrl, shiftKey: !!modifiers.shift }));
}
/** Header labels (i18n keys) currently flagged data-column-selected="true". */
function selectedHeaderLabels(root: HTMLElement): string[] {
return headerCells(root)
.filter((th) => th.dataset.columnSelected === "true")
.map((th) => th.textContent?.trim() ?? "");
}
function columnNameCells(root: HTMLElement): HTMLTableCellElement[] {
return [...root.querySelectorAll<HTMLInputElement>("[data-column-name-input]")].map((input) => input.closest("td") as HTMLTableCellElement);
}
function dispatchShortcut(target: Element, key: string): KeyboardEvent {
const event = new KeyboardEvent("keydown", { key, metaKey: true, bubbles: true, cancelable: true });
target.dispatchEvent(event);
return event;
}
beforeEach(() => {
vi.clearAllMocks();
mocks.connection.db_type = "mysql";
mocks.connection.driver_profile = "mysql";
mocks.loadObjectDdl.mockResolvedValue({ ddl: "CREATE TABLE user (id int)", cacheStatus: "remote" });
mocks.loadObjectMetadataFacet.mockResolvedValue({ value: [], cacheStatus: "remote" });
mocks.getMysqlTableAutoIncrement.mockResolvedValue(null);
mocks.buildMysqlAutoIncrementSql.mockResolvedValue("");
mocks.executeBatch.mockResolvedValue({ affected_rows: 0 });
});
afterEach(() => {
for (const app of mountedApps.splice(0)) app.unmount();
document.body.innerHTML = "";
});
describe("TableStructureEditor header column selection", () => {
it("selects a single column on header click and highlights its cells", async () => {
const root = await mountEditor(draftWithColumns(defaultSeed()));
clickHeader(root, "structureEditor.columnName");
await nextTick();
expect(selectedHeaderLabels(root)).toEqual(["structureEditor.columnName"]);
// The actions header never participates in column selection.
expect(headerCell(root, "structureEditor.actions").dataset.columnSelected).toBeUndefined();
for (const cell of columnNameCells(root)) expect(cell.classList.contains("structure-grid-column-selected")).toBe(true);
});
it("toggles columns with ctrl-click", async () => {
const root = await mountEditor(draftWithColumns(defaultSeed()));
clickHeader(root, "structureEditor.columnName");
clickHeader(root, "structureEditor.dataType", { ctrl: true });
await nextTick();
expect(selectedHeaderLabels(root)).toEqual(["structureEditor.columnName", "structureEditor.dataType"]);
clickHeader(root, "structureEditor.dataType", { ctrl: true });
await nextTick();
expect(selectedHeaderLabels(root)).toEqual(["structureEditor.columnName"]);
});
it("selects the range between anchor and target on shift-click", async () => {
const root = await mountEditor(draftWithColumns(defaultSeed()));
clickHeader(root, "structureEditor.columnName");
clickHeader(root, "structureEditor.comment", { shift: true });
await nextTick();
expect(selectedHeaderLabels(root)).toEqual(["structureEditor.columnName", "structureEditor.dataType", "structureEditor.length", "structureEditor.nullable", "structureEditor.primaryKey", "structureEditor.defaultValue", "structureEditor.comment"]);
});
it("clears the header selection when a field row is clicked", async () => {
const root = await mountEditor(draftWithColumns(defaultSeed()));
clickHeader(root, "structureEditor.columnName");
await nextTick();
expect(selectedHeaderLabels(root)).toEqual(["structureEditor.columnName"]);
// Click an ordinary field row (drop-marked rows are not selectable).
const row = root.querySelector<HTMLElement>('tr[data-column-id="existing:id"]')!;
expect(row).not.toBeNull();
row.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
row.dispatchEvent(new MouseEvent("click", { bubbles: true, cancelable: true }));
await nextTick();
expect(selectedHeaderLabels(root)).toEqual([]);
for (const cell of columnNameCells(root)) expect(cell.classList.contains("structure-grid-column-selected")).toBe(false);
});
});
describe("TableStructureEditor column selection copy shortcuts", () => {
it("selects every copyable column on Cmd+A outside editable targets", async () => {
const root = await mountEditor(draftWithColumns(defaultSeed()));
const event = dispatchShortcut(document.body, "a");
expect(event.defaultPrevented).toBe(true);
await nextTick();
const selected = selectedHeaderLabels(root);
const expected = headerCells(root)
.map((th) => th.textContent?.trim() ?? "")
.filter((label) => !label.includes("structureEditor.actions"));
expect(selected).toEqual(expected);
});
it("copies the selected columns as TSV on Cmd+C and excludes drop-marked rows", async () => {
const root = await mountEditor(draftWithColumns(defaultSeed()));
clickHeader(root, "structureEditor.columnName");
clickHeader(root, "structureEditor.dataType", { ctrl: true });
clickHeader(root, "structureEditor.nullable", { ctrl: true });
await nextTick();
const event = dispatchShortcut(document.body, "c");
expect(event.defaultPrevented).toBe(true);
await vi.waitFor(() => expect(mocks.copyToClipboard).toHaveBeenCalledTimes(1), { timeout: 3000 });
// Labels and yes/no literals come back as raw i18n keys because the test
// i18n mock is the identity; the base type of `varchar(64)` is `varchar`.
expect(mocks.copyToClipboard).toHaveBeenCalledWith("structureEditor.columnName\tstructureEditor.dataType\tstructureEditor.nullable\nid\tint\tstructureEditor.no\nname\tvarchar\tstructureEditor.yes");
await vi.waitFor(() => expect(mocks.toast).toHaveBeenCalledWith("grid.copied"), { timeout: 3000 });
});
it("leaves Cmd+A/Cmd+C to the browser when an input is focused", async () => {
const root = await mountEditor(draftWithColumns(defaultSeed()));
const input = root.querySelector<HTMLInputElement>("[data-column-name-input]")!;
const selectAll = dispatchShortcut(input, "a");
const copy = dispatchShortcut(input, "c");
expect(selectAll.defaultPrevented).toBe(false);
expect(copy.defaultPrevented).toBe(false);
expect(selectedHeaderLabels(root)).toEqual([]);
expect(mocks.copyToClipboard).not.toHaveBeenCalled();
});
it("does not intercept Cmd+C when no column is selected", async () => {
await mountEditor(draftWithColumns(defaultSeed()));
const event = dispatchShortcut(document.body, "c");
expect(event.defaultPrevented).toBe(false);
expect(mocks.copyToClipboard).not.toHaveBeenCalled();
});
});