Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: table/list keyAttribute error if not unique (fixes SFKUI-6936) #284

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions etc/vue.api.md
Original file line number Diff line number Diff line change
Expand Up @@ -7798,6 +7798,7 @@ callbackBeforeItemDelete(item: ListItem): void;
escapeNewlines(value: string): string;
updateActiveRowFromVModel(): void;
setActiveRow(row: ListItem | undefined): void;
confirmUniqueKey(): void;
}, ComponentOptions, ComponentOptionsMixin, ("change" | "click" | "select" | "collapse" | "update:modelValue" | "expand" | "unselect" | "update:active")[], "change" | "click" | "select" | "collapse" | "update:modelValue" | "expand" | "unselect" | "update:active", PublicProps, Readonly<ExtractPropTypes< {
rows: {
type: PropType<ListArray>;
Expand Down
14 changes: 14 additions & 0 deletions packages/vue/src/components/FDataTable/FDataTable.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,20 @@ it("should call provided sort method when clicking columnheader that is registra
`);
});

it("should throw error if `keyAttribute` is not unique", async () => {
expect.assertions(1);
expect(() => {
mount(FDataTable, {
props: {
rows: [{ id: "a" }, { id: "b" }, { id: "b" }],
keyAttribute: "id",
},
});
}).toThrowErrorMatchingInlineSnapshot(
`"Expected each table row to have a unique key attribute but encountered duplicate of "b" in row index 2."`,
);
});

describe("html-validate", () => {
it("should require non-empty key-attribute attribute", () => {
expect.assertions(2);
Expand Down
70 changes: 60 additions & 10 deletions packages/vue/src/components/FDataTable/FDataTable.vue
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ Default text is 'Tabellen är tom' (key fkui.data-table.empty).
<slot name="empty">{{ $t("fkui.data-table.empty", "Tabellen är tom") }}</slot>
</td>
</tr>
<tr v-for="row in rows" :key="rowKey(row)" class="table__row">
<tr v-for="row in internalRows" :key="rowKey(row)" class="table__row">
<!--
@slot Slot for table row.

Expand All @@ -59,7 +59,7 @@ Default text is 'Tabellen är tom' (key fkui.data-table.empty).

<script lang="ts">
import { type PropType, computed, defineComponent, provide } from "vue";
import { type ListArray, type ListItem } from "../../types";
import { type ListItem } from "../../types";
import { TableScroll, tableScrollClasses, hasSlot } from "../../utils";
import {
FTableColumnData,
Expand All @@ -77,6 +77,17 @@ import { FSortFilterDatasetInjected, FSortFilterDatasetInterface } from "../FSor
import { FIcon } from "../FIcon";
import { TranslationMixin } from "../../plugins";

interface InternalListItem extends ListItem {
[internalKey]: string;
}
interface MapItem {
id: string;
item: InternalListItem;
}

const internalKey = Symbol("table-key");
let internalIndex = 0;

export default defineComponent({
name: "FDataTable",
components: {
Expand Down Expand Up @@ -104,15 +115,16 @@ export default defineComponent({
* The rows will be listed in the given array order.
*/
rows: {
type: Array as PropType<ListArray>,
type: Array as PropType<ListItem[]>,
required: true,
},
/**
* Unique attribute in rows.
*/
keyAttribute: {
type: String,
required: true,
required: false,
default: undefined,
},
/**
* If `true` alternating rows will use a different background color.
Expand Down Expand Up @@ -150,6 +162,7 @@ export default defineComponent({
data() {
return {
columns: [] as FTableColumnData[],
map: [] as MapItem[],
};
},
computed: {
Expand All @@ -175,18 +188,55 @@ export default defineComponent({
tabindex(): number | undefined {
return this.scroll !== TableScroll.NONE ? 0 : undefined;
},
internalRows(): InternalListItem[] {
const { keyAttribute } = this;
if (keyAttribute) {
const seenKeys: Set<unknown> = new Set<unknown>();

return this.rows.map((row, index) => {
const key = row[keyAttribute];
if (key === undefined) {
throw new Error(`Key attribute [${this.keyAttribute}]' is missing in row index ${index}`);
}

const rowKey = String(key);
if (seenKeys.has(rowKey)) {
throw new Error(
`Expected each table row to have a unique key attribute but encountered duplicate of "${rowKey}" in row index ${index}.`,
);
}

seenKeys.add(rowKey);

// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- dsad
// @ts-ignore -- dsad
row[internalKey] = rowKey;

return row as InternalListItem;
});
}

return this.rows.map((row) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- dsad
// @ts-ignore -- dsad
if (row[internalKey] === undefined) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- dsad
// @ts-ignore -- dsad
row[internalKey] = String(internalIndex++);
}
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- dsad
// @ts-ignore -- dsad
return row as InternalListItem;
});
},
},
mounted() {
this.registerCallbackOnSort(this.callbackOnSort);
this.registerCallbackOnMount(this.callbackSortableColumns);
},
methods: {
rowKey(item: ListItem): string {
const key = item[this.keyAttribute];
if (typeof key === "undefined") {
throw new Error(`Key attribute [${this.keyAttribute}]' is missing in row`);
}
return String(key);
rowKey(item: InternalListItem): string {
return item[internalKey];
},
columnClasses(column: FTableColumnData): string[] {
const classes = ["table__column", `table__column--${column.type}`, column.size];
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -956,6 +956,37 @@ it("should call provided sort method when clicking columnheader that is registra
`);
});

describe("`keyAttribute` prop", () => {
it("should throw error if not unique in row", async () => {
expect.assertions(1);
expect(() => {
mount(FInteractiveTable, {
props: {
rows: [{ id: "a" }, { id: "b" }, { id: "b" }],
keyAttribute: "id",
},
});
}).toThrowErrorMatchingInlineSnapshot(
`"Expected each row to have a unique key attribute but encountered duplicate of "b" in row index 2."`,
);
});

it("should throw error if not unique in expandable row", async () => {
expect.assertions(1);
expect(() => {
mount(FInteractiveTable, {
props: {
rows: [{ id: "a" }, { id: "b", more: [{ id: "a" }] }],
keyAttribute: "id",
expandableAttribute: "more",
},
});
}).toThrowErrorMatchingInlineSnapshot(
`"Expected each row to have a unique key attribute but encountered duplicate of "a" in expandable row index 0 of row index 1."`,
);
});
});

describe("Expandable rows", () => {
it("Should handle slot content in expanded rows", () => {
expect.assertions(3);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -395,6 +395,8 @@ export default defineComponent({
return includeItem(row, this.rows, this.keyAttribute);
});
}

this.confirmUniqueKey();
},
},
active: {
Expand Down Expand Up @@ -616,6 +618,49 @@ export default defineComponent({
*/
this.$emit("update:active", this.activeRow);
},
confirmUniqueKey(): void {
const seenKeys: Record<string, boolean> = {};

for (const row of this.rows) {
const rowKey = String(row[this.keyAttribute]);
if (seenKeys[rowKey]) {
const index = this.rows.indexOf(row);
const msg =
`Expected each row to have a unique key attribute but ` +
`encountered duplicate of "${rowKey}" in row index ${index}.`;

throw new Error(msg);
}

seenKeys[rowKey] = true;
}

if (!this.isExpandableTable) {
return;
}

for (const row of this.rows) {
const expandableRows = this.expandableRows(row);
if (expandableRows === undefined) {
continue;
}

for (const expandableRow of expandableRows) {
const rowKey = String(expandableRow[this.keyAttribute]);
if (seenKeys[rowKey]) {
const index = this.rows.indexOf(row);
const expandableIndex = expandableRows.indexOf(expandableRow);
const msg =
`Expected each row to have a unique key attribute but encountered duplicate` +
` of "${rowKey}" in expandable row index ${expandableIndex} of row index ${index}.`;

throw new Error(msg);
}

seenKeys[rowKey] = true;
}
}
},
},
});
</script>
16 changes: 16 additions & 0 deletions packages/vue/src/components/FList/FList.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -526,6 +526,22 @@ describe("screenreader slot", () => {
});
});

describe("`keyAttribute` prop", () => {
it("should throw error if `keyAttribute` is not unique", async () => {
expect.assertions(1);
expect(() => {
mount(FList, {
props: {
items: [{ id: "a" }, { id: "b" }, { id: "b" }],
keyAttribute: "id",
},
});
}).toThrowErrorMatchingInlineSnapshot(
`"Expected each list item to have a unique key attribute but encountered duplicate of "b" in item index 2."`,
);
});
});

describe("html-validate", () => {
it("should require non-empty key-attribute attribute", () => {
expect.assertions(2);
Expand Down
13 changes: 13 additions & 0 deletions packages/vue/src/components/FList/FList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,19 @@ export default defineComponent({
immediate: true,
handler: function () {
this.updateSelectedItemsFromVModel();

const seenKeys: Record<string, boolean> = {};
for (const item of this.items) {
const rowKey = String(item[this.keyAttribute]);
if (seenKeys[rowKey]) {
const index = this.items.indexOf(item);
throw new Error(
`Expected each list item to have a unique key attribute but encountered duplicate of "${rowKey}" in item index ${index}.`,
);
}

seenKeys[rowKey] = true;
}
},
},
modelValue: {
Expand Down
Loading
Loading