8000 Preserve hidden positions when reordering profile attributes by FayezBast · Pull Request #55560 · keycloak/keycloak · GitHub
[go: up one dir, main page]

Skip to content
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
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ type DraggableTableProps<T> = Omit<TableProps, "data" | "ref"> & {
data: T[];
actions?: Action<T>[];
onDragFinish: (dragged: string, newOrder: string[]) => void;
restoreOrderOnDrop?: boolean;
};

export function DraggableTable<T>({
Expand All @@ -45,6 +46,7 @@ export function DraggableTable<T>({
data,
actions,
onDragFinish,
restoreOrderOnDrop,
...props
}: DraggableTableProps<T>) {
const { t } = useTranslation();
Expand All @@ -59,7 +61,7 @@ export function DraggableTable<T>({

const itemOrder: string[] = useMemo(
() => data.map((d) => get(d, keyField)),
[data],
[data, keyField],
);

const ReactDragEvent) => {
Expand Down Expand Up @@ -130,8 +132,15 @@ export function DraggableTable<T>({
};

const ReactDragEvent) => {
evt.preventDefault();
if (restoreOrderOnDrop) {
// The data supplied by the caller determines the committed order.
move(itemOrder);
}
if (isValidDrop(evt)) {
onDragFinish(state.draggedItemId, state.tempItemOrder);
if (state.draggingToItemIndex !== -1) {
onDragFinish(state.draggedItemId, state.tempItemOrder);
}
} else {
onDragCancel();
}
Expand All @@ -154,8 +163,9 @@ export function DraggableTable<T>({
bodyRef.current?.children || [],
).findIndex((item) => item.id === dragId);
if (draggingToItemIndex !== state.draggingToItemIndex) {
// Tables that keep the dropped order use it for the next drag.
const tempItemOrder = moveItem(
itemOrder,
restoreOrderOnDrop ? [...itemOrder] : itemOrder,
state.draggedItemId,
draggingToItemIndex,
);
Expand All @@ -171,6 +181,9 @@ export function DraggableTable<T>({
};

const ReactDragEvent) => {
if (restoreOrderOnDrop) {
move(itemOrder);
}
const tr = evt.target as HTMLTableRowElement;
tr.classList.remove(styles.modifiers.ghostRow);
tr.setAttribute("aria-grabbed", "false");
Expand Down Expand Up @@ -211,12 +224,7 @@ export function DraggableTable<T>({
))}
</Tr>
</Thead>
<Tbody
ref={bodyRef}
>
>
>
>
<Tbody ref={bodyRef} >
{data.map((row) => (
<Tr
key={get(row, keyField)}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,6 @@ import { useUserProfile } from "./UserProfileContext";

const RESTRICTED_ATTRIBUTES = ["username", "email"];

type movedAttributeType = UserProfileAttribute;

type AttributesTabProps = {
setTableData: React.Dispatch<
React.SetStateAction<Record<string, string>[] | undefined>
Expand All @@ -37,16 +35,17 @@ type AttributesTabProps = {

export const AttributesTab = ({ setTableData }: AttributesTabProps) => {
const { adminClient } = useAdminClient();
const { config, save } = useUserProfile();
const { config, save, isSaving } = useUserProfile();
const { realm } = useRealm();
const { t } = useTranslation();
const combinedLocales = useLocale();
const navigate = useNavigate();
const [filter, setFilter] = useState("allGroups");
const [isFilterTypeDropdownOpen, toggleIsFilterTypeDropdownOpen] =
useToggle();
const [data, setData] = useState(config?.attributes);
const [attributeToDelete, setAttributeToDelete] = useState("");
const [isDeleting, setIsDeleting] = useState(false);
const isUpdating = isSaving || isDeleting;

const [toggleDeleteDialog, DeleteConfirm] = useConfirmDialog({
titleKey: t("deleteAttributeConfirmTitle"),
Expand All @@ -55,8 +54,9 @@ export const AttributesTab = ({ setTableData }: AttributesTabProps) => {
}),
continueButtonLabel: t("delete"),
continueButtonVariant: ButtonVariant.danger,
confirmButtonDisabled: isUpdating,
onConfirm: async () => {
if (!config?.attributes) return;
if (isUpdating || !config?.attributes) return;

const translationsToDelete = config.attributes.find(
(attribute) => attribute.name === attributeToDelete,
Expand All @@ -71,6 +71,7 @@ export const AttributesTab = ({ setTableData }: AttributesTabProps) => {
? translationsToDelete.slice(2, -1)
: undefined;

setIsDeleting(true);
try {
if (formattedTranslationsToDelete) {
await Promise.all(
Expand Down Expand Up @@ -120,6 +121,8 @@ export const AttributesTab = ({ setTableData }: AttributesTabProps) => {
console.error(
`Error removing translations or updating attributes: ${error}`,
);
} finally {
setIsDeleting(false);
}
},
});
Expand All @@ -129,23 +132,37 @@ export const AttributesTab = ({ setTableData }: AttributesTabProps) => {
}

const attributes = config.attributes ?? [];
const groups = config.groups ?? [];
const matchesFilter = (attribute: UserProfileAttribute) =>
filter === "allGroups" || attribute.group === filter;
const visibleAttributes = attributes.filter(matchesFilter);

const executeMove = async (
attribute: UserProfileAttribute,
newIndex: number,
) => {
const fromIndex = attributes.findIndex((attr) => {
return attr.name === attribute.name;
});
const executeMove = async (nameDragged: string, newOrder: string[]) => {
const fromIndex = visibleAttributes.findIndex(
(attribute) => attribute.name === nameDragged,
);
const toIndex = newOrder.indexOf(nameDragged);
if (
isUpdating ||
newOrder.length !== visibleAttributes.length ||
fromIndex < 0 ||
toIndex < 0 ||
fromIndex === toIndex
) {
return;
}

let movedAttribute: movedAttributeType = {};
movedAttribute = attributes[fromIndex];
attributes.splice(fromIndex, 1);
attributes.splice(newIndex, 0, movedAttribute);
const reordered = [...visibleAttributes];
const [movedAttribute] = reordered.splice(fromIndex, 1);
reordered.splice(toIndex, 0, movedAttribute);

// Refill the slots in the full list that belong to the visible attributes.
let visibleIndex = 0;
const updatedAttributes = attributes.map((attribute) =>
matchesFilter(attribute) ? reordered[visibleIndex++] : attribute,
);

await save(
{ ...config, attributes, groups },
{ ...config, attributes: updatedAttributes, groups: config.groups ?? [] },
{
successMessageKey: "updatedUserProfileSuccess",
errorMessageKey: "updatedUserProfileError",
Expand Down Expand Up @@ -179,13 +196,7 @@ export const AttributesTab = ({ setTableData }: AttributesTabProps) => {
>
toggleIcon={<FilterIcon />}
=> {
const filter = value.toString();
setFilter(filter);
setData(
filter === "allGroups"
? attributes
: attributes.filter((attr) => attr.group === filter),
);
setFilter(value.toString());
toggleIsFilterTypeDropdownOpen();
}}
selections={filter === "allGroups" ? t(filter) : filter}
Expand Down Expand Up @@ -226,15 +237,8 @@ export const AttributesTab = ({ setTableData }: AttributesTabProps) => {
<DeleteConfirm />
<DraggableTable
keyField="name"
(nameDragged, items) => {
const keys = attributes.map((e) => e.name);
const newIndex = items.indexOf(nameDragged);
const oldIndex = keys.indexOf(nameDragged);
const dragged = attributes[oldIndex];
if (!dragged.name) return;

await executeMove(dragged, newIndex);
}}
>
restoreOrderOnDrop
actions={[
{
title: t("edit"),
Expand All @@ -249,7 +253,8 @@ export const AttributesTab = ({ setTableData }: AttributesTabProps) => {
},
{
title: t("delete"),
isActionable: ({ name }) => !RESTRICTED_ATTRIBUTES.includes(name!),
isActionable: ({ name }) =>
!isUpdating && !RESTRICTED_ATTRIBUTES.includes(name!),
onClick: (_key, _idx, component) => {
setAttributeToDelete(component.name);
toggleDeleteDialog();
Expand All @@ -271,7 +276,7 @@ export const AttributesTab = ({ setTableData }: AttributesTabProps) => {
displayKey: t("attributeGroup"),
},
]}
data={data ?? attributes}
data={visibleAttributes}
/>
</>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,41 +37,49 @@ export const UserProfileProvider = ({ children }: PropsWithChildren) => {
const { realm } = useRealm();
const { addAlert, addError } = useAlerts();
const { t } = useTranslation();
const [config, setConfig] = useState<UserProfileConfig | null>(null);
const [profile, setProfile] = useState<{
config: UserProfileConfig;
refreshCount: number;
}>();
const [refreshCount, setRefreshCount] = useState(0);
const [isSaving, setIsSaving] = useState(false);
const [pendingSaves, setPendingSaves] = useState(0);

useFetch(
() => adminClient.users.getProfile({ realm }),
(config) => setConfig(config),
[refreshCount],
(config) => setProfile({ config, refreshCount }),
[realm, refreshCount],
);

const save: SaveCallback = async (updatedConfig, options) => {
setIsSaving(true);
setPendingSaves((count) => count + 1);

try {
await adminClient.users.updateProfile({
...updatedConfig,
realm,
});

setIsSaving(false);
setRefreshCount(refreshCount + 1);
// Reload the saved profile because PUT responses may arrive out of order.
setRefreshCount((count) => count + 1);
addAlert(
t(options?.successMessageKey ?? "userProfileSuccess"),
AlertVariant.success,
);

return true;
} catch (error) {
setIsSaving(false);
addError(options?.errorMessageKey ?? "userProfileError", error);

return false;
} finally {
setPendingSaves((count) => count - 1);
}
};

const config = profile?.config ?? null;
const isSaving =
pendingSaves > 0 || refreshCount !== (profile?.refreshCount ?? 0);

return (
<UserProfileContext.Provider value={{ config, save, isSaving }}>
{children}
Expand Down
47 changes: 46 additions & 1 deletion js/apps/admin-ui/test/realm-settings/keys.spec.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import { test } from "@playwright/test";
import { expect, test } from "@playwright/test";
import { v4 as uuid } from "uuid";
import { toKeysTab } from "../../src/realm-settings/routes/KeysTab.tsx";
import { createTestBed } from "../support/testbed.ts";
import adminClient from "../utils/AdminClient.ts";
import { switchToggle } from "../utils/form.ts";
import { login } from "../utils/login.ts";
Expand All @@ -9,6 +11,7 @@ import { goToRealm, goToRealmSettings } from "../utils/sidebar.ts";
import {
assertRowExists,
clickRowKebabItem,
getRowByCellText,
searchItem,
} from "../utils/table.ts";
import {
Expand All @@ -19,6 +22,48 @@ import {
switchToFilter,
} from "./keys.ts";

test("Reorders key providers again while the first refresh is pending", async ({
page,
}) => {
await using testBed = await createTestBed();
const { realm } = testBed;
await login(page, { to: toKeysTab({ realm, tab: "providers" }) });

const names = page.getByTestId("provider-name-link");
await expect(names.nth(2)).toBeVisible();
const [first, second, third, ...remaining] = await names.allTextContents();
const expectedOrder = [third, second, first, ...remaining];
const refreshStarted = Promise.withResolvers<boolean>();
const releaseRefresh = Promise.withResolvers<void>();
const providersUrl = `**/admin/realms/${realm}/components/?type=org.keycloak.keys.KeyProvider`;
await page.route(
providersUrl,
async (route) => {
const response = await route.fetch();
refreshStarted.resolve(response.ok());
await releaseRefresh.promise;
await route.fulfill({ response });
},
{ times: 1 },
);

try {
await getRowByCellText(page, first).dragTo(getRowByCellText(page, third));
expect(await refreshStarted.promise).toBe(true);
await expect(names).toHaveText([second, third, first, ...remaining]);

const secondRefresh = page.waitForResponse(providersUrl);
await getRowByCellText(page, third).dragTo(getRowByCellText(page, second));
expect((await secondRefresh).ok()).toBe(true);
await expect(names).toHaveText(expectedOrder);
} finally {
releaseRefresh.resolve();
}

await page.reload();
await expect(names).toHaveText(expectedOrder);
});

test.describe.serial("Realm Settings - Keys", () => {
const realmName = `events-realm-settings-${uuid()}`;
const searchPlaceholder = "Search key";
Expand Down
Loading
0