Compare commits

...

1 Commits

Author SHA1 Message Date
Vinícius Lourenço
ea27937d6e fix(roles): keep the editor loading until the role's grants are in local state 2026-11-20 19:42:39 -03:00
2 changed files with 156 additions and 3 deletions

View File

@@ -1,13 +1,42 @@
import { QueryClient, QueryClientProvider } from 'react-query';
import ROUTES from 'constants/routes';
import { customRoleResponse } from 'mocks-server/__mockdata__/roles';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
import {
act,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import {
AUTHZ_CHECK_URL,
authzMockResponse,
setupAuthzAdmin,
} from 'lib/authz/utils/authz-test-utils';
import { getCurrentLocation } from 'lib/router/navigation';
import CreateEditRolePage from '../CreateEditRolePage';
jest.mock('@monaco-editor/react', () => ({
__esModule: true,
default: ({
value,
onChange,
}: {
value: string;
onChange: (next?: string) => void;
}): JSX.Element => (
<textarea
data-testid="monaco-editor"
value={value}
onChange={(e): void => onChange(e.target.value)}
/>
),
}));
const CUSTOM_ROLE_ID = '019c24aa-3333-0001-aaaa-111111111111';
const rolesApiBase = '*/api/v1/roles';
const VIEW_ROLE_URL = `${ROUTES.ROLE_DETAILS.replace(
@@ -408,4 +437,125 @@ describe('EditRolePage', () => {
);
});
});
describe('JSON view opened from the URL', () => {
const roleGrants = roleWithTransactionGroups.data.transactionGroups;
function renderJsonView(client?: QueryClient): ReturnType<typeof render> {
const page = <CreateEditRolePage />;
return render(
client ? (
<QueryClientProvider client={client}>{page}</QueryClientProvider>
) : (
page
),
undefined,
{
initialRoute: `/settings/roles/${CUSTOM_ROLE_ID}/edit?name=Custom%20Role&viewMode=json`,
},
);
}
function readBuffer(editor: HTMLElement): unknown {
return JSON.parse((editor as HTMLTextAreaElement).value);
}
it('shows the role grants when the role loads after the authz check', async () => {
server.use(
rest.get(`${rolesApiBase}/:id`, (_req, res, ctx) =>
res(ctx.delay(300), ctx.status(200), ctx.json(roleWithTransactionGroups)),
),
);
renderJsonView();
const editor = await screen.findByTestId('monaco-editor');
expect(readBuffer(editor)).toStrictEqual(roleGrants);
});
it('shows the role grants when the role loads before the authz check', async () => {
server.use(
rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
const payload = await req.json();
return res(
ctx.delay(300),
ctx.status(200),
ctx.json(
authzMockResponse(
payload,
payload.map(() => true),
),
),
);
}),
);
renderJsonView();
const editor = await screen.findByTestId('monaco-editor');
expect(readBuffer(editor)).toStrictEqual(roleGrants);
});
it('saves what was typed in the buffer even when the role refetches afterwards', async () => {
const updatedBodies: unknown[] = [];
let roleReads = 0;
server.use(
rest.get(`${rolesApiBase}/:id`, (_req, res, ctx) => {
roleReads += 1;
return res(
ctx.status(200),
ctx.json(
roleReads === 1
? roleWithTransactionGroups
: {
...roleWithTransactionGroups,
data: {
...roleWithTransactionGroups.data,
transactionGroups: [
{
objectGroup: {
resource: { kind: 'role', type: 'role' },
selectors: ['*'],
},
relation: 'update',
},
],
},
},
),
);
}),
rest.put(`${rolesApiBase}/:id`, async (req, res, ctx) => {
updatedBodies.push(await req.json());
return res(ctx.status(200), ctx.json({ status: 'success' }));
}),
);
const user = userEvent.setup();
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
renderJsonView(client);
const editor = await screen.findByTestId('monaco-editor');
await user.type(editor, '[[]', {
initialSelectionStart: 0,
initialSelectionEnd: (editor as HTMLTextAreaElement).value.length,
});
await act(async () => {
await client.invalidateQueries();
});
await waitFor(() => {
expect(roleReads).toBeGreaterThan(1);
});
await user.click(screen.getByTestId('save-button'));
await waitFor(() => {
expect(updatedBodies).toHaveLength(1);
});
expect(updatedBodies[0]).toMatchObject({ transactionGroups: [] });
});
});
});

View File

@@ -86,6 +86,9 @@ export function useCreateEditRolePageActions(
const { mutateAsync: updateRole, isLoading: isUpdating } =
useUpdateRolePermissions();
const isSaving = isCreating || isUpdating;
// Editors read their initial value once, so stay loading until the fetched
// role has been copied into local state.
const isSeedingFromRole = !!rolePermissionsData && !isInitialized;
useEffect(() => {
if (rolePermissionsData && !isInitialized) {
@@ -229,7 +232,7 @@ export function useCreateEditRolePageActions(
setEditorMode: handleModeChange,
resources: localResources,
setResources: handleResourcesChange,
isLoading: isLoadingPermissions,
isLoading: isLoadingPermissions || isSeedingFromRole,
isSaving,
hasUnsavedChanges,
handleSave,